【问题标题】:How to make network calls when flutter app changes from offline to online?Flutter App从离线变为在线时如何进行网络调用?
【发布时间】:2020-10-18 03:29:08
【问题描述】:

我正在开发一个 Flutter 应用程序,该应用程序在离线时以对象的形式将数据存储在数据库中。 当用户重新上线时,应用程序必须发出所有发布请求。是否有可能找出用户何时重新上线,即使用户在另一个应用程序上或被锁定,我也可以这样做。

【问题讨论】:

    标签: flutter bloc


    【解决方案1】:

    您可以使用包connectivity
    并创建一个流来监听连接变化。

    定义一个流:

    StreamSubscription<ConnectivityResult> networkSubscription;
    

    在 initState() 方法中添加:

    networkSubscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
        // This will be called every time a connectivity change happens
        try {
            final result = await InternetAddress.lookup('google.com');
            if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
                print('Connected to internet');
                // Connectivity changed from disconnected to connected
            }
        } on SocketException catch (_) {
            print('Not connected to internet');
            // Connectivity changed from connected to disconnected 
        }
    });
    

    别忘了处理流:

    @override
    void dispose() {
        networkSubscription.cancel();
        super.dispose();
    }
    

    当应用程序关闭或在后台时,我不知道该怎么做。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-27
      相关资源
      最近更新 更多