我如何使用肘节检查连接性?

3 connection wifi dart flutter

我需要使用连接库检查应用程序内每个页面的连接性,因此我将在提供程序内使用肘节。问题是何时关闭流以便在用户关闭应用程序时可以处理它?

像这样:

import 'package:connectivity/connectivity.dart';
@override
dispose() {
  super.dispose();
  subscription.cancel();
}

 
Run Code Online (Sandbox Code Playgroud)

Sim*_*Sot 8

在此输入图像描述

1. 确保您已将 flutter_bloc和导入connectivity_plus到您的pubspec.yaml.

2.创建一个InternetCubit文件:

  • internet_cubit.dart
  • 互联网状态.dart

3.internet_state.dart:

在这里,我们为肘节和肘节状态创建带有连接类型的枚举:

part of 'internet_cubit.dart';

enum ConnectionType {
  wifi,
  mobile,
}

@immutable
abstract class InternetState {}

class InternetLoading extends InternetState {}

class InternetConnected extends InternetState {
  final ConnectionType connectionType;

  InternetConnected({@required this.connectionType});
}

class InternetDisconnected extends InternetState {}
Run Code Online (Sandbox Code Playgroud)

4.internet_cubit.dart:

Cubit 依赖于连接插件,因此我们导入它并创建一个流订阅,以便能够对连接更改做出反应。

我们还定义了两种方法emitInternetConnectedemitInternetDisconnected这将改变实际的肘状态。

确保正确处理流订阅。

import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:meta/meta.dart';

part 'internet_state.dart';

class InternetCubit extends Cubit<InternetState> {
  final Connectivity connectivity;
  StreamSubscription connectivityStreamSubscription;
  InternetCubit({@required this.connectivity})
      : assert(connectivity != null),
        super(InternetLoading()) {
    connectivityStreamSubscription =
        connectivity.onConnectivityChanged.listen((connectivityResult) {
      if (connectivityResult == ConnectivityResult.wifi) {
        emitInternetConnected(ConnectionType.wifi);
      } else if (connectivityResult == ConnectivityResult.mobile) {
        emitInternetConnected(ConnectionType.mobile);
      } else if (connectivityResult == ConnectivityResult.none) {
        emitInternetDisconnected();
      }
    });
  }

  void emitInternetConnected(ConnectionType _connectionType) =>
      emit(InternetConnected(connectionType: _connectionType));

  void emitInternetDisconnected() => emit(InternetDisconnected());

  @override
  Future<void> close() {
    connectivityStreamSubscription.cancel();
    return super.close();
  }
}
Run Code Online (Sandbox Code Playgroud)

5. 在您的应用程序主文件中创建一个插件实例Connectivity并将其传递给您的BlocProvider. 根据您的需求设置集体消费:

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_application_4/cubit/internet_cubit.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

void main() => runApp(MyApp(connectivity: Connectivity()));

class MyApp extends StatelessWidget {
  final Connectivity connectivity;

  const MyApp({Key key, this.connectivity}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => InternetCubit(connectivity: connectivity),
      child: MaterialApp(
        title: 'Connectivity cubit',
        home: Scaffold(
          appBar: AppBar(
            title: Text('Connectivity cubit spotlight'),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                BlocBuilder<InternetCubit, InternetState>(
                  builder: (context, state) {
                    if (state is InternetConnected &&
                        state.connectionType == ConnectionType.wifi) {
                      return Text(
                        'Wifi',
                        style: TextStyle(color: Colors.green, fontSize: 30),
                      );
                    } else if (state is InternetConnected &&
                        state.connectionType == ConnectionType.mobile) {
                      return Text(
                        'Mobile',
                        style: TextStyle(color: Colors.yellow, fontSize: 30),
                      );
                    } else if (state is InternetDisconnected) {
                      return Text(
                        'Disconnected',
                        style: TextStyle(color: Colors.red, fontSize: 30),
                      );
                    }
                    return CircularProgressIndicator();
                  },
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)