从 Navigator.pop 接收地图

ven*_*ick 5 dart flutter

我有一个页面,用户在初始登录后输入他的用户名和生日,然后我想返回并在上一个屏幕中使用这些数据。

在屏幕 2 中:

Navigator.pop(context, {'username':username, 'birthday':birthday});
Run Code Online (Sandbox Code Playgroud)

在屏幕 1 中:

final userData = await Navigator.pushNamed(context, '/setup_profile');
Run Code Online (Sandbox Code Playgroud)

Final/var 适用于单个变量(例如 String),但不适用于映射,因为它不知道返回对象实际上是映射。

当然,如果不指定它是一个 Map 就不能使用userData['username'],我不明白如何指定它。

我试过了

Map<String, dynamic> userData = await Navigator.pushNamed(context, '/register');
Run Code Online (Sandbox Code Playgroud)

它不起作用我收到此错误:

Unhandled Exception: type 'MaterialPageRoute<dynamic>' is not a subtype of type 'Route<Map<String, dynamic>>'
Run Code Online (Sandbox Code Playgroud)

然后我尝试了

Route route = await Navigator.pushNamed(context, '/register');
Map<String, dynamic> data = route.currentResult;
Run Code Online (Sandbox Code Playgroud)

这不太有效,我遇到了同样的错误

Unhandled Exception: type 'MaterialPageRoute<dynamic>' is not a subtype of type 'Route<Route<dynamic>>'
Run Code Online (Sandbox Code Playgroud)

简而言之,我想在 Screen1 中使用返回的 Map。

主要问题是我不知道如何指定返回数据,它是自定义类、地图、列表还是其他内容。如何指定 Navigator.pop 的返回类型?

Jos*_*man 3

Navigator.pop()允许您提供可选的泛型类型参数。

使用 正确传递参数Navigator(而不仅仅是方法)的一个好习惯.pop()是创建页面/屏幕参数对象。

screen1.dart

class Screen1Arguments {
  Map<String, dynamic> someMapVariable;

  Screen1Arguments(this.someMapVariable);
}
Run Code Online (Sandbox Code Playgroud)

Screen2根据您的设置,您现在可以从中检索值,Screen1如下所示:

screen1.dart

RaisedButton(
  child: Text('Open Second Screen'),
  onPressed: () async {
    final Screen1Arguments args = await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => Screen2(),
      ),
    );
    print("args ${args.someMapVariable}");
  },
),
Run Code Online (Sandbox Code Playgroud)

鉴于现在您正在使用Screen1Arguments该方法的类型化参数.pop(),您现在可以方便地Map在您的 中传递变量Screen2

screen2.dart

RaisedButton(
  child: Text('Close Screen'),
  onPressed: () {
    Navigator.pop(
      context,
      Screen1Arguments(
        {
          "key1": "value1",
          "key2": "value2",
          "key3": 3,
        },
      ),
    );
  },
),
Run Code Online (Sandbox Code Playgroud)

此外,您仍然可以添加具有不同数据类型(除了Map)的其他变量,就像应用程序中的任何其他模型类或对象一样:

class Screen1Arguments {
  Map<String, dynamic> someMapVariable;
  String username;
  Date birthday;

  Screen1Arguments(this.someMapVariable, this.username, this.birthday);
}
Run Code Online (Sandbox Code Playgroud)

进一步阅读