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

moonvader picture moonvader · May 11, 2018 · Viewed 78.6k times · Source

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 and if I pass null it means that I am creating new item. Editing screen is Stateful widget and I am not sure how to use this approach https://flutter.io/cookbook/navigation/passing-data/ for my case.

class RecordPage extends StatefulWidget {
  final Record recordObject;

  RecordPage({Key key, @required this.recordObject}) : super(key: key);

  @override
  _RecordPageState createState() => new _RecordPageState();
}

class _RecordPageState extends State<RecordPage> {
  @override
  Widget build(BuildContext context) {
   //.....
  }
}

How can I access recordObject inside _RecordPageState?

Answer

dhuma1981 picture dhuma1981 · May 11, 2018

To use recordObject in _RecordPageState, you have to just write widget.objectname like below

class _RecordPageState extends State<RecordPage> {
  @override
  Widget build(BuildContext context) {
   .....
   widget.recordObject
   .....
  }
}