I am trying to Cache JSON data, everything in my code is working fine, but the problem is I don't want to request getting the data from api and display it every time, which makes the app very slow, so I want to Cache data on the device and updated every week. i dont know how to do that, please help.
here is my code
class AnimalJoke extends StatefulWidget {
const AnimalJoke({Key? key}) : super(key: key);
@override
_AnimalJokeState createState() => _AnimalJokeState();
}
class _AnimalJokeState extends State<AnimalJoke> {
Future getData() async {
var response = await http.post(
Uri.parse("https://here is endpont api"),
);
var responsebody = jsonDecode(response.body);
print('connected succsefully');
return responsebody;
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
automaticallyImplyLeading: true,
backgroundColor: Colors.black,
title: Text("طرائف عن الحيوانات"),
centerTitle: true,
),
backgroundColor: Colors.yellowAccent,
body: FutureBuilder(
future: getData(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
List snap = snapshot.data;
if (snapshot.connectionState == ConnectionState.waiting) {
return Center(child: CircularProgressIndicator());
}
if (snapshot.hasError) {
return Center(
child: Text("error"),
);
}
return ListView.builder(
itemCount: snap.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(
" ${snap[index]['joke']}",
textDirection: TextDirection.rtl,
style:
TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
),
subtitle: Text(
" ${snap[index]['answer']}",
textDirection: TextDirection.rtl,
style: TextStyle(fontSize: 18),
),
);
});
},
),
),
);
}
}
CodePudding user response:
You can do this two ways, One is using your data in local DB and another one is using dio cache library Library Link. Please check the details in the library documentation.
Dio().get(
"http://www.google.com",
options: buildCacheOptions(Duration(days: 7)),
);
CodePudding user response:
You can use SharedPreference to save data to your phone once the api has done loading. You can also save a date/time when the api data was loaded. Check your shared preference data everytime the app is ran with current system date n time. If one week has passed, delete shared pref data and recall api to load list. Hope it's clear
