首页 > 解决方案 > 在 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');
}

能否请高手帮帮我。谢谢

标签: flutterdartmaterialpageroute

解决方案


该代码有点难以理解,但是看起来您忘记将类传递screenTitleMyAppMyAppStateful部件。

在您上面列出的代码中,您有以下无状态小部件:

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();
  }
}

对我来说,您似乎必须将 传递screenTitleMyAppStateFul构造函数才能使其在您的有状态小部件中可用,如下所示:

  @override
  Widget build(BuildContext context) {
    return MyAppStateFul(screenTitle);
  }

当然,这也需要您更改MyAppStateFul构造函数以接受screenTitle参数(如果还没有的话)。

我认为这应该为您解决。


推荐阅读