在 Flutter 应用程序屏幕之间传递数据或参数的最佳方式是什么? [英] What is the best way to pass data or arguments between flutter app screens?

查看:33
本文介绍了在 Flutter 应用程序屏幕之间传递数据或参数的最佳方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了将参数从一个屏幕发送到另一个屏幕,我必须将此参数设置为小部件类中的一个字段.由于将许多参数传递给多个小部件,我认为这可能会导致更大的应用程序出现问题.

在屏幕之间有效传递数据的最佳方式是什么?

解决方案

通常最好的方法是使用应用状态管理.您在切换路线之前编辑状态并在新屏幕上阅读状态.如果通过持久性完成,这还有一个好处是能够在关闭后将您的应用恢复到最后一个状态(这在手机上经常发生).

根据您的应用状态的复杂性,您可以使用 Flutter 内置的状态管理或类似 redux 的插件.

Redux 需要更多样板代码,但也提供了更大的灵活性,并且适用于经常需要的非常大的应用程序.

这里有一些关于这个主题的有趣文章.

状态管理官方文档

Redux 与否

帮助选择状态管理

替代方案是在路线导航上传递参数.这可以作为路由字符串的一部分(不适用于静态路由字符串)或使用 MaterialPageRoute 完成,例如(参见这个答案).

还有一个包可以让传递参数变得容易:https://pub.dartlang.org/packages/navigate.

导航包的示例如下所示(取自 github issue):

 Map arg = {"transactionType":TransactionType.fromLeft,"replaceRoute":ReplaceRoute.thisOne};Navigate.navigate(上下文,家",transactionType:TransactionType.fromLeft ,replaceRoute: ReplaceRoute.thisOne,arg: arg);

In order to send an argument from one screen to the other I have to set this argument as a field in the widgets class. With many arguments being passed down to several widgets I think this might cause a problem for bigger applications.

What is the best way to pass data between screens efficiently?

解决方案

Typically the best way is to use app state management. You edit the state before switching routes and read the state on the new screen. If done with persistence this also has the benefit of being able to restore your app to the last state after being closed (which happens frequently on phones).

Depending on the complexity of your app state you could use the flutter built in state management or an addon like redux.

Redux requires more boilerplate coding but also offers more flexibility and for very large apps that is often required.

Here are a few interesting articles about the subject.

Official docs for state management

Redux or not

Help with choosing state management

Alternatives are to pass arguments on route navigation. This can be done either as part of the route string (which doesn't work with static route strings) or with a MaterialPageRoute for example (see this answer).

There is also package that makes passing parameters easy: https://pub.dartlang.org/packages/navigate.

An example with the navigate package looks like this (taken from this github issue):

  Map arg =  {"transactionType":TransactionType.fromLeft,"replaceRoute":ReplaceRoute.thisOne};
    Navigate.navigate(context,
                          "home",
                          transactionType:TransactionType.fromLeft ,
                          replaceRoute: ReplaceRoute.thisOne,
                          arg: arg
                          );

这篇关于在 Flutter 应用程序屏幕之间传递数据或参数的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆