适当的方式布局嵌套页面和传递数据?



我有3页:

> A page where the user enters their desired display name
> A page where the user enters their desired username
> A page where the user enters their desired password

我需要能够将数据(显示名,用户名,密码)传递到密码页面,其中有一个最终的"提交"按钮,该按钮将实际创建用户的帐户。

到目前为止,我所做的是创建3个单独的小部件,我调用Navigator.push来在它们之间切换。

然而,根据这个答案,提供者库看起来并没有很好地处理导航推送。

所以我想知道我应该如何布局我的小部件,使它的工作,因为它应该与provider?

您的嵌套页面看起来非常好,这里有两种可能的方法,其中一种是您提到的使用提供者。相反,您可以在Navigator中使用内置参数。Push将数据向下传递到小部件树。

可能有点"脏"。但它应该在您的情况下工作得很好,因为没有太多的数据和嵌套页面要传递。

首先需要定义需要传入的参数,例如:

// You can pass any object to the arguments parameter.
// In this example, create a class that contains both
// a customizable title and message.
class ScreenArguments {
final String displayName;
final String username;
ScreenArguments({this.displayName, this.username});
}

接下来,像这样传递所需的数据:

Navigator.pushNamed(
context,
ExtractArgumentsScreen.routeName,
arguments: ScreenArguments(
displayName: 'Your Display Name',
),

然后在下一个屏幕上,您需要在小部件树构建上下文中提取参数:

final args = ModalRoute.of(context)!.settings.arguments as ScreenArguments;

通过此方法访问数据并将其存储在嵌套页面的新变量中:

String displayName = args.displayName

重复此步骤,直到最终的嵌套页面包含用户名参数。提取这些参数,现在就可以在最终的嵌套页面上向数据库提交表单了

示例流:

> A page where the user enters their desired display name
- Pass this argument through Nagivator.push
> A page where the user enters their desired username
- Store the displayName argument as variable
- Pass both displayName and username argument through Navigator.push
> A page where the user enters their desired password
- Store both displayName and username argument as variable
- Retrieve all input variables and pass into submit form

有关如何正确地通过Navigator

传递参数的更多细节,您可以参考此文档。

最新更新