blob: 540534f9181438233625c7fd72a32d0a5c5a14cc [file] [log] [blame]
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter/services.dart';
/// Connection Status Check Result
///
/// Wifi: Device connected via Wi-Fi
/// Mobile: Device connected to cellular network
/// None: Device not connected to any network
enum ConnectivityResult { wifi, mobile, none }
const MethodChannel _methodChannel =
const MethodChannel('plugins.flutter.io/connectivity');
const EventChannel _eventChannel =
const EventChannel('plugins.flutter.io/connectivity_status');
class Connectivity {
Stream<ConnectivityResult> _onConnectivityChanged;
/// Fires whenever the connectivity state changes.
Stream<ConnectivityResult> get onConnectivityChanged {
if (_onConnectivityChanged == null) {
_onConnectivityChanged = _eventChannel
.receiveBroadcastStream()
.map(_stringToConnectivityResult);
}
return _onConnectivityChanged;
}
/// Checks the connection status of the device.
///
/// Do not use the result of this function to decide whether you can reliably
/// make a network request. It only gives you the radio status.
///
/// Instead listen for connectivity changes via [onConnectivityChanged] stream.
Future<ConnectivityResult> checkConnectivity() async {
final String result = await _methodChannel.invokeMethod('check');
return _stringToConnectivityResult(result);
}
}
ConnectivityResult _stringToConnectivityResult(String state) {
switch (state) {
case 'wifi':
return ConnectivityResult.wifi;
case 'mobile':
return ConnectivityResult.mobile;
case 'none':
default:
return ConnectivityResult.none;
}
}