Sukhchain Singh
Sukhchain Singh

Reputation: 844

Pass variable to a Widget outside Stateful class

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),
      ),
    ),
  );
}

Upvotes: 0

Views: 36

Answers (1)

Hugo Passos
Hugo Passos

Reputation: 8427

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),
      ),
    ),
  );
}

Upvotes: 1

Related Questions