【问题标题】:Flutter: Passing multiple data between screensFlutter:在屏幕之间传递多个数据
【发布时间】:2019-06-20 03:04:06
【问题描述】:

我是 Flutter 的新手。我正在尝试将多个数据发送到另一个屏幕:

// screen1.dart
..
Expanded(
  child: RaisedButton(
    onPressed: () {
      Navigator.push(context,
        MaterialPageRoute(
          builder: (context) => new Screen2(name: thing.name, email: thing.email, address: thing.address, etc..),
        ),
      );
    },
  ),
),
..


// screen2.dart

class Screen2 extends StatefulWidget{
  Screen2({this.name}, {this.email}, {this.address}, etc..);
  final String name;
  final String email;
  final String address;
  // etc
  @override
  State<StatefulWidget> createState() { return new Screen2State();}
}

class Screen2State extends State<Screen2> {
  Widget build(BuildContext context) {
    return new WillPopScope(
      ..
      child: Scaffold(
        ..
        new Row(
          children: <Widget>[
            new Text(widget.name),
            new Text(widget.email),
            new Text(widget.address),
            etc..
          ],
        ),
      )
    )
}

但我得到了错误:A non-null String must be provided to a Text widget.

数据是从 TextEditingControllers 传输的。当只有 1 个数据传输时它可以工作,但当有 2 个或更多数据时它会失败。

在屏幕之间发送多个数据的正确方法是什么?

【问题讨论】:

    标签: flutter


    【解决方案1】:

    一切看起来都很好,但你需要在 Screen 2 类的构造函数中更改为这个

    Screen2({this.name, this.email, this.address, etc..});
    

    修改代码

    // screen1.dart
    ..
    Expanded(
      child: RaisedButton(
        onPressed: () {
          Navigator.push(context,
            MaterialPageRoute(
              builder: (context) => new Screen2(name: thing.name, email: thing.email, address: thing.address, etc..),
            ),
          );
        },
      ),
    ),
    ..
    
    
    // screen2.dart
    
    class Screen2 extends StatefulWidget{
     Screen2({this.name, this.email, this.address, etc..});
      final String name;
      final String email;
      final String address;
      // etc
      @override
      State<StatefulWidget> createState() { return new Screen2State();}
    }
    
    class Screen2State extends State<Screen2> {
      Widget build(BuildContext context) {
        return new WillPopScope(
          ..
          child: Scaffold(
            ..
            new Row(
              children: <Widget>[
                new Text(widget.name),
                new Text(widget.email),
                new Text(widget.address),
                etc..
              ],
            ),
          )
        )
    }
    

    注意:文本小部件不会接受空值,因此请确保您传递了所有值。或者你可以用默认值初始化变量为空白

    final String name="";
    final String email="";
    final String address="";
    

    【讨论】:

      【解决方案2】:

      考虑通过路由参数传递参数。参考官方文档https://flutter.dev/docs/cookbook/navigation/navigate-with-arguments

      【讨论】:

        猜你喜欢
        • 2021-03-01
        • 2019-05-20
        • 1970-01-01
        • 2019-11-01
        • 2021-03-05
        • 1970-01-01
        • 2018-01-10
        • 1970-01-01
        相关资源
        最近更新 更多