【问题标题】:How to use this kind of method in global?如何在全球使用这种方法?
【发布时间】:2019-06-05 04:49:50
【问题描述】:

我检查了手机是否连接到互联网。我用过这种方式。它工作得很好。但我每节课都用这种方式。相同的代码重复。我不明白,如何在全局中使用这种代码。

初始化变量

bool isOffline = false;

初始化状态

  @override
  void initState() {
    ConnectionStatusSingleton connectionStatus =
        ConnectionStatusSingleton.getInstance();// connectionStatusSingleton is another class
    _connectionChangeStream =
        connectionStatus.connectionChange.listen(connectionChanged);
    connectionChanged(connectionStatus.hasConnection);
    super.initState();
  }

connectionChanged 方法

void connectionChanged(dynamic hasConnection) {
    setState(() {
      isOffline = !hasConnection;
    });
  }

之后我在小部件中使用 如果连接不可用我显示appBar,

  appBar: isOffline
      ? PreferredSize(
    preferredSize: Size.fromHeight(20.0),
    child: AppBar(
      leading: Container(),
      centerTitle: true,
      backgroundColor: Colors.red,
      title: Text(
        AppTranslations.of(context).text("connection_drop"),
        style: TextStyle(fontSize: 15.0, color: Colors.white),
      ),
    ),
  )
      : null,

【问题讨论】:

    标签: flutter dart flutter-dependencies flutter-navigation


    【解决方案1】:

    您可以使用StreamBuilder 来实现此目的。只需将依赖于 Stream 的小部件包装起来。

    类似这样的:

    void main() {
      runApp(App());
    }
    
    class App extends StatelessWidget {
      const App({Key key}) : super(key: key);
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: Scaffold(
            appBar: AppBar(
              title: StreamBuilder<ConnectivityResult>(
                stream: Connectivity().onConnectivityChanged,
                initialData: ConnectivityResult.none,
                builder: (context, snapshot) {
                  switch (snapshot.data) {
                    case ConnectivityResult.wifi:
                      return Text("we're on a wifi network");
                    case ConnectivityResult.mobile:
                      return Text("we're on a mobile network");
                    case ConnectivityResult.none:
                      return Text('no network connection');
                  }
                },
              ),
            ),
          ),
        );
      }
    }
    

    另外,您可能想看看https://pub.dev/packages/connectivityhttps://pub.dev/packages/data_connection_checker

    要重用 AppBar 小部件,您可以将其提取到自己的类中:

    class MyAppBar extends StatelessWidget {
      ...
      @override
      Widget build(BuildContext context) {
        return AppBar(
          title: StreamBuilder<ConnectivityResult>(
            ...
          ),
        );
      }
      ...
    }
    
    // every time you need it, just pass it as an argument to the `Scaffold`'s `appBar` parameter.
    
    ...
    Scaffold(
      ...
      appbar: MyAppBar();
      ...
    )
    ...
    

    编辑:我已经用实际可行的东西改进了代码示例。

    【讨论】:

    • 参数类型'StreamBuilder'不能赋值给参数类型'PreferredSizeWidget'
    • 错误来了
    • @user9139407 我又做了一次编辑,通过添加initialData: ConnectivityResult.none 并删除不必要的代码来简化代码
    • pub.dev/packages/connectivity 的工作方式是它不检查互联网连接。所以是的,如果您想可靠地确定数据连接是否可用,您可以使用 stackoverflow.com/a/49648870/9139407 如果您仔细阅读该答案的 cmets,您会发现中国无法访问“google.com”,所以也许您会想要 ping 'example.com' 或其他地址(可能是您尝试使用的服务),但请记住,您不应依赖连接状态来发出网络请求,即始终将您的个人请求包装在 @ 987654333@
    • 评论继续:我已经遇到了这个问题并决定创建一个包来处理它。 pub.dev/packages/data_connection_checkerstackoverflow.com/a/49648870/9139407中的方法类似
    猜你喜欢
    • 2016-09-20
    • 1970-01-01
    • 2021-03-05
    • 1970-01-01
    • 1970-01-01
    • 2022-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多