Issue
im developing a flutter app that i want to make it connect to the internet, i have tried the flutter Connectivity, connectivity_plus, but these packages don't detect data access, the only detect mobile or WiFi connection and acts as if it is online though there is no data access, i have also tried data_connection_checker and internet_connection _checker, but i think i was not able to implement them well, i want the body of my statefull widget to be determined based on the the internet access, when online body: Body() appear, when offline: NoConnectionPage() should appear, and also to continue check for internet access through the app.
Solution
If I'm not wrong , you are expecting this.
I have used connectivity_plus plugin to check internet connection. and for better performance used flutter_bloc : ^7.3.3 (If you familiar with BLoc state management) within equatable: ^2.0.3 plugins.
FULL CODE:
Bloc part:
network_connectivity_bloc.dart
:
import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:equatable/equatable.dart';
part 'network_connectivity_event.dart';
part 'network_connectivity_state.dart';
class NetworkConnectivityBloc
extends Bloc<NetworkConnectivityEvent, NetworkConnectivityState> {
NetworkConnectivityBloc() : super(InitialNetworkConnectivityState());
bool networkOfflineOnce = false;
ConnectivityResult? connectivityResult;
Connectivity? connectivity;
StreamSubscription<ConnectivityResult>? _connectivitySubscription;
@override
Stream<NetworkConnectivityState> mapEventToState(
NetworkConnectivityEvent event,
) async* {
if (event is InitNetworkConnectivity) {
connectivity = Connectivity();
connectivityResult = await (connectivity!.checkConnectivity());
add(SetNetworkStatus(connectivityResult: connectivityResult));
}
if (event is ListenNetworkConnectivity) {
if (connectivity == null) {
add(InitNetworkConnectivity());
}
_connectivitySubscription = connectivity!.onConnectivityChanged
.listen((ConnectivityResult result) {
add(SetNetworkStatus(connectivityResult: result));
});
}
if (event is SetNetworkStatus) {
if (event.connectivityResult == ConnectivityResult.mobile) {
if (networkOfflineOnce) {
networkOfflineOnce = false;
}
yield NetworkOnline();
print("Connected => Cellular Network");
} else if (event.connectivityResult == ConnectivityResult.wifi) {
if (networkOfflineOnce) {
networkOfflineOnce = false;
}
yield NetworkOnline();
print("Connected => WiFi");
} else {
networkOfflineOnce = true;
yield NetworkOffline();
print("Not Connected => Offline , Please Check Internet Connection");
}
}
}
dispose() {
_connectivitySubscription!.cancel();
}
}
network_connectivity_event.dart
class
part of 'network_connectivity_bloc.dart';
abstract class NetworkConnectivityEvent extends Equatable {
const NetworkConnectivityEvent();
@override
List<Object> get props => [];
}
class InitNetworkConnectivity extends NetworkConnectivityEvent {}
class ListenNetworkConnectivity extends NetworkConnectivityEvent {}
class SetNetworkStatus extends NetworkConnectivityEvent {
final ConnectivityResult? connectivityResult;
const SetNetworkStatus({required this.connectivityResult});
@override
String toString() =>
'connectivityResult {connectivityResult: $connectivityResult}';
}
network_connectivity_state.dart
class:
part of 'network_connectivity_bloc.dart';
abstract class NetworkConnectivityState extends Equatable {
const NetworkConnectivityState();
@override
List<Object> get props => [];
}
class InitialNetworkConnectivityState extends NetworkConnectivityState {}
class NetworkOnline extends NetworkConnectivityState {}
class NetworkOffline extends NetworkConnectivityState {}
UI PART:
main.dart
:
import 'package:flutter/material.dart';
import 'package:flutter_application_1/bloc/network_connectivity_bloc.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter/foundation.dart';
void main() async {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'INTERNET CHECK',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const InterNetChecker());
}
}
class InterNetChecker extends StatelessWidget {
const InterNetChecker({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Internet stateManagement"),
centerTitle: true,
),
body: BlocProvider(
create: (context) => NetworkConnectivityBloc(),
child: const Center(
child: NetworkStatusIndicator(),
),
),
);
}
}
class NetworkStatusIndicator extends StatefulWidget {
const NetworkStatusIndicator({Key? key}) : super(key: key);
@override
_NetworkStatusColorIndicatorState createState() =>
_NetworkStatusColorIndicatorState();
}
class _NetworkStatusColorIndicatorState extends State<NetworkStatusIndicator> {
NetworkConnectivityBloc? _networkConnectivityBloc;
@override
void initState() {
_networkConnectivityBloc =
BlocProvider.of<NetworkConnectivityBloc>(context);
_networkConnectivityBloc!.add(InitNetworkConnectivity());
_networkConnectivityBloc!.add(ListenNetworkConnectivity());
super.initState();
}
@override
void dispose() {
super.dispose();
BlocProvider.of<NetworkConnectivityBloc>(context).dispose();
}
@override
Widget build(BuildContext context) {
return BlocBuilder(
bloc: _networkConnectivityBloc,
builder: (BuildContext context, NetworkConnectivityState state) {
if (state is NetworkOnline) {
return showNetworkStatus(Colors.green, "ONLINE");
}
if (state is NetworkOffline) {
return showNetworkStatus(Colors.red, "OFFILINE");
}
return showNetworkStatus(Colors.grey, "");
},
);
}
}
Widget showNetworkStatus(MaterialColor color, String status) {
return
Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
IconButton(
icon: Icon(
Icons.fiber_manual_record,
color: color,
size: 15,
),
onPressed: () {},
),
const SizedBox(width: 10),
Text(
status,
style: TextStyle(fontSize: 25, color: color),
)
],
),
);
}
Answered By - Shruti Ramnandan Sharma
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.