Skip to main content

How to write a code Internet Connectivity in Flutter

Check Internet Connectivity In Flutter


In pubspec.yaml file:  add package,

connectivity_plus: ^3.0.3 
provider: ^6.0.3

In Dart file: Write a Code,

1- Create  AppScaffold.dart file,

import 'package:flutter/material.dart';
import 'package:../widgets/network_widget.dart';
import 'network_aware_widget.dart';


class AppScaffold extends StatelessWidget {
final Widget child;

const AppScaffold({Key? key, required this.child}) : super(key: key);

@override
Widget build(BuildContext context) {
return Scaffold(
body: NetworkAwareWidget(
onlineChild: child,
offlineChild: Center(
child: OfflineWidget() //(according to need create offline Network UI)
)),
);
}
}
2- Create an OfflineWidget.dart file,

import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:.../routes/const_string_route_name.dart';
import 'package:.../styles/Style.dart';
import 'package:.../styles/colors.dart';
import 'package:.../styles/fontSize.dart';
import 'package:sizer/sizer.dart';

class OfflineWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
fontSizes(context);
return Scaffold(
body: Center(
child: Container(
decoration: containerDecoration,
height: MediaQuery.of(context).size.height,
child: Center(
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Center(
child: Image(
height: 20.h,
image: AssetImage('assets/images/connection.png'),
),
),
Center(
child: Image(
height: 20.h,
image: AssetImage('assets/images/network.png'),
),
),
Center(
child: Text(
"Something Went wrong .",
style: GoogleFonts.raleway(
fontWeight: FontWeight.w600,
fontSize: fontSizes.subtitle,
height: 1.2,
letterSpacing: .5,
color: redColor,
),
),
),
Center(
child: Text(
"No Internet Connection.",
style: GoogleFonts.raleway(
fontWeight: FontWeight.w600,
fontSize: fontSizes.subtitle,
height: 1.2,
letterSpacing: .5,
color: redColor,
),
),
),
Center(
child: Text(
"Your are Offline.",
style: GoogleFonts.raleway(
fontWeight: FontWeight.w600,
fontSize: fontSizes.subtitle,
height: 1.2,
letterSpacing: .5,
color: blackColor,
),
),
),
SizedBox(
height: 2.h,
),
InkWell(
onTap: () {
Navigator.pushNamedAndRemoveUntil(
context, splashRoute, (route) => false);
},
child: Container(
height: 5.h,
width: MediaQuery.of(context).size.width * 0.6,
decoration: containerDecoration1,
child: Center(
child: Text(
"Try Again",
style: GoogleFonts.raleway(
fontWeight: FontWeight.w600,
fontSize: fontSizes.subtitle,
height: 1.2,
letterSpacing: .5,
color: kBackgroundColor,
),
),
),
),
)
],
),
),
),
),
)

);

}
}


3- Create a NetworkAwareWidget.dart file ,

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

class NetworkAwareWidget extends StatelessWidget {
final Widget onlineChild;
final Widget offlineChild;

const NetworkAwareWidget(
{Key? key, required this.onlineChild, required this.offlineChild})
: super(key: key);


@override
Widget build(BuildContext context) {
return Consumer<NetworkStatus>(builder: (context, data, child) {
return data == NetworkStatus.Online ? onlineChild : offlineChild;
});
}
}
4- Create a NetworkStatusService.dart file,

import 'dart:async';
import 'package:connectivity_plus/connectivity_plus.dart';

enum NetworkStatus { Online, Offline }

class NetworkStatusService {

StreamController<NetworkStatus> networkStatusController =
StreamController<NetworkStatus>();


NetworkStatusService() {
Connectivity().onConnectivityChanged.listen((status) {
networkStatusController.add(_getNetworkStatus(status));
});
}

NetworkStatus _getNetworkStatus(ConnectivityResult status) {
return status == ConnectivityResult.mobile ||
status == ConnectivityResult.wifi
? NetworkStatus.Online
: NetworkStatus.Offline;
}


}
Finally, use this Network Check Status Widgets in the Requirement file

Like this,

MultiProvider(
providers: [
StreamProvider<NetworkStatus>(
create: (context) =>
NetworkStatusService().networkStatusController.stream,
initialData: NetworkStatus.Online,
)
], child: const AppScaffold(child: LoginScreen())
)
Thanks for reading the article ...

Comments

Popular posts from this blog

How to write a code of Encode and Decode json data in Dart language

 Encode and decode JSON data in dart language import 'dart:convert'; void main() {   // Original data as a Dart map   Map<String, dynamic> originalData = {     'field1': 'value1',     'field2': 42,     'field3': true,   };   // Encode the Dart map to JSON string   String jsonString = jsonEncode(originalData);   print('Original JSON String:');   print(jsonString);   // Encode the JSON string to base64   String base64EncodedString = base64.encode(utf8.encode(jsonString));   print('\nBase64 Encoded String:');   print(base64EncodedString);   // Decode the base64 string to JSON string   String decodedJsonString = utf8.decode(base64.decode(base64EncodedString));   print('\nDecoded JSON String:');   print(decodedJsonString);   // Decode the JSON string to a Dart map   Map<String, dynamic> decodedData = jsonDecode(decodedJsonString);   print('\nDecoded Dart Ma...

About of Free Learning Tech Point

  Welcome to Free Learning Tech Point , where knowledge meets accessibility. Our platform is dedicated to providing high-quality educational resources and e-learning opportunities to learners around the world, completely free of charge. Our Mission: At Free Learning Tech Point, we believe that education is a fundamental right, and everyone should have access to valuable learning materials. Our mission is to break down barriers to education by offering a diverse range of courses, tutorials, and resources across various subjects and disciplines. What Sets Us Apart: - Free Access: Our commitment is to make learning accessible to all. No subscription fees, no hidden costs – just free, open access to knowledge.    - Quality Content: We curate and create content that is both engaging and informative. Whether you're a student, professional, or lifelong learner, our resources are designed to cater to various learning styles and levels. - Diverse Subjects: From tech and science...

Privacy Policy Of Free Learning Tech Point

  Thank you for visiting Free Learning Tech Point . You can use our website, services, and products with the awareness that this Privacy Policy describes how we gather, use, disclose, and protect your personal information. 1- Information We Collect: We may collect personal information that you provide directly to us, such as your name, email address, and any other information you choose to provide when using our Services. We may also collect non-personal information, such as aggregated data and usage patterns. 2- How We Use Your Information: We may use the information we collect for various purposes, including but not limited to: Providing and improving our Services. Responding to your inquiries and requests. Analyzing usage patterns and trends. Sending you updates, newsletters, and other communications. Personalizing your experience on our platform. 3- Cookies and Similar Technologies: We may use cookies and similar technologies to collect information about your interactions with...