1

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

我认为另一种方法可以与 Navigator 一起玩,但我不确定在哪里使用它。在中间件里面(有味道)?实际上,我在connectivityMiddleware 中添加了一个监听器。我应该在 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),
              ],
            ),
      ),
    );
  }
}
4

1 回答 1

0

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

//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。

于 2018-11-14T13:11:33.080 回答