[英]Problem when i request my API for store data in map flutter
When i clicked in my SwitchButton
, i save the id in SharedPreferences
.当我点击我的
SwitchButton
时,我将 ID 保存在SharedPreferences
中。 I recupered this id and i requested my API.我恢复了这个 ID,并请求了我的 API。
Because with this ID, i recupered all technologies.因为有了这个ID,我恢复了所有的技术。
But the problem, my list is reset at each id.但问题是,我的列表在每个 id 处被重置。
EDIT:编辑:
Theme theme;
List<Technology> technos = [];
class Technology {
int id;
String name;
Technology({this.id, this.name});
factory Technology.fromJson(Map<String, dynamic> json) {
return Technology(
id: json['id'],
name: json['name'],
);
}
Future<List<Technology>> getTechnologies() async {
String id = await Theme().getTheme();
String url = 'http://10.0.2.2:3000/v1/api/theme/${id}/technology';
String token = await Candidate().getToken();
final response = await http.get(url, headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer ${token}',
});
if (response.statusCode == 200) {
List technosList = jsonDecode(response.body);
for (var technoMap in technosList) {
technos.add(Technology.fromJson(technoMap));
}
return technos;
} else {
throw Exception('Failed to load technos');
}
}
}
Because at each API you are overwriting technos
hence previous data is lost.因为在每个
technos
上,您都在覆盖技术,因此以前的数据会丢失。 You can make this technos
global on that Screen
or if you use BLOC
methods.您可以在该
Screen
上将此technos
全局,或者如果您使用BLOC
方法。
Use List<Technology> technos = [];
使用
List<Technology> technos = [];
globally not in getTechnologies()
.全球不在
getTechnologies()
中。
rest is ok to add rest 可以加
technos.add(Technology.fromJson(technoMap));
I edited my method:我编辑了我的方法:
Future<List<String>> getListTheme() async {
List<String> themes = List<String>();
final SharedPreferences preferences = await SharedPreferences.getInstance();
for (String key in preferences.getKeys()) {
if (key == 'token') {
preferences.containsKey(key);
} else {
themes.add(jsonEncode(preferences.getStringList(key)));
}
}
return themes;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.