简体   繁体   English

使用 Flutter 中的 package 与提供程序的连接

[英]Using connectivity package in Flutter with provider

I am creating a new Flutter project.我正在创建一个新的 Flutter 项目。

I would like to check the internet connectivity status for the whole application using Provider.我想使用 Provider 检查整个应用程序的 Internet 连接状态。

I have included both packages "connectivity" and "provider" in the pubspec.yaml file.我在 pubspec.yaml 文件中包含了“connectivity”和“provider”这两个包。

Then I have changed main.dart as follow, to include a streamprovider for Connectivity plugin:然后我改变了 main.dart 如下,包括连接插件的流提供程序:

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        StreamProvider(
            create: (context) => Connectivity().onConnectivityChanged),
      ],
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        title: 'My New App',
        theme: ThemeData(
          backgroundColor: Colors.white,
        ),
        home: MyHomePage(title: 'My New App Login'),
      ),
    );
  }
}

What should I do on every new class where I want to check the internet connectivity status?在我想检查互联网连接状态的每个新 class 上,我应该怎么做?

I know I have to instatiate the provider:我知道我必须使提供者成立:

var connectionStatus;
connectionStatus = Provider.of<ConnectivityResult>(context);

but then, what should I do to listen to the connectivity status on every class?但是,我应该怎么做才能监听每个 class 的连接状态?

I kept getting an error no matter what I did.无论我做什么,我都不断收到错误。 Kept giving me a null result.一直给我一个null结果。 So I thought I'd see the code behind and lo and behold, what do I find...所以我想我会看到背后的代码,瞧,我发现了什么......

在此处输入图像描述

在此处输入图像描述

I have literally no idea what the problem is or if it's just a problem on my side, rip.我真的不知道问题是什么,或者这只是我这边的问题,撕裂。

EDIT:编辑:

I followed wut moneer did and it works, lol.我跟着 wut moneer 做了,它有效,哈哈。

import 'package:connectivity/connectivity.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        StreamProvider(create: (context) => Connectivity().onConnectivityChanged),
      ],
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        title: 'My New App',
        theme: ThemeData(
          backgroundColor: Colors.white,
        ),
        home: MyHomePage(title: 'My New App Login'),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _connectivityType = 'Init';

  void _getConnectionStatus(ConnectivityResult con) {
    print(con);
    setState(() {
      switch (con) {
        case ConnectivityResult.mobile:
          _connectivityType = 'Mobile';
          break;
        case ConnectivityResult.wifi:
          _connectivityType = 'Wifi';
          break;
        case ConnectivityResult.none:
          _connectivityType = 'None';
          break;
        default:
          _connectivityType = 'Unknown';
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    final con = Provider.of<ConnectivityResult>(context);
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_connectivityType',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => _getConnectionStatus(con),
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

EDIT 2: If ya want to check your internet connection, this is the package for ya.编辑 2:如果您想检查您的互联网连接,就是您的 package。

ConnectivityResult is an enum so you need to compare it. ConnectivityResult是一个枚举,因此您需要对其进行比较。


/// Connection status check result.
enum ConnectivityResult {
  /// WiFi: Device connected via Wi-Fi
  wifi,

  /// Mobile: Device connected to cellular network
  mobile,

  /// None: Device not connected to any network
  none
}

You should also check if the value is null I don't quite remember why您还应该检查该值是否为null我不太记得为什么

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM