3

I need to check the connectivity in every page inside my application using connectivity library, So i will use a cubit inside the provider. the question is when to close the stream to make it possible to dispose it when the user close the app?

just like this:

import 'package:connectivity/connectivity.dart';
@override
dispose() {
  super.dispose();
  subscription.cancel();
}

 
  • 1
    Please revisit your question and clarify... basically all of it. We are sitting at the other side of the world with none of the context you have. A question so generic and vague as this is unanswerable. Please post your full code and ask a question in that context. I see no connectivity check, I see no cubit, I have no idea what "subscription" in your program even *is*. So how could I possibly say anything to help you with it? – nvoigt Apr 15 '21 at 10:18

1 Answers1

8

enter image description here

1. Make sure you have imported flutter_bloc and connectivity_plus in your pubspec.yaml.

2. Create an InternetCubit files:

  • internet_cubit.dart
  • internet_state.dart

3. internet_state.dart:

Here we create enum with connection types for our cubit and cubit states:

part of 'internet_cubit.dart';

enum ConnectionType {
  wifi,
  mobile,
}

@immutable
abstract class InternetState {}

class InternetLoading extends InternetState {}

class InternetConnected extends InternetState {
  final ConnectionType connectionType;

  InternetConnected({@required this.connectionType});
}

class InternetDisconnected extends InternetState {}

4. internet_cubit.dart:

Cubit depends on connectivity plugin, so we import it and create a stream subscription to be able to react on connection changes.

Also we define two methods emitInternetConnected and emitInternetDisconnected that will change actual cubit state.

Make sure to dispose of stream subscription properly.

import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:meta/meta.dart';

part 'internet_state.dart';

class InternetCubit extends Cubit<InternetState> {
  final Connectivity connectivity;
  StreamSubscription connectivityStreamSubscription;
  InternetCubit({@required this.connectivity})
      : assert(connectivity != null),
        super(InternetLoading()) {
    connectivityStreamSubscription =
        connectivity.onConnectivityChanged.listen((connectivityResult) {
      if (connectivityResult == ConnectivityResult.wifi) {
        emitInternetConnected(ConnectionType.wifi);
      } else if (connectivityResult == ConnectivityResult.mobile) {
        emitInternetConnected(ConnectionType.mobile);
      } else if (connectivityResult == ConnectivityResult.none) {
        emitInternetDisconnected();
      }
    });
  }

  void emitInternetConnected(ConnectionType _connectionType) =>
      emit(InternetConnected(connectionType: _connectionType));

  void emitInternetDisconnected() => emit(InternetDisconnected());

  @override
  Future<void> close() {
    connectivityStreamSubscription.cancel();
    return super.close();
  }
}

5. In your app main file create an instance of Connectivity plugin and pass it to your BlocProvider. Set up bloc consuming with your needs:

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_application_4/cubit/internet_cubit.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

void main() => runApp(MyApp(connectivity: Connectivity()));

class MyApp extends StatelessWidget {
  final Connectivity connectivity;

  const MyApp({Key key, this.connectivity}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => InternetCubit(connectivity: connectivity),
      child: MaterialApp(
        title: 'Connectivity cubit',
        home: Scaffold(
          appBar: AppBar(
            title: Text('Connectivity cubit spotlight'),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                BlocBuilder<InternetCubit, InternetState>(
                  builder: (context, state) {
                    if (state is InternetConnected &&
                        state.connectionType == ConnectionType.wifi) {
                      return Text(
                        'Wifi',
                        style: TextStyle(color: Colors.green, fontSize: 30),
                      );
                    } else if (state is InternetConnected &&
                        state.connectionType == ConnectionType.mobile) {
                      return Text(
                        'Mobile',
                        style: TextStyle(color: Colors.yellow, fontSize: 30),
                      );
                    } else if (state is InternetDisconnected) {
                      return Text(
                        'Disconnected',
                        style: TextStyle(color: Colors.red, fontSize: 30),
                      );
                    }
                    return CircularProgressIndicator();
                  },
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
Simon Sot
  • 2,748
  • 2
  • 10
  • 23