alibaba / fish-redux

An assembled flutter application framework.
https://github.com/alibaba/fish-redux
Apache License 2.0
7.33k stars 843 forks source link

initState方法需要BuildContext #430

Closed wangbo4020 closed 5 years ago

wangbo4020 commented 5 years ago

一些国际化字符串需要从资源中获取,但是在initState中获取不到BuildContext。

zjuwjf commented 5 years ago

你可以通过buildPage中传入参数BuildContext,然后在initState方法中可以获取。

wangbo4020 commented 5 years ago

page中的 initState 中的context是可以传的, 但是Lifecyle回调中的initState中的ctx.context没法正常使用。 在initState之后的生命周期context正常。 例如以下代码,在Lifecyle.initState使用S.of(ctx.context),和AppData.of(ctx.context)。

class AppData extends InheritedWidget {
  static AppData of(BuildContext context) {
    return context.inheritFromWidgetOfExactType(AppData);
  }

  Repository repo;

  AppData({Key key, Widget child}) : super(key: key, child: child) {
    this.repo = Repository("initial");
  }

  @override
  bool updateShouldNotify(AppData old) {
    return repo != old.repo;
  }
}

Main: void main() => runApp(AppData(child: createApp());

App: 我们是否需要利用 MaterialPageRoute Builder回传的BuildContext呢。

return MaterialApp(
    title: 'Fluro',
    debugShowCheckedModeBanner: false,
    theme: ThemeData(
      primarySwatch: Colors.blue,
    ),
    localizationsDelegates: {
      GlobalMaterialLocalizations.delegate,
      S.delegate,
    },
    supportedLocales: S.delegate.supportedLocales,
    home: routes.buildPage('todo_list', null),
    onGenerateRoute: (RouteSettings settings) {
      return MaterialPageRoute<Object>(builder: (BuildContext context) {
        return routes.buildPage(settings.name, settings.arguments);
      });
    },
  );

Effect:

Effect<TabState> buildEffect() {
  return combineEffects(<Object, Effect<TabState>>{
    Lifecycle.initState: _initState,
  });
}

void _initState(Action action, Context<TabState> ctx) {
  S.of(ctx.context).appName;// Another exception was thrown: inheritFromWidgetOfExactType(_LocalizationsScope) or inheritFromElement() was called before ComponentState<TabState>.initState() completed.
  AppData.of(ctx.context).repo;// Another exception was thrown: inheritFromWidgetOfExactType(AppData) or inheritFromElement() was called before ComponentState<TabState>.initState() completed.
}
wangbo4020 commented 5 years ago

用原生的试验了下,这个好像不是fish-redux的问题。 https://stackoverflow.com/questions/49457717/flutter-get-context-in-initstate-method stackoverflow上建议这样写:

void _initState(Action action, Context<TabState> ctx) {
  Future.delayed(Duration.zero, () {
    S.of(ctx.context).appName;
    AppData.of(ctx.context).repo;
  });
}