【问题标题】:Problem when i request my API for store data in map flutter当我请求我的 API 在地图颤动中存储数据时出现问题
【发布时间】:2020-01-25 09:42:18
【问题描述】:

当我点击我的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');
    }
  }
}


【问题讨论】:

  • 这是否意味着technos 列表总是只有一个条目?您可以打印technoList 的大小以确保它正在被重置吗?
  • 我打印了我的 id 字符串和技术专家:1 I/flutter(7137):2 I/flutter(7137):id:2 I/flutter(7137):[{id:1,名称: GitHub}, {id: 2, name: BitBucket}, {id: 3, name: Travis}, {id: 4, name: Docker}] I/flutter (7137): Dans le var: [{id: 1, name: GitHub}, {id: 2, name: BitBucket}, {id: 3, name: Travis}, {id: 4, name: Docker}] 我们可以看到,technolist 没有 id 2 的数据 @ChennaReddy

标签: android mobile flutter flutter-layout


【解决方案1】:

因为您在每个 API 上都覆盖了 technos,因此之前的数据会丢失。 您可以在 Screen 或使用 BLOC 方法时将此 technos 设为全局。

全局使用List&lt;Technology&gt; technos = [];,而不是getTechnologies()

剩下的可以添加

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

【讨论】:

  • 是的,我知道,我测试了这个,但是没有用...我没有 id 1 或 id 2 的技术,这取决于我点击第一个的时间
  • 我编辑了我的帖子,在我的结果中,我的列表中总是有 id 2 的数据
  • 还是错了,这里不应该是全局的,但是在 UI 页面中应该有 List 添加新结果list.add(getTechnologies() ); setstate();
【解决方案2】:

我编辑了我的方法:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-06
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2023-02-08
    • 2019-10-30
    相关资源
    最近更新 更多