首页 > 解决方案 > 在 Flutter 中恢复互联网连接时获取数据

问题描述

我正在开发一个从互联网上获取一些数据的应用程序。为了避免互联网连接出现问题,我添加了连接包

如果应用程序启动时连接了互联网,然后关闭了互联网连接,我可以显示一个带有“无互联网”文本的容器。如果我再次打开互联网,则会显示数据。

实现这一点的代码如下:

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

class CheckNetworkPage extends StatefulWidget {
  @override
  _CheckNetworkPageState createState() => _CheckNetworkPageState();
}

class _CheckNetworkPageState extends State<CheckNetworkPage> {
  StreamSubscription<ConnectivityResult> _networkSubscription;

  Future<List<Data>> fetchData() async {

  // Code to fetch data

 }


  @override
  initState() {
    super.initState();
    fetchData();
    _networkSubscription = Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
     _connectionStatus = result.toString();
     print(_connectionStatus);

     if (result == ConnectivityResult.wifi ||
      result == ConnectivityResult.mobile ||
      result == ConnectivityResult.none) {
      print("Result: $result");
      setState(() {});
  }
    });
  }

// Cancel subscription after you are done
  @override
  dispose() {
    super.dispose();

    _networkSubscription.cancel();
  }

   @override
   Widget build(BuildContext context) {
    // More code. I can use the result of _connectionStatus to build my app
   }
 }

但是,如果应用程序在没有互联网的情况下启动,当我打开它时,数据不会加载,因为它是在initState().

之前没有获取数据并打开互联网连接时如何获取数据

标签: flutterdartconnectivity

解决方案


您可以将最新获取的数据存储在变量中。

List<Data> fetchedData;

Future<List<Data>> fetchData() async {

  // Code to fetch data
  // Add this :
  fetchedData = ...
}

然后在您的侦听器中,检查此数据是否已定义:

if (result == ConnectivityResult.wifi ||
    result == ConnectivityResult.mobile ||
    result == ConnectivityResult.none) {
        print("Result: $result");
        setState(() {});
        // Add this : 
        if (fetchedData == null) fetchData()
}

推荐阅读