dart - 如何在 flutter 的另一个有状态小部件中访问在一个有状态小部件中创建的对象

我被困在我的项目中,我在 flutter 中创建了两个有状态的小部件作为两个不同的 dart 文件。现在,我必须在第二个小部件中访问在第一个小部件中创建的对象的实例,但我不太确定在创建小部件时如何在 flutter 中做到这一点。

我想到的一种可能的解决方案是在一个 dart 文件中声明两个小部件,而不是在两个布局中声明两个 dart 文件,但我很好奇我们是否可以通过在两个单独的 dart 文件中声明来做到这一点。

我发布这些文件只是为了重现问题。

main.dart

 import 'package:flutter/material.dart';
 import 'package:untitled2/models.dart';
 import 'package:untitled2/secondwidget.dart';

void main() {
 runApp(new MaterialApp(
     home: new MyApp(),
 ),);
}

class MyApp extends StatefulWidget {
@override
_MyAppState createState() => new _MyAppState();
  }

      class _MyAppState extends State<MyApp> {
 final TextEditingController _nameController = new TextEditingController();
 final TextEditingController _emailIdController = new 
 TextEditingController();
 final TextEditingController _passwordController = new 
 TextEditingController();
 final TextEditingController _confirmPasswordController = new 
 TextEditingController();

 MyModel myModel = new MyModel();

 @override
 Widget build(BuildContext context) {
  return new MaterialApp(
  home: new Scaffold(
    body: new ListView(

      children: <Widget>[
        new Container(
          child: new TextFormField(
            decoration: new InputDecoration(
              labelText: 'Enter your Name'
            ),
            controller: _nameController,
            onSaved: (String value){myModel.name = value;} ,
          ),
        ),
        new Container(
          child: new TextFormField(
            decoration: new InputDecoration(
                labelText: 'EmailId'
            ),
              controller: _emailIdController,
              onSaved: (String value){myModel.emailId = value;}
          ),
        ),
        new Container(
          child: new TextFormField(
            decoration: new InputDecoration(
                labelText: 'Password'
            ),
              controller: _passwordController,
              onSaved: (String value){myModel.password = value;}
          ),
        ),
        new Container(
          child: new TextFormField(
            decoration: new InputDecoration(
                labelText: 'Confirm Password'
            ),
            controller: _confirmPasswordController,

          ),
        ),
        new Container(
          child: new FlatButton(
            onPressed: ((){

              Navigator.push(context, new MaterialPageRoute(builder: (_) => 
         new SecondScreen(),),);

            }),
            child: new Text('Save'),),
        ),



      ],


      ),
     ),
    );
   }
  }

models.dart

class MyModel {

String name;
String emailId;
String password;

  }

secondwidget.dart

 import 'package:flutter/material.dart';


 class SecondScreen extends StatefulWidget {
 @override
 _SecondScreenState createState() => new _SecondScreenState();
}

class _SecondScreenState extends State<SecondScreen> {
@override
Widget build(BuildContext context) {
return new MaterialApp(
  home: new Scaffold(
    body: new ListView(

      children: <Widget>[
        new Container(
          child: new TextFormField(
            decoration: new InputDecoration(
                labelText: 'Enter address'
            ),
          ),
        ),
        new Container(
          child: new TextFormField(
            decoration: new InputDecoration(
                labelText: 'Address Line 2'
            ),
          ),
        ),
        new Container(
          child: new TextFormField(
            decoration: new InputDecoration(
                labelText: 'Address Line 3'
            ),
          ),
        ),
        new Container(
          child: new TextFormField(
            decoration: new InputDecoration(
                labelText: 'POST CODE'
            ),
          ),
        ),

        new Container(
          child: new TextFormField(
            decoration: new InputDecoration(
                labelText: 'Mobile Number'
            ),
          ),
        ),
        new Container(
          child: new FlatButton(
              onPressed: ((){


                //I want to push the data captured from main.dart and from 
                            //secondwidget.dart into database
     // I want to use the instance of MyModel from main.dart here to save 
      // the data captured from the first screen and this one into database

              }),
              child: new Text('Save'),),
        ),


      ],


    ),
  ),
);
}
}

最佳答案

根据您的用例,有很多方法可以做到这一点。这里有几个选项:

  1. 您可以将创建的对象公开为 State 的公共(public)成员。然后使用 GlobalKeycurrentState 属性在一个 State 中获取对另一个 State 的引用。现在您可以通过公共(public)成员访问创建的对象。 (注意:这种模式限制了 State 的可测试性和封装性,因此请谨慎使用。)
  2. 两个小部件都可以有一个祖先小部件,它扩展了 InheritedWidget他们用来查找创建的对象。
  3. 两个小部件都可以在其构造函数中传递模型参数,例如 ValueNotifier .他们可以使用此对象来读取和写入值。

如果您更详细地了解您的用例,我们可以帮助您选择一种有意义的模式。

这是一些实现选项 #1 的代码。

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

final key = new GlobalKey<MyStatefulWidget1State>();

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        body: new Column(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: <Widget>[
            new MyStatefulWidget1(key: key),
            new MyStatefulWidget2(),
          ],
        ),
      ),
    );
  }
}

class MyStatefulWidget1 extends StatefulWidget {
  MyStatefulWidget1({ Key key }) : super(key: key);
  State createState() => new MyStatefulWidget1State();
}

class MyStatefulWidget1State extends State<MyStatefulWidget1> {
  String _createdObject = "Hello world!";
  String get createdObject => _createdObject;

  @override
  Widget build(BuildContext context) {
    return new Center(
      child: new Text(_createdObject),
    );
  }
}

class MyStatefulWidget2 extends StatefulWidget {
  State createState() => new MyStatefulWidget2State();
}

class MyStatefulWidget2State extends State<MyStatefulWidget2> {
  String _text = 'PRESS ME';

  @override
  Widget build(BuildContext context) {
    return new Center(
      child: new RaisedButton(
        child: new Text(_text),
        onPressed: () {
          setState(() {
            _text = key.currentState.createdObject;
          });
        },
      ),
    );
  }
}

https://stackoverflow.com/questions/46542768/

相关文章:

dart - Flutter:在简历上更新小部件?

flutter - 如何在 Flutter 中更改状态栏和应用栏颜色?

visual-studio-code - Visual Studio 代码中的 Flutter 检查

dart - Flutter:使用按钮更改标签栏 View 中的当前标签

dart - 在所有页面 Flutter 中持久化 AppBar Drawer

flutter - 没有 ScrollView 的刷新指示器

flutter - 如何让应用程序保持清醒?

testing - Flutter 测试的代码覆盖率数据如何显示?

dart - 如何查看已安装的 Flutter 版本?

flutter - 如何在 flutter 中听焦点变化?