flutter - 在 Flutter 中将数据从一个屏幕传递到另一个屏幕是 null
问题描述
我有两个屏幕,从一个我想将标题字符串传递到另一个屏幕。此标题可以登录或注册,在第一个屏幕中预先确定。我试过的:
Container(
child: RaisedGradientButton(
onPressed: () {
print('Login clicked');
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
MyApp(
formMode: FormMode.LOGIN,
screenTitle: "Login",
)
),
);
},
textButton: "Login",
height: 55,
width : 200.0,
buttonTitleColor: Colors.white,
buttonBackgroundColor: Colors.red,
)
),
下面是带有初始化步骤的第二个屏幕:
enum FormMode { LOGIN, SIGNUP }
void main() {
runApp(
MaterialApp(
home: StatelessLanding(),
),
);
}
class MyApp extends StatelessWidget{
// In the constructor, require a Todo
final FormMode formMode;
final String screenTitle;
MyApp({Key key, @required this.formMode, @required this.screenTitle})
: super(key: key);
@override
Widget build(BuildContext context){
return MyAppStateFul();
}
}
class _MyAppStateFulState extends State<MyAppStateFul> {
FormMode formMode;
String screenTitle;
_MyAppStateFulState(FormMode formMode, String screenTitle) {
this.formMode = formMode;
this.screenTitle = screenTitle;
}
}
这是我使用屏幕标题的地方:
@override
Widget build(BuildContext context) {
var screenTitle = "Login";
print('screen title is $widget.screenTitle');
print('screen title is $this.screenTitle');
print('screen title is $screenTitle');
}
能否请高手帮帮我。谢谢
解决方案
该代码有点难以理解,但是看起来您忘记将类传递screenTitle
给MyApp
小MyAppStateful
部件。
在您上面列出的代码中,您有以下无状态小部件:
class MyApp extends StatelessWidget{
// In the constructor, require a Todo
final FormMode formMode;
final String screenTitle;
MyApp({Key key, @required this.formMode, @required this.screenTitle}) : super(key: key);
@override
Widget build(BuildContext context) {
return MyAppStateFul();
}
}
对我来说,您似乎必须将 传递screenTitle
给MyAppStateFul
构造函数才能使其在您的有状态小部件中可用,如下所示:
@override
Widget build(BuildContext context) {
return MyAppStateFul(screenTitle);
}
当然,这也需要您更改MyAppStateFul
构造函数以接受screenTitle
参数(如果还没有的话)。
我认为这应该为您解决。
推荐阅读
- javascript - React Router 仅在刷新页面后才起作用
- angular - 无法理解,为什么 SVG 的某些部分在从角度组件生成时最初没有绘制?
- typescript - TypeScript 中的泛型比较
- javascript - JSON.stringify 在模板文字中的 map 方法中不起作用
- c++ - 重温:C++中静态数组和动态数组的区别?
- java - 无法反序列化 HashSet 的实例
- python - 如何将看起来像列表的文件变成列表?
- python - 使用 bs4 beautifulSoup 查找特定元素
- html - 使用 css 将 3 个 div 粘合在一起
- php - 使用 JSON_ARRAYAGG 或 JSON_OBJECT 时 PHP5.4 和 MySQL 5.7.32 “中止连接”