0

What is the best way to pass variable (photoUrl) to a Widget? Adding widget inside state class it says: Only static members can be accessed in initializers.

Changing method to static neither solves my issue.

class _ABState extends State<AB> {
  int _selectedPage = 0;
  String photoUrl; /* Value set in initState()*/

  /* To switch between pages */
  final _pageOptions = [
    Text('Page 1'),
    accountPage(), /* Page 2 */
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _pageOptions[_selectedPage],
    );
  }
}

/* Widget outside class requires photoUrl */
Widget accountPage() {
  return Container(
    decoration: BoxDecoration(
      image: DecorationImage(
        image: NetworkImage(photoUrl),
      ),
    ),
  );
}
0

1 Answer 1

1

You are calling accountPage() at the initializer, but photoUrl is set only on initState(), so even if accountPage() had access to photoUrl, it would get the wrong value.

I suggest the following:

class _ABState extends State<AB> {
  int _selectedPage = 0;
  String photoUrl;
  List<Widget>_pageOptions;

  @override
  void initState() {
    super.initState();
    photoUrl = "<PLACE_YOUR_VALUE>";
    _pageOptions = [
      Text('Page 1'),
      accountPage(photoUrl),
    ];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _pageOptions[_selectedPage],
    );
  }
}

Widget accountPage(String photoUrl) {
  return Container(
    decoration: BoxDecoration(
      image: DecorationImage(
        image: NetworkImage(photoUrl),
      ),
    ),
  );
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.