mvasco
mvasco

Reputation: 5107

Using connectivity package in Flutter with provider

I am creating a new Flutter project.

I would like to check the internet connectivity status for the whole application using Provider.

I have included both packages "connectivity" and "provider" in the pubspec.yaml file.

Then I have changed main.dart as follow, to include a streamprovider for Connectivity plugin:

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        StreamProvider(
            create: (context) => Connectivity().onConnectivityChanged),
      ],
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        title: 'My New App',
        theme: ThemeData(
          backgroundColor: Colors.white,
        ),
        home: MyHomePage(title: 'My New App Login'),
      ),
    );
  }
}

What should I do on every new class where I want to check the internet connectivity status?

I know I have to instatiate the provider:

var connectionStatus;
connectionStatus = Provider.of<ConnectivityResult>(context);

but then, what should I do to listen to the connectivity status on every class?

Upvotes: 2

Views: 3739

Answers (2)

rkdupr0n
rkdupr0n

Reputation: 703

I kept getting an error no matter what I did. Kept giving me a null result. So I thought I'd see the code behind and lo and behold, what do I find...

enter image description here

enter image description here

I have literally no idea what the problem is or if it's just a problem on my side, rip.

EDIT:

I followed wut moneer did and it works, lol.

import 'package:connectivity/connectivity.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        StreamProvider(create: (context) => Connectivity().onConnectivityChanged),
      ],
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        title: 'My New App',
        theme: ThemeData(
          backgroundColor: Colors.white,
        ),
        home: MyHomePage(title: 'My New App Login'),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _connectivityType = 'Init';

  void _getConnectionStatus(ConnectivityResult con) {
    print(con);
    setState(() {
      switch (con) {
        case ConnectivityResult.mobile:
          _connectivityType = 'Mobile';
          break;
        case ConnectivityResult.wifi:
          _connectivityType = 'Wifi';
          break;
        case ConnectivityResult.none:
          _connectivityType = 'None';
          break;
        default:
          _connectivityType = 'Unknown';
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    final con = Provider.of<ConnectivityResult>(context);
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_connectivityType',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => _getConnectionStatus(con),
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

EDIT 2: If ya want to check your internet connection, this is the package for ya.

Upvotes: 2

moneer alhashim
moneer alhashim

Reputation: 828

ConnectivityResult is an enum so you need to compare it.


/// Connection status check result.
enum ConnectivityResult {
  /// WiFi: Device connected via Wi-Fi
  wifi,

  /// Mobile: Device connected to cellular network
  mobile,

  /// None: Device not connected to any network
  none
}

You should also check if the value is null I don't quite remember why

Upvotes: 1

Related Questions