Flutter FutureBuilder未更新

时间:2019-01-22 17:32:27

标签: dart flutter

我有一个Flutter FutureBuilder,需要使用用户提供的新数据进行更新。但是,FutureBuilder中的UI元素不会更新,仍然包含旧值。我已经通过打印语句检查了新数据是否正确加载。问题似乎与FutureBuilder在加载新数据时重建小部件有关。任何帮助表示赞赏。

Future<List<PollItem>> fetchPost(String loc) async {
  return new Future(() async {

    final response = await http
        .post(restip + '/getPosts',
        body: {"data": loc});

    if (response.statusCode == 200) {
      print(response.body);

      // If the call to the server was successful, parse the JSON
      // This function adds json to list
      PollItem.fromJson(json.decode(response.body));

      // list is a list of posts gathered based on the string criteria
      return list;
    } else {
      throw Exception('Failed to load polls');
    }
  });
}

class PollState extends State<Poll> {
  TextEditingController textc = new TextEditingController();

  static String dropDowntext = "City";
  String _name = "Search";
  final _names = [''];


  Widget build(BuildContext context) {

    print("dropdown"+dropDowntext);
    textc.text = _name;
    print(dropDowntext);
    return FutureBuilder<List<PollItem>>(
      future: fetchPost(dropDowntext),
      initialData: [PollItem()],
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          print(snapshot.data[0].question);
          });
}

这是我的全局文件:

 List<PollItem> list = new List();
      factory PollItem.fromJson(Map<String, dynamic> json) {
        int len = json['length'];
        if(listNum!=len) {
          listNum = len;
          list.clear();
          for (int i = 0; i < len; i++) {
            list.add(PollItem(
              answer1: json[i.toString()]['answer1'],
              location: json[i.toString()]['location']

            )
            );
          }
        }
        }

1 个答案:

答案 0 :(得分:1)

您无需创建Future对象:

   Future<List<PollItem>> fetchPost(String loc) async {
    final response = await http.post(restip + '/getPosts',body: {"data": loc});

      if (response.statusCode == 200) {
        print(response.body);
        final data = json.decode(response.body);
        int len = data['length'];
        final List<PollItem> newList = List();
        for (int i = 0; i < len; i++) {
          newList.add(PollItem(
          answer1: data[i.toString()]['answer1'],
          location: data[i.toString()]['location']
            )
          );
        }

        print("new list size: ${newList.length}");

        return newList;
      } else {
        throw Exception('Failed to load polls');
      }
      return null;
  }