当我请求我的API以在地图波动中存储数据时出现的问题

问题描述 投票:0回答:2

当我单击SwitchButton时,我将ID保存在SharedPreferences中。我收回了这个ID,并请求了我的API。

由于有了这个ID,我收回了所有技术。

但是问题是,我的列表在每个ID处重置。

编辑:


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');
    }
  }
}


android mobile flutter flutter-layout
2个回答
0
投票

由于每个API都将覆盖technos,因此先前的数据会丢失。您可以使该technos在该Screen上全局,或者如果您使用BLOC方法。

全局使用List<Technology> technos = [];,不在getTechnologies()中。

可以添加其余内容

technos.add(Technology.fromJson(technoMap));

0
投票

我编辑了方法:

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;
  }

© www.soinside.com 2019 - 2024. All rights reserved.