User 6683331
User 6683331

Reputation: 710

Fetch data when internet connection comes back in Flutter

I'm developing an app that fetchs some data from the internet. In order to avoid issues with the internet connection I added the connectivity package.

If internet is connected when the app starts and then the internet connection is switched off, I can display a Container with the Text of "no internet". If I switch internet on again, the data is displayed.

The code to achive this is the following:

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

However, if the app starts without internet, when I switch it on, the data doesn't load, as it is fetched in initState().

How to fetch the data when it was no fetched before and internet connection is switched on?

Upvotes: 3

Views: 4482

Answers (1)

Augustin R
Augustin R

Reputation: 7829

You could store latest fetched data in a variable.

List<Data> fetchedData;

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

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

Then in your listener, check whether this data is defined :

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

Upvotes: 1

Related Questions