I have an api for fetching gmys and loading the results on a flutter app. I would like the flutter application to load the data and store in cache. When the use visits the page, the flutter application should check if there is internet connection, if there is, data should be loaded from the online api, if there is no internet connection, it should load from cache json file.
Currently the app is fetching from online api only when there is internet. Bellow is my code:
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
class GymList extends StatelessWidget {
final String apiUrl ="apitogetgyms";
Future<List<dynamic>> fetchGyms() async {
var result = await http.get(apiUrl);
return json.decode(result.body)['gyms'];
}
String _name(dynamic gyms) {
return gyms['name'];
}
String _location(dynamic gyms) {
return gyms['location'];
}
String _phone(dynamic gyms) {
return gyms['phone'];
}
String _email(dynamic gyms) {
return gyms['email'];
}
String _img(dynamic gyms){
return gyms['img'];
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Gyms List'),
),
body: Container(
child: FutureBuilder<List<dynamic>>(
future: fetchGyms(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
//print(_name(snapshot.data[]));
return ListView.builder(
padding: EdgeInsets.all(8),
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
return Card(
child: Column(
children: <Widget>[
ListTile(
leading: CircleAvatar(
radius: 30,
backgroundImage:
NetworkImage(snapshot.data[index]['img'])),
title: Text(_name(snapshot.data[index])),
subtitle: Text(_location(snapshot.data[index])),
trailing: Text(_email(snapshot.data[index])),
)
],
),
);
});
} else if (snapshot.hasError) {
return Text("${snapshot.error}");
} else {
return Center(child: CircularProgressIndicator());
}
},
),
),
);
}
}
You can achieve this result by using 2 packages shared_preferences and connectivity.
Using connectivity you can check for your connection status and know if you have access to internet.
import 'package:connectivity/connectivity.dart';
final connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.none) {
// I am not connected.
} else {
// I am connected to internet.
}
Then using shared_preferences you can easily save your JSON and load it when you are not connected to internet.
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
final jsonKey = 'json_key'; // Key used to save and get your data from SharedPreferences.
final prefs = await SharedPreferences.getInstance();
// Save your JSON as a String by encoding it.
await prefs.setString(jsonKey, jsonEncode(myJsonData));
// Get your JSON from SharedPreferences and decode it.
final json = jsonDecode(prefs.getString(jsonKey));
Example
import 'package:connectivity/connectivity.dart';
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
Future<List<dynamic>> fetchGyms() async {
final jsonKey = 'json_key';
final prefs = await SharedPreferences.getInstance();
final connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.none) {
final json = jsonDecode(prefs.getString(jsonKey));
return json['gyms'];
} else {
final result = await http.get(apiUrl);
await prefs.setString(jsonKey, jsonEncode(result.body.toString()));
return jsonDecode(result.body)['gyms'];
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With