forked from md-siam/package_of_the_day
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnectivity_plus.dart
83 lines (69 loc) · 2.23 KB
/
connectivity_plus.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:overlay_support/overlay_support.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'utils.dart';
class MyConnectivityPlus extends StatelessWidget {
const MyConnectivityPlus({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return OverlaySupport(
child: MaterialApp(
title: 'Connectivity Plus',
debugShowCheckedModeBanner: false,
theme: ThemeData(primarySwatch: Colors.deepPurple),
home: const ConnectivityPlusHomeScreen(),
),
);
}
}
class ConnectivityPlusHomeScreen extends StatefulWidget {
const ConnectivityPlusHomeScreen({Key? key}) : super(key: key);
@override
State<ConnectivityPlusHomeScreen> createState() =>
_ConnectivityPlusHomeScreenState();
}
class _ConnectivityPlusHomeScreenState
extends State<ConnectivityPlusHomeScreen> {
late StreamSubscription subscription;
@override
void initState() {
super.initState();
/// this subscription listener will automatically display the snackbar
/// if the internet connection is `established` or `disconnected`
///
subscription = Connectivity().onConnectivityChanged.listen((result) {
showConnectivitySnackBar(context, result);
});
}
@override
void dispose() {
subscription.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Connectivity Plus')),
body: Center(
child: ElevatedButton(
child: const Text('Check Connection'),
onPressed: () async {
var result = await Connectivity().checkConnectivity();
// ignore: use_build_context_synchronously
showConnectivitySnackBar(context, result);
},
),
),
);
}
void showConnectivitySnackBar(
BuildContext context, ConnectivityResult result) {
final hasInternet = result != ConnectivityResult.none;
final message = hasInternet
? 'You have again ${result.toString()}'
: 'You have no internet';
final color = hasInternet ? Colors.green : Colors.red;
Utils.showTopSnackBar(context, message, color);
}
}