如何处理Flutter + Redux appp

时间:2018-11-14 10:54:03

标签: redux flutter flutter-redux

我有一个flupper + redux应用程序,我想检测一下连接何时消失并显示等待屏幕。我已将MyApp订阅到状态为state.haveInternet的属性中,以在state.haveInternet更改时重新构建整个应用程序。 问题是状态更改时,我的应用程序不显示NoInternetScreen。我做错了什么?

我认为导航器可能会带来另一个麻烦,但是我不确定在哪里使用它。在中间件内部(闻起来)?实际上,我在ConnectivityMidleware中添加了一个侦听器。我应该在runApp()之前将该中间件移至main()吗?

void main() {
  Store<AppState> store = Store(
    Reducers.root,
    initialState: AppState.initial(),
    middleware: [
      LoggingMiddleware.printer(),
      firebaseAuthMiddleware,
      firebaseDatabaseMiddleware,
      firebaseMessagingMiddleware,
      connectivityMiddleware,
    ],
  );

  SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])
      .then((_) {
    runApp(new MyApp(store));
  });
}

class MyApp extends StatelessWidget {
  Store<AppState> store;

  MyApp(this.store);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    FirebaseAnalytics analytics = FirebaseAnalytics();

    return new StoreProvider(
      store: store,
      child: StoreConnector<AppState, Map>(
        converter: (store) {
          Map _viewmodel = {};
          Map<String, double> media =
              calculaMedia(List.of(store.state.registros.values), 10);

          _viewmodel['mainColor'] = getColorByTension(
              media['alta'].round(), media['baja'].round());

          if (media['alta'] == 0.0 || media['baja'] == 0) {
            _viewmodel['mainColor'] = Colors.red;
          }
          _viewmodel['haveInternet'] = store.state.haveConnectivity;

          return _viewmodel;
        },
        builder: (context, viewmodel) => MaterialApp(
              onGenerateTitle: (context) => AppLocalizations.of(context).title,
              theme: new ThemeData(
                primarySwatch: viewmodel['mainColor'],
              ),
              home: viewmodel['haveInternet'] ? SplashScreen(store): NoInternetScreen(),
              localizationsDelegates: [
                const AppLocalizationsDelegate(),
                GlobalMaterialLocalizations.delegate,
                GlobalWidgetsLocalizations.delegate,
              ],
              supportedLocales: [
                const Locale('en', 'US'), // English
                const Locale('es', 'ES'), // Spanish
                // ... other locales the app supports
              ],
              navigatorObservers: [
                FirebaseAnalyticsObserver(analytics: analytics),
              ],
            ),
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:0)

您可以使用这种简单的方法来了解用户是否已连接到Internet。

//Use dart.io for lookup method.
import 'dart:io';
Future<bool> _checkConnectivity() async {
bool connect;
try {
final result = await InternetAddress.lookup('google.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
connect = true;
}
} on SocketException catch (_) {
connect = false;
}
return connect;
}

现在,您可以轻松地在希望返回Future的任何地方轻松使用此方法。