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

我想到的一个可能的解决方案是在一个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的公共成员.然后在一个State中使用GlobalKeycurrentState属性来获得对另一个State的引用.现在,您可以通过public成员访问创建的对象.(注意:这种模式限制了State的可测试性和封装性,所以要谨慎使用.)
  2. 这两个小部件都可以有一个扩展InheritedWidget的祖先小部件,它们用来查找创建的对象.
  3. 这两个小部件都可以在其构造函数(如ValueNotifier)中传递模型参数.他们可以使用此对象来读写该值.

如果您深入了解用例的更多细节,我们可以帮助您 Select 有意义的模式.

以下是实现选项#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;
          });
        },
      ),
    );
  }
}

Flutter相关问答推荐

获取屏幕大小的滚动视图与动态大小?

所需引用Firebase处不存在任何对象

如何在FiRestore中正确编写OR查询

允许冻结在初始化时使用工厂

将目标平台设置为Flutter 构建

我想在Flutter中画一个箭头,但我似乎无法填满空间

Flutter 文件拾取器Android SingleInstance模式它返回的文件路径为空

Firestore 不会取代 map

Flutter - Riverpod 2.0 - 如何访问 onDispose 回调?

如何动态获取任何小部件的像素?

如何使Flutter 屏幕无法关闭?

Android 模拟器在 Apple M2 芯片 EXC_BAD_ACCESS / KERN_INVALID_ADDRESS 上随机崩溃

Flutter - 展开图标无法正常工作

使用 Riverpod 和 copyWith 方法更新数据类中列表中变量的值

为什么 appBar 小部件在 flutter 中不是常量

访问 AsyncSnapshot 中的嵌套属性

Flutter snapShot.hasData 为假但响应有数据

如何在 Flutter 中创建 Facebook 创建帖子屏幕?

Flutter:font_awesome_icon pro 版报错?如何设置 font_awesome 克隆仓库的路径?

Textfield 和 MasonryGrid 给出错误(垂直视口的高度没有限制)