0

I checked mobile is connect to the internet or not. I used this way. It's working very well. But I used this way every classes. same code duplicated. I don't understand, How to use this kind of code in global.

initialize variable

bool isOffline = false;

initState

  @override
  void initState() {
    ConnectionStatusSingleton connectionStatus =
        ConnectionStatusSingleton.getInstance();// connectionStatusSingleton is another class
    _connectionChangeStream =
        connectionStatus.connectionChange.listen(connectionChanged);
    connectionChanged(connectionStatus.hasConnection);
    super.initState();
  }

connectionChanged method

void connectionChanged(dynamic hasConnection) {
    setState(() {
      isOffline = !hasConnection;
    });
  }

After that I used in widget If connection not available I displayed appBar,

  appBar: isOffline
      ? PreferredSize(
    preferredSize: Size.fromHeight(20.0),
    child: AppBar(
      leading: Container(),
      centerTitle: true,
      backgroundColor: Colors.red,
      title: Text(
        AppTranslations.of(context).text("connection_drop"),
        style: TextStyle(fontSize: 15.0, color: Colors.white),
      ),
    ),
  )
      : null,
user9139407
  • 964
  • 1
  • 12
  • 25

1 Answers1

1

You can use StreamBuilder to achieve this. Just wrap the widgets, that depend on this Stream with it.

Something like this:

void main() {
  runApp(App());
}

class App extends StatelessWidget {
  const App({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: StreamBuilder<ConnectivityResult>(
            stream: Connectivity().onConnectivityChanged,
            initialData: ConnectivityResult.none,
            builder: (context, snapshot) {
              switch (snapshot.data) {
                case ConnectivityResult.wifi:
                  return Text("we're on a wifi network");
                case ConnectivityResult.mobile:
                  return Text("we're on a mobile network");
                case ConnectivityResult.none:
                  return Text('no network connection');
              }
            },
          ),
        ),
      ),
    );
  }
}

Also, you might want to take a look at https://pub.dev/packages/connectivity and https://pub.dev/packages/data_connection_checker

To reuse the AppBar widget you can extract it in its own class:

class MyAppBar extends StatelessWidget {
  ...
  @override
  Widget build(BuildContext context) {
    return AppBar(
      title: StreamBuilder<ConnectivityResult>(
        ...
      ),
    );
  }
  ...
}

// every time you need it, just pass it as an argument to the `Scaffold`'s `appBar` parameter.

...
Scaffold(
  ...
  appbar: MyAppBar();
  ...
)
...

Edit: I've improved the code example with something that actually works.

kristiyan.mitev
  • 315
  • 3
  • 7
  • The argument type 'StreamBuilder' can't be assigned to the parameter type 'PreferredSizeWidget' – user9139407 Jun 05 '19 at 06:59
  • Error is coming – user9139407 Jun 05 '19 at 06:59
  • @user9139407 I've made yet another edit, to simplify the code by adding `initialData: ConnectivityResult.none` and removing unnecessary code – kristiyan.mitev Jun 05 '19 at 07:42
  • The way https://pub.dev/packages/connectivity works is that it doesn't check for internet connection. So yes, if you want to reliably determine if data connection is available, you can use https://stackoverflow.com/a/49648870/9139407 If you read the comments of that answer carefully you will see that 'google.com' is not accessible for China, so maybe you'll want to ping 'example.com' or some other address (maybe the service you're trying to use), but keep in mind that you should not rely on the connection state to make network requests, i.e. always wrap your individual requests in `try-catch` – kristiyan.mitev Jun 05 '19 at 07:47
  • comment continues: I've already had this problem and decided to create a package, that deals with it. https://pub.dev/packages/data_connection_checker It works in a similar way to the method in https://stackoverflow.com/a/49648870/9139407 – kristiyan.mitev Jun 05 '19 at 07:50
  • thank you for supported. I edited my answer. If connection not available I displayed appBar, if available not displayed appBar – user9139407 Jun 05 '19 at 08:22
  • my device is connected to the internet. but a first-time snapshot.data null, `no network connection` after disconnect internet and connect internet working – user9139407 Jun 05 '19 at 09:17
  • Sir, I asked how to use this kind of code in global..I mean I show appBar in every pages when mobile is offline. So above code I used every class...I asked, How to create common class and access in any classes? – user9139407 Jun 05 '19 at 19:12
  • Sorry for lack of English – user9139407 Jun 05 '19 at 19:13
  • Oh, got it. Just extract the AppBar in its own Widget. I've updated my answer with a minimal example. – kristiyan.mitev Jun 06 '19 at 07:15