如何在从网络接收新项目后重新绘制flutter.io中的小部件网格?

Moo*_*ker 2 user-interface android ios dart flutter

我正在修改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(),
        //));
      });
    });
  }
Run Code Online (Sandbox Code Playgroud)

并且我将其他配方加载到点击界面按钮:

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

但是如何在收到新食谱时重新绘制主页?我已经尝试过你已经看过注释掉的Navigator部分,但它没有用.我也试过了

new PestoDemo();
Run Code Online (Sandbox Code Playgroud)

但它只显示了一个新的配方,并不觉得是一种重新绘制的正确方法.

小智 6

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

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

例如:

setState(() {
  _recipes.add(job);
});
Run Code Online (Sandbox Code Playgroud)

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

另一个提示:当你得到HttpClientResponse时,你应该检查mountedState对象的属性.如果mounted为false,则表示已从树中删除窗口小部件,您可能希望忽略网络响应.