Thoxh
Thoxh

Reputation: 149

The instance member 'X' can't be accessed in an initializer. - Flutter, VoidCallback Function

So as you might see I'm trying to use the function addUser of my StatefulWidget in my StatelessWidget. The only problem is the following error add HomeWidget(addUser: addUser),: The instance member 'addUser' can't be accessed in an initializer. Can you help me solving that problem? Thanks a lot.

My StatefulWidget:


class _HomeStatefulState extends State<HomeStateful> {

  void addUser() {
   //do something
  }

  final List<Widget> _children = [
    HomeWidget(addUser: addUser),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: _children[_currentIndex],
      bottomNavigationBar: BottomNavigationBar(
          currentIndex: _currentIndex,
          onTap: onTabTapped,
          items: [
            BottomNavigationBarItem(
              icon: Icon(Icons.home),
              title: Text("Home"),
              backgroundColor: Colors.blue,
            ),
          ]),
    );
  }
}

The StatelessWidget:


class HomeWidget extends StatelessWidget {
  const HomeWidget({Key key, @required this.addUser}) : super(key: key);
  final VoidCallback addUser;

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: [
          SafeArea(
              child: Column(
            children: [
              Padding(
                child: FlatButton(
                  onPressed: addUser,
                ),
              ),
            ],
          )),
        ],
      ),
    );
  }
}


Upvotes: 1

Views: 281

Answers (2)

FDuhen
FDuhen

Reputation: 4826

Your problem here is that you're trying to access a function of your Widget before it has been initialised.
If you want to build a "default" setup for your Widget, a good way is to use the initState method.

List<Widget> _children;
  
  @override
  void initState() {
    super.initState();
    _children = [
      HomeWidget(addUser: addUser),
    ];
  }

Upvotes: 0

Patrick O&#39;Hara
Patrick O&#39;Hara

Reputation: 2229

You cannot access addUser before the object is initialised. Move the reference in the constructor, e.g.

  List<Widget> _children;

  _HomeTestState() {
    _children = [
      HomeWidget(addUser: addUser),
    ];
  }

Upvotes: 1

Related Questions