Home > Software engineering >  how to display fetched data from server using Rest APi, after internet connection is lost?
how to display fetched data from server using Rest APi, after internet connection is lost?

Time:02-19

I Build a Flutter chat app, using Rest Api, I fetched all User from the server using http.GET, request and display as Listview as shown in my code below, but User is Displayed as a ListView only if there is an Internet Connection, if Internet connection is lost. I get a blank Screen. I call fetchData(); method inside ininState({}) to fetch all user when the app opens for the first time , and I store all user in a List, it works fine, but if internet connection is lost, I got black screen. I want to display already fetched user even if internet connection is lost.

import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:taxiyee_messaging_app/models/message_model.dart';
import 'package:taxiyee_messaging_app/screens/chatscreen.dart';
import 'package:http/http.dart' as http;
import 'package:taxiyee_messaging_app/screens/login_screen.dart';

import '../models/usermodel.dart';

class ChatList extends StatefulWidget {
  bool items;
  ChatList({required this.items});

  @override
  State<ChatList> createState() => _ChatListState();
}


class _ChatListState extends State<ChatList> {
  late Future<dynamic> futureUser;
  List<User> userList = [];
  List<User> myuserList = [];
   bool items =true;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    futureUser = fetchData();
  }

  @override
  Widget build(BuildContext context) {
    return items? ListView.builder(
      shrinkWrap: true,
      itemCount: userList.length,
      itemBuilder: (BuildContext context, int index) {
        var user = userList[index];
        var sender = userList[index].sender;
        return Column(
          children: [
            ListTile(
              onTap: () {
                Navigator.push(context, MaterialPageRoute(
                    builder: (BuildContext context){
                      return Chatscreen(user:User(message: user, sender: sender));
                    }));
              },
              leading: const CircleAvatar(
                radius: 30,
                child: Icon(Icons.person),
              ),
              trailing: const CircleAvatar(
                child: Text("2"),
              ),
              title: Text(sender["name"]),
              subtitle: Text(user.message),
            ),
            const Divider(
              thickness: 0.5,
              color: Colors.blue,
            ),
          ],
        );
      },
    ):Container(width: 200,
    height: 400,
    color: Colors.red,);
/////////////
  }
 
  fetchData() async {
    final response = await http.get(
      Uri.parse('https://staging.taxiye.com:7003/chatst'),
      headers: <String, String>{
        'Content-Type': 'application/json; charset=UTF-8',
        "Authorization": authToken,
      },
    );
    if (response.statusCode == 200) {
      print(response.body);
      var values = json.decode(response.body)["allChats"];
      var mychatvalues = json.decode(response.body)["myChats"];
      if (values.length > 0) {
        for (int i = 0; i < values.length; i  ) {
          if (values[i] != null) {
            Map<String, dynamic> map = values[i];
            setState(() {
              userList.add(User.fromJson(map));
            });
          }
        }
      }
      if (mychatvalues.length > 0) {
        for (int i = 0; i < mychatvalues.length; i  ) {
          if (mychatvalues[i] != null) {
            Map<String, dynamic> map = mychatvalues[i];
            setState(() {
              myuserList.add(User.fromJson(map));
            });
          }
        }
      }
    } else {
      // If that call was not successful, throw an error.
      throw Exception('Failed to load post');
    }

    // return
  }
}

CodePudding user response:

You need to store server data in your local database. The flow is:

call api -> store data to local databse -> retrieve from local database.

You can use try-catch method to check whether there is an internet connection.

   try {
         // call api , store to local db, retrieve from local db
        } catch (e) {
          retrieve from local db if no network
        }
  • Related