flutter - 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 个或更多数据时失败。
在屏幕之间发送多个数据的正确方法是什么?
解决方案
一切看起来都很好,但是您需要将 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="";
推荐阅读
- java - Java:哈希映射到嵌套的 JSON 对象
- reactjs - TypeError: test.each 不是 React 测试中的函数
- c++ - 为嵌套枚举类声明友元插入运算符(运算符 <<)
- python - 我需要帮助将此 REST API Curl 命令转换为 Python 请求
- javascript - RequiredJS 加载 JS 文件失败
- .htaccess - 除少数文件和文件夹外,禁止将所有请求重定向到 403
- c# - 如何在 Windows 事件查看器中删除和创建日志
- sql - Oracle SQL 查询 Group By with having 子句
- python - 字节模式的正则表达式匹配会产生不寻常的结果 - '.' 不等于 [\x00-\xff]
- html - getBoundingClientRect() 为 Chrome 中的嵌套 SVG 返回错误值