how to access an object created in one stateful widget in another stateful widget in flutter

前端 未结 3 1115
予麋鹿
予麋鹿 2020-12-08 04:41

I am stuck in my project where I have two stateful widgets created in flutter as two different dart files. Now, I have to access the instance of an object created in first w

3条回答
  •  一向
    一向 (楼主)
    2020-12-08 04:53

    You can pass the model when you construct SecondScreen widget.

    1. Add model to SecondScreen constructor:

      class SecondScreen extends StatefulWidget {
        final MyModel myModel;
      
        SecondScreen(MyModel myModel, {Key key}):
            super(key: key);
      ...
      }
      
    2. Pass model when you construct SecondScreen in main.dart

      Navigator.push(context, new MaterialPageRoute(builder: (_) => 
        new SecondScreen(model)));
      
    3. Now you can access model in _SecondScreenState via widget.myModel

提交回复
热议问题