颤动的未来和setstate

时间:2018-05-15 10:22:13

标签: dart flutter

我在尝试获取API调用的结果时尝试添加一个Image小部件。我的代码是:

class AnimalDetailsPage extends StatefulWidget {
  final selection;

  _AnimalDetailsPage createState() => new _AnimalDetailsPage();
  AnimalDetailsPage({Key key, this.selection}) : super(key: key);
}

class _AnimalDetailsPage extends State<AnimalDetailsPage> {

  Future<List> getphotos(horseId) async {
    http.Response response = await http.get(
        Uri.encodeFull(
            "http://myhorses.com/api/getHorsePhotos?horse_id=" +
                horseId));
    return JSON.decode(response.body);
  }

  @override
  Widget build(BuildContext context) {

    final menu = new MyMenuBar();

    List<Widget> bodyContent = [menu];
    dynamic body = new Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: bodyContent,
    );

    if (widget.selection != null) {
      final horse = widget.selection;
      getphotos(horse['id'].toString()).then((res) {
        setState(() {
          bodyContent.add(new Image.network(res[0]['image']));
        });
      });

    } 

    return Scaffold(
      body: body,
    );
  }
}

我无法理解的是setState不会更新视图。如果我将setState移出then语句并对图像src进行硬编码,那么它可以正常工作。

1 个答案:

答案 0 :(得分:4)

bodyContentbuild()

中声明
  @override
  Widget build(BuildContext context) {

    final menu = new MyMenuBar();

    List<Widget> bodyContent = [menu];
    ...
    bodyContent.add(new Image.network(res[0]['image']));
    ...

setState()会导致build再次执行,这意味着保留图像的bodyContent将被丢弃,并创建一个新的。{/ p>

List<Widget> bodyContent = [menu];移出build()方法并将其设为类级别字段,您应该得到所需的结果。