1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

flutterでネットワーク接続状態を検出・監視する

Posted at

connectivity_plusというパッケージを使ってflutterでデバイスのネットワークの接続状況を検出、監視する方法。このパッケージを使うとネットワークの他にwifiとかbluetoothとかの接続状況をチャックすることもできるらしい。

インストール

% flutter pub add connectivity_plus

インターネット接続を監視

main.dart
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:connectivity_plus/connectivity_plus.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Connectivity Example with Flutter Hooks'),
        ),
        body: ConnectivityExample(),
      ),
    );
  }
}

class ConnectivityExample extends HookWidget {
  @override
  Widget build(BuildContext context) {
    final isConnected = useState(false);

    useEffect(() {
      final connectivity = Connectivity();
      final subscription = connectivity.onConnectivityChanged.listen((List<ConnectivityResult> results) {
        isConnected.value = results.any((result) => result != ConnectivityResult.none);
      });

      return subscription.cancel;
    }, []);

    return Center(
      child: Text(
        isConnected.value ? 'Connected to the Internet' : 'No Internet Connection',
        style: TextStyle(fontSize: 24),
      ),
    );
  }
}

flutter_hooksを使用してisConnectedの状態を管理(useStateで状態を保持しuseEffectで接続状態の監視を設定)。これにより、インターネット接続がない場合はfalse、接続がある場合はtrueに設定される。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?