我如何使用 cubit 检查连接? [英] how could i check connectivity using cubit?

查看:34
本文介绍了我如何使用 cubit 检查连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用连接库检查应用程序内每个页面的连接性,所以我将在提供者内部使用一肘.问题是什么时候关闭流,以便在用户关闭应用程序时处理它?<​​/p>

就像这样:

import 'package:connectivity/connectivity.dart';@覆盖处置(){超级处置();订阅.取消();}

解决方案

1.确保您已在 pubspec.yaml 中导入了 flutter_blocconnectivity_plus.

2.创建 InternetCubit 文件:

  • internet_cubit.dart
  • internet_state.dart

3.internet_state.dart:

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

'internet_cubit.dart' 的一部分;枚举连接类型{无线上网,移动的,}@不可变抽象类 InternetState {}class InternetLoading 扩展了 InternetState {}class InternetConnected 扩展了 InternetState {最终 ConnectionType connectionType;InternetConnected({@required this.connectionType});}class InternetDisconnected 扩展了 InternetState {}

4.internet_cubit.dart:

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

我们还定义了两个方法 emitInternetConnectedemitInternetDisconnected ,它们将改变实际的 cubit 状态.

确保正确处理流订阅.

import 'dart:async';导入 'package:bloc/bloc.dart';导入'包:connectivity_plus/connectivity_plus.dart';导入 'package:meta/meta.dart';internet_state.dart"部分;类 InternetCubit 扩展了 Cubit<InternetState>{最终的连通性;StreamSubscription 连接性StreamSubscription;InternetCubit({@required this.connectivity}):断言(连接!= null),超级(互联网加载()){连接流订阅 =连接.onConnectivityChanged.listen((连接结果){如果(connectivityResult == ConnectivityResult.wifi){发射互联网连接(ConnectionType.wifi);} else if (connectivityResult == ConnectivityResult.mobile) {发射InternetConnected(ConnectionType.mobile);} else if (connectivityResult == ConnectivityResult.none) {发射InternetDisconnected();}});}void emitInternetConnected(ConnectionType _connectionType) =>发射(互联网连接(连接类型:_connectionType));void emitInternetDisconnected() =>发射(InternetDisconnected());@覆盖未来<void>关闭() {连通性StreamSubscription.cancel();返回 super.close();}}

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

import 'package:connectivity_plus/connectivity_plus.dart';导入 'package:flutter/material.dart';导入'包:flutter_application_4/cubit/internet_cubit.dart';导入'包:flutter_bloc/flutter_bloc.dart';void main() =>runApp(MyApp(connectivity: Connectivity()));class MyApp 扩展 StatelessWidget {最终的连通性;const MyApp({Key key, this.connectivity}) : super(key: key);@覆盖小部件构建(BuildContext 上下文){返回 BlocProvider(创建:(上下文)=>InternetCubit(连接性:连通性),孩子:材料应用程序(title: '连通肘',主页: 脚手架(应用栏:应用栏(title: Text('连通肘聚光灯'),),身体:中心(孩子:列(mainAxisAlignment: MainAxisAlignment.center,孩子们: [BlocBuilder(构建器:(上下文,状态){如果(状态是 InternetConnected &&state.connectionType == ConnectionType.wifi) {返回文本('无线上网',样式:TextStyle(颜色:Colors.green,fontSize:30),);} else if (状态是InternetConnected &&state.connectionType == ConnectionType.mobile) {返回文本('移动的',样式:TextStyle(颜色:Colors.yellow,fontSize:30),);} else if(状态为InternetDisconnected){返回文本('断开',样式:TextStyle(颜色:Colors.red,fontSize:30),);}返回 CircularProgressIndicator();},),],),),),),);}}

I need to check the connectivity in every page inside my application using connectivity library, So i will use a cubit inside the provider. the question is when to close the stream to make it possible to dispose it when the user close the app?

just like this:

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

 

解决方案

1. Make sure you have imported flutter_bloc and connectivity_plus in your pubspec.yaml.

2. Create an InternetCubit files:

  • internet_cubit.dart
  • internet_state.dart

3. internet_state.dart:

Here we create enum with connection types for our cubit and cubit states:

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 {}

4. internet_cubit.dart:

Cubit depends on connectivity plugin, so we import it and create a stream subscription to be able to react on connection changes.

Also we define two methods emitInternetConnected and emitInternetDisconnected that will change actual cubit state.

Make sure to dispose of stream subscription properly.

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();
  }
}

5. In your app main file create an instance of Connectivity plugin and pass it to your BlocProvider. Set up bloc consuming with your needs:

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();
                  },
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

这篇关于我如何使用 cubit 检查连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆