Passing data to StatefulWidget and accessing it in it's state in Flutter

前端 未结 5 2229
星月不相逢
星月不相逢 2020-11-30 22:25

I have 2 screens in my Flutter app: list of records and screen for creating and editing records.

If I pass object to second screen that means I am going to edit this

5条回答
  •  暖寄归人
    2020-11-30 22:45

    Full Example

    You don't need to pass parameters to State using it's constructor. You can easily access these using widget.myField.

    class MyRecord extends StatefulWidget {
      final String recordName;
      const MyRecord(this.recordName);
    
      @override
      MyRecordState createState() => MyRecordState();
    }
    
    class MyRecordState extends State {
      @override
      Widget build(BuildContext context) {
        return Text(widget.recordName); // Here you direct access using widget
      }
    }
    

    Pass your data when you Navigate screen :

     Navigator.of(context).push(MaterialPageRoute(builder: (context) => MyRecord("WonderWorld")));
    

提交回复
热议问题