我是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个或更多数据时失败。
在屏幕之间发送多个数据的正确方法是什么?
答案 0 :(得分:1)
考虑通过路由参数传递参数。在此处https://flutter.dev/docs/cookbook/navigation/navigate-with-arguments
引用官方文档答案 1 :(得分: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="";