我想在本地存储上保存数据以使应用程序脱机工作。 我想从api,json数据中获取数据并将其保存到本地存储中, PostList和Post是我的课程
Future <PostsList> fetchPostsList(language) async {
final response =
await http.get('https://sas-survey.urbanway.net/api/questions/1/${language}');
if(response.statusCode == 200){
// storagepost.setItem('resultPost', response.body);
return PostsList.fromJson(json.decode(response.body));
}else{
// return storagepost.getItem('resultPost');
throw Exception('Filed to load post');
}
}
final LocalStorage storagee = new LocalStorage('result_app');
static PostsList resultsListEn = new PostsList();
_addItemEn( String id,
String question,
String photo,
List answers,
String categoryid) {
setState(() {
final resulten = new Post(id: id, title: question, image: photo, answers: answers, category: categoryid);
print(resulten.title.toString());
resultsListEn.posts.add(resulten);
_saveToStorageEn();
});
}
_saveToStorageEn() {
widget.storagee.setItem('en', resultsListEn.toJsonEncodable());
}
new FutureBuilder<PostsList>(
future: fetchPostsList(en),
builder: (context, snapshot){
if(snapshot.hasData){
List<Post> questionsEn =snapshot.data.posts;
questionsEn.forEach((question){
_addItemEn(question.id, question.title, question.image, question.answers, question.category);
});
return Center();
}else if(snapshot.hasError){
return Text("${snapshot.error}");
}
return CircularProgressIndicator();
},
),
这是我的代码,我缺少什么?
答案 0 :(得分:0)
您可以将Shared Preferences用于基本数据。将toJson和fromJson方法添加到模型PostList和Post中,并使用json.decode / encode对其进行序列化并将其另存为字符串。读回时,将其转换回并使用。下面是我如何做的示例。您的代码不够完整,无法进行调整。
get postValue {
var jsonContent = sharedPreferencesInstance.getString('post-key');
if(jsonContent != null) {
return Post.fromJson(json.decode(jsonContent));
}
return null;
}
set postValue(Post post) => sharedPreferencesInstance.setString(
'post-key', json.encode(post.toJson()));