gpt4 book ai didi

android - 从网络接收到新项目后,如何在 flutter.io 中重绘小部件网格?

转载 作者:IT王子 更新时间:2023-10-29 06:36:18 25 4
gpt4 key购买 nike

我正在修改 Pesto 示例 https://github.com/flutter/flutter/blob/76844e25da8806a3ece803f0e59420425e28a405/examples/flutter_gallery/lib/demo/pesto_demo.dart通过添加以下功能从网上接收新食谱:

  void loadMore(BuildContext context, query) {
HttpClient client = new HttpClient();
client.getUrl(Uri.parse("http://10.0.2.2:5000/search/" + query ))
.then((HttpClientRequest request) {
return request.close();
})
.then((HttpClientResponse response) {
// Process the response.
response.transform(UTF8.decoder).listen((contents) {
// handle data
var decoded = JSON.decode(contents);
var rec = new Recipe(
name: decoded['title'],
author: decoded['author'],
professionIconPath: 'images/1.png',
description: decoded['description'],
imageUrl: 'http://example.jpg',
);
kPestoRecipes.add(job);
//Navigator.push(context, new MaterialPageRoute<Null>(
// settings: const RouteSettings(name: "/"),
// builder: (BuildContext context) => new PestoHome(),
//));
});
});
}

我将加载额外的食谱绑定(bind)到点击界面按钮:

floatingActionButton: new FloatingActionButton(
child: new Icon(Icons.edit),
onPressed: () {
scaffoldKey.currentState.showSnackBar(new SnackBar(
content: new Text('Adding new recipe')
));
loadMore(context, "test");
},
),

但是收到新菜谱后如何重新绘制主页?我试过您看到的 Navigator 部分已被注释掉,但它没有用。我也试过了

new PestoDemo();

但它只显示了一小会儿新配方,而且感觉不是重新绘制的正确方法。

最佳答案

每当您更改影响给定 State 对象的 build() 函数返回内容的数据时,您应该调用 setState:

https://docs.flutter.io/flutter/widgets/State/setState.html

例如:

setState(() {
_recipes.add(job);
});

如果您这样做,我建议将 kPestoRecipes 从全局常量更改为 State 子类的私有(private)成员变量。这可能涉及将列表从一个小部件传递到另一个小部件,而不是让所有小部件都引用全局常量。

另一个提示:当您获得 HttpClientResponse 时,您应该检查 State 对象的 mounted 属性。如果 mounted 为 false,则意味着小部件已从树中删除,您可能希望忽略网络响应。

关于android - 从网络接收到新项目后,如何在 flutter.io 中重绘小部件网格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42041713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com