Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Connectivity Demo
import 'dart:async';
import 'package:connectivity/connectivity.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Network state demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('NetworkState Demo'),
),
body: FormWidget(),
);
}
}
class FormWidget extends StatefulWidget {
@override
_FormWidgetState createState() => _FormWidgetState();
}
class _FormWidgetState extends State<FormWidget> {
String assetUrl = "assets/wifi.gif";
String message = "Unknown Connection";
StreamSubscription subscription;
@override
void initState() {
super.initState();
subscription = Connectivity()
.onConnectivityChanged
.listen((ConnectivityResult result) {
if (result == ConnectivityResult.none) {
setState(() {
assetUrl = "assets/no_wifi.gif";
message = "No network connection";
});
}
if (result == ConnectivityResult.mobile) {
setState(() {
assetUrl = "assets/network.gif";
message = "Mobile network connected";
});
} else if (result == ConnectivityResult.wifi) {
setState(() {
assetUrl = "assets/wifi.gif";
message = "Wifi Connected";
});
}
});
}
@override
void dispose() {
subscription.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Form(
child: Column(
children: <Widget>[
Image.asset(assetUrl,height: 200,),
Text(
message,
style: TextStyle(fontSize: 30, fontWeight: FontWeight.w700),
),
Image.network("https://pbs.twimg.com/media/EcUEf3oUcAAshqn?format=jpg&name=medium"),
],
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment