5

I have a Flutter FutureBuilder that needs to be updated with new data given by the user. However, the UI elements in the FutureBuilder do not update and still contain the old values. I have checked through print statements that the new data is correctly loaded. The issue seems to be with FutureBuilder rebuilding the widget when the new data is loaded. Any help is appreciated.

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

Here is my global file:

 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']

            )
            );
          }
        }
        }
Rohan D
  • 133
  • 2
  • 9

1 Answers1

3

You don't need to create a Future object :

   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;
  }
diegoveloper
  • 93,875
  • 20
  • 236
  • 194
  • I made this change and it still seems to display the old data. – Rohan D Jan 22 '19 at 18:50
  • I updated the code, could you try again? whats the value of 'new list size: ... ' ? – diegoveloper Jan 22 '19 at 18:58
  • also try to add the code of the PollState , it looks like is incomplete – diegoveloper Jan 22 '19 at 19:00
  • Thank you for your help. I made the changes, but I am getting some compilation errors. Do I need to wrap it in a Future? If not, I probably need to change the return type right? – Rohan D Jan 22 '19 at 19:02
  • sorry I think I forgot the type : final List newList = List(); – diegoveloper Jan 22 '19 at 19:07
  • This solution works and I am able to print the right value. However, none of the UI elements are showing up even though the list length is 1. Any idea why that might be? – Rohan D Jan 22 '19 at 19:14
  • @diegoveloper Could you please help me out to find out the problem on my this question? https://stackoverflow.com/questions/64540805/why-futurebuilder-callback-is-not-calling-after-facebook-logged-in-data-in-flutt – Emon Oct 26 '20 at 16:49