Build a Network Sensitive UI in Flutter using Provider and Connectivity

Dane Mackier
May 26 · 4 min read

Implementation

connectivity: ^0.4.3+1
provider: ^2.0.1
enum ConnectivityStatus {
WiFi,
Cellular,
Offline
}
import 'dart:async';import 'package:connectivity/connectivity.dart';
import 'package:network_aware/enums/connectivity_status.dart';
class ConnectivityService {
// Create our public controller
StreamController<ConnectivityStatus> connectionStatusController = StreamController<ConnectivityStatus>();
ConnectivityService() {
// Subscribe to the connectivity Chanaged Steam
Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
// Use Connectivity() here to gather more info if you need t
connectionStatusController.add(_getStatusFromResult(result));
});
}
// Convert from the third part enum to our own enum
ConnectivityStatus _getStatusFromResult(ConnectivityResult result) {
switch (result) {
case ConnectivityResult.mobile:
return ConnectivityStatus.Cellular;
case ConnectivityResult.wifi:
return ConnectivityStatus.WiFi;
case ConnectivityResult.none:
return ConnectivityStatus.Offline;
default:
return ConnectivityStatus.Offline;
}
}
}
@override
Widget build(BuildContext context) {
return StreamProvider<ConnectivityStatus>(
builder: (context) => ConnectivityService().connectionStatusController,
child: MaterialApp(
title: 'Connectivity Aware UI',
theme: ThemeData(
textTheme: Theme.of(context)
.textTheme
.apply(bodyColor: Colors.white, displayColor: Colors.white)),
home: HomeView(),
),
);
}

Network sensitivity

class NetworkSensitive extends StatelessWidget {
final Widget child;
final double opacity;
NetworkSensitive({
this.child,
this.opacity = 0.5,
});
@override
Widget build(BuildContext context) {
return Container();
}
}
...@override
Widget build(BuildContext context) {
// Get our connection status from the provider
var connectionStatus = Provider.of<ConnectivityStatus>(context);
if (connectionStatus == ConnectivityStatus.WiFi) {
return child;
}
if (connectionStatus == ConnectivityStatus.Cellular) {
return Opacity(
opacity: opacity,
child: child,
);
}
return Opacity(
opacity: 0.1,
child: child,
);
}
...
...
// Wrap the Error's Stats counter
child: NetworkSensitive(
child: StatsCounter(
size: screenHeight(context,
dividedBy: 2, decreasedBy: toolbarHeight) -
CounterMargins, // 60 margins
count: 13,
title: 'Errors',
titleColor: Colors.red,
),
),
...
// Wrap the Users counter
...
NetworkSensitive(
child: StatsCounter(
size: screenHeight(context,
dividedBy: 3, decreasedBy: toolbarHeight) -
CounterMargins,
count: 55,
title: 'Users',
),
),
...
var connectionStatus = Provider.of<ConnectivityStatus>(context);

Flutter Community

Articles and Stories from the Flutter Community

Dane Mackier

Written by

A full stack software developer focused on building mobile products, its tools and architecture. Always reducing boiler plate code and experimenting.

Flutter Community

Articles and Stories from the Flutter Community