Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 994
User 6683331 Avatar asked Apr 19 '26 06:04

User 6683331


1 Answers

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()
}
like image 67
Augustin R Avatar answered Apr 21 '26 21:04

Augustin R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!