我正在修改香蒜酱示例 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(),
//));
});
});
}
我将加载其他食谱绑定到单击界面按钮:
floatingActionButton: new FloatingActionButton(
child: new Icon(Icons.edit),
onPressed: () {
scaffoldKey.currentState.showSnackBar(new SnackBar(
content: new Text('Adding new recipe')
));
loadMore(context, "test");
},
),
但是,收到新食谱后如何重新绘制主页?我试过您看到的带有导航器的部分被注释掉了,但它不起作用。我也试过
new PestoDemo();
但它只展示了一会儿新食谱,感觉不像是重新绘制的正确方法。
每当更改影响给定 State 对象的 build(( 函数返回的数据时,都应该调用 setState:
https://docs.flutter.io/flutter/widgets/State/setState.html
例如:
setState(() {
_recipes.add(job);
});
如果您这样做,我建议将 kPestoRerecies 从全局常量更改为 State 子类的私有成员变量。 这可能涉及将列表从一个小部件传递到另一个小部件,而不是让所有小部件都引用全局常量。
另一个提示:当您获得 HttpClientResponse 时,您应该检查 State 对象的 mounted
属性。 如果mounted
为 false,则表示该小部件已从树中删除,您可能希望忽略网络响应。