I am trying to use the BLoC library with the connectivity_plus
plugin in Flutter. I have followed this post and this post to set up an Internet Cubit for the project. The code works fine when the app is started with the internet connection turned on.
However, with the internet connection turned off, if I kill the app and re-launch it or do a hot restart, the CircularProgressIndicator() is shown instead of Text("Internet Disconnected")
.
Turning the internet back on correctly shows Text("Internet Connected")
widget. After this, If I turn off the internet connection again, this time around it correctly shows the Text("Internet Disconnected")
widget.
Also, emitInternetDisconnected
is not caught as an exception in the try catch
block to update the app's state.
The problem with the CircularProgressIndicator()
being always displayed with the internet disconnected occurs only when the app is re-launched or hot restarted. I cannot figure out the bug in my code. What should I do to fix my code? Thanks
This is the code in the internet_cubit.dart
file
import 'dart:async';
import 'dart:io';
import 'package:bloc/bloc.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'internet_enum.dart';
part 'internet_state.dart';
class InternetCubit extends Cubit<InternetState> {
final Connectivity? connectivity;
StreamSubscription? connectivityStreamSubscription;
InternetCubit({required this.connectivity}) : super(InternetLoading()) {
monitorInternetConnection();
}
void monitorInternetConnection() async {
connectivityStreamSubscription =
connectivity!.onConnectivityChanged.listen((connectivityResult) async {
try {
final result = await InternetAddress.lookup("example.com");
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
if (connectivityResult == ConnectivityResult.wifi) {
emitInternetConnected(ConnectionType.WiFi);
} else if (connectivityResult == ConnectivityResult.mobile) {
emitInternetConnected(ConnectionType.Mobile);
} else if (connectivityResult == ConnectivityResult.none) {
emitInternetDisconnected();
}
}
} on SocketException catch (_) {
emitInternetDisconnected();
}
});
}
void emitInternetConnected(ConnectionType _connectionType) =>
emit(InternetConnected(connectionType: _connectionType));
void emitInternetDisconnected() => emit(InternetDisconnected());
@override
Future<void> close() async {
connectivityStreamSubscription!.cancel();
return super.close();
}
}
This is the code in the internet_state.dart
file
part of 'internet_cubit.dart';
abstract class InternetState {}
class InternetLoading extends InternetState {}
class InternetConnected extends InternetState {
final ConnectionType? connectionType;
InternetConnected({required this.connectionType});
}
class InternetDisconnected extends InternetState {}
This is the code in my main.dart
file
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'internet_cubit.dart';
void main() {
runApp(
BlocProvider<InternetCubit>(
create: (_) => InternetCubit(connectivity: Connectivity()),
child: MyApp(),
),
);
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter BLoC Demo',
home: SafeArea(
child: Scaffold(
appBar: AppBar(
title: Text("Flutter BLoC Demo"),
centerTitle: true,
backgroundColor: Colors.blue[900],
),
body: Center(
child: Builder(
builder: (context) {
return MaterialButton(
onPressed: () {
Navigator.push(context, MaterialPageRoute(builder: (context) => ScreenOne()));
},
color: Colors.black,
textColor: Colors.white,
child: Text("Screen 1"));
},
),
),
),
),
);
}
}
class ScreenOne extends StatelessWidget {
const ScreenOne({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
appBar: AppBar(
title: Text("Flutter BLoC Demo"),
centerTitle: true,
backgroundColor: Colors.blue[900],
),
body: Center(
child: BlocBuilder<InternetCubit, InternetState>(
builder: (_, state) {
if (state is InternetDisconnected) {
return Text("Internet disconnected");
} else if (state is InternetConnected) {
return Text("Internet connected");
}
return CircularProgressIndicator();
},
),
),
),
);
}
}