How to handle connection lost in a Flutter + Redux appp












0















I've a flupper + redux app and I want to detect whene the connectivity is gone and display a waiting screen. I've subscribed MyApp to a property in my state called state.haveInternet with the idea of rebuild the whole app when the state.haveInternet changes.
The problem is that my app doesnt display the NoInternetScreen when the state changes. What I'm doing wrong?



I think that another aproach could be play with the Navigator but I'm not sure where to use it. Inside the midleware (it smells)? Actually, I add a listener in connectivityMidleware. Should I move that midleware to the main() before runApp() ?



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),
],
),
),
);
}
}









share|improve this question



























    0















    I've a flupper + redux app and I want to detect whene the connectivity is gone and display a waiting screen. I've subscribed MyApp to a property in my state called state.haveInternet with the idea of rebuild the whole app when the state.haveInternet changes.
    The problem is that my app doesnt display the NoInternetScreen when the state changes. What I'm doing wrong?



    I think that another aproach could be play with the Navigator but I'm not sure where to use it. Inside the midleware (it smells)? Actually, I add a listener in connectivityMidleware. Should I move that midleware to the main() before runApp() ?



    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),
    ],
    ),
    ),
    );
    }
    }









    share|improve this question

























      0












      0








      0








      I've a flupper + redux app and I want to detect whene the connectivity is gone and display a waiting screen. I've subscribed MyApp to a property in my state called state.haveInternet with the idea of rebuild the whole app when the state.haveInternet changes.
      The problem is that my app doesnt display the NoInternetScreen when the state changes. What I'm doing wrong?



      I think that another aproach could be play with the Navigator but I'm not sure where to use it. Inside the midleware (it smells)? Actually, I add a listener in connectivityMidleware. Should I move that midleware to the main() before runApp() ?



      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),
      ],
      ),
      ),
      );
      }
      }









      share|improve this question














      I've a flupper + redux app and I want to detect whene the connectivity is gone and display a waiting screen. I've subscribed MyApp to a property in my state called state.haveInternet with the idea of rebuild the whole app when the state.haveInternet changes.
      The problem is that my app doesnt display the NoInternetScreen when the state changes. What I'm doing wrong?



      I think that another aproach could be play with the Navigator but I'm not sure where to use it. Inside the midleware (it smells)? Actually, I add a listener in connectivityMidleware. Should I move that midleware to the main() before runApp() ?



      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),
      ],
      ),
      ),
      );
      }
      }






      redux flutter flutter-redux






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 14 '18 at 10:54









      user3712489user3712489

      1




      1
























          1 Answer
          1






          active

          oldest

          votes


















          0














          You can use this simple method to know whether the user is connected to the internet or not.



          //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;
          }


          now you can easily use this method, wherever you want it returns a Future.






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53298518%2fhow-to-handle-connection-lost-in-a-flutter-redux-appp%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            You can use this simple method to know whether the user is connected to the internet or not.



            //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;
            }


            now you can easily use this method, wherever you want it returns a Future.






            share|improve this answer




























              0














              You can use this simple method to know whether the user is connected to the internet or not.



              //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;
              }


              now you can easily use this method, wherever you want it returns a Future.






              share|improve this answer


























                0












                0








                0







                You can use this simple method to know whether the user is connected to the internet or not.



                //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;
                }


                now you can easily use this method, wherever you want it returns a Future.






                share|improve this answer













                You can use this simple method to know whether the user is connected to the internet or not.



                //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;
                }


                now you can easily use this method, wherever you want it returns a Future.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 14 '18 at 13:11









                Md Sadab WasimMd Sadab Wasim

                665




                665






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53298518%2fhow-to-handle-connection-lost-in-a-flutter-redux-appp%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Xamarin.iOS Cant Deploy on Iphone

                    Glorious Revolution

                    Dulmage-Mendelsohn matrix decomposition in Python