Redux
似乎是用于移动应用程序开发的非常好的架构。但是,移动应用程序具有一些Web应用程序不常见的功能。
就我而言,我想在某个特定屏幕开始后启动长轮询/监视位置/跟踪文件系统(监视外部状态的任何操作),并在屏幕关闭时停止。
假设我们有一个函数,该函数可以随着时间的推移发出多个事件。
Stream<Event>monitor();
我只想在某些特定屏幕处于活动状态时收听此功能。
做到这一点的最佳方法是什么?
答案 0 :(得分:2)
假设您有3个页面:“ PageHome.dart”,“ Page1.dart”,“ Page2.dart”。
创建另一个dart文件“ GlobalVariables.dart”,在该文件中创建一个类gv,为这三个页面创建静态redux“商店”。
在gv中创建静态var strCurPage。
假定每个页面都有一个变量,该变量将由外部事件更改,请将它们在gv中也声明为静态var。
GlobalVariables.dart中的代码:
import 'package:redux/redux.dart';
enum Actions {
Increment
}
// The reducer, which takes the previous count and increments it in response to an Increment action.
int reducerRedux(int intSomeInteger, dynamic action) {
if (action == Actions.Increment) {
return intSomeInteger + 1;
}
return intSomeInteger;
}
class gv {
static Store<int> storePageHome =
new Store<int>(reducerRedux, initialState: 0);
static Store<int> storePage1 =
new Store<int>(reducerRedux, initialState: 0);
static Store<int> storePage2 =
new Store<int>(reducerRedux, initialState: 0);
static String strCurPage = 'PageHome';
static String strPageHomeVar = 'PageHomeInitialContent';
static String strPage1Var = 'Page1InitialContent';
static String strPage2Var = 'Page2InitialContent';
}
在所有其他dart文件中导入“ GlobalVariables.dart”。
在导航到新页面之前,例如从PageHome到Page1,设置:
gv.strCurPage ='Page1';
void thisFunctionCalledByExternalEvent(strPage1NewContent, strPage2NewContent) {
gv.strPage1Var = strPage1NewContent;
gv.strPage2Var = strPage2NewContent;
if (gv.strCurPage == 'Page1') {
// Dispatch storePage1 to refresh Page 1
storePage1.dispatch(Actions.Increment);
} else if (gv.strCurPage == 'Page2') {
// Dispatch storePage2 to refresh Page 2
storePage2.dispatch(Actions.Increment);
} else {
// Do not need to refresh page if user currently navigating other pages.
// so do nothing here
}
}
我不知道这是否是最好的方法,但是使用redux和GlobalVariables.dart,我可以:
了解用户当前正在导航的页面。
更改页面的内容,即使在事件触发时用户不在该页面上也是如此。 (但是内容将在用户稍后导航到该页面时显示)
在事件触发时,无论用户导航到哪个页面,都强制用户转到特定页面。