首页 > 解决方案 > Flutter:在屏幕之间传递多个数据

问题描述

我是 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

解决方案


一切看起来都很好,但是您需要将 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="";

推荐阅读