【发布时间】:2019-01-22 17:32:27
【问题描述】:
我有一个 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']
)
);
}
}
}
【问题讨论】:
-
你在
PollState的某个地方打电话给setState吗? -
你的“列表”变量是什么?
-
是的,当我获得 dropDowntext 的更新值时,我正在调用 setState。我的列表变量是存储在另一个类中的对象列表。我在问题中添加了代码以反映这一点。
-
你能在返回列表之前打印list.length吗? ?结果如何?
-
是的,我打印了它,它是 1。返回一个数据元素。