简体   繁体   中英

Passing parameter to stateful widget

I tried to pass a parameter uid to a stateful widget like this:

class BoardBody extends StatefulWidget {
  String uid;
  BoardBody({
    @required this.uid,
  });

When I try to access it at initstate, I got a null. However, if I hot reload the page, the value widget.uid is printed out. Did I do anything wrong? I have like to have the uid available so that I can pull some data from the DB.

  @override
  void initState() {
    // TODO: implement initState
    print("user id");
    print(widget.uid);
    super.initState();
  }

I have passed the uid data to the widget like this:

BoardBody(uid: uid)

I think this is due to you used routes in the main.dart. Thus, initState() loads after it builds Scaffold.

If you try to build the screen/Widget with MaterialPageRoute(builder: (context) => BoardBody()), you'll see the result (printed uid).

Try this.

@override
  void initState() {
    super.initState();
    // TODO: implement initState
    print("user id");
    print(widget.uid);
  }

So super.initState() should be above your print. This should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM