【问题标题】:Flutter Future and setstateFlutter Future 和 setstate
【发布时间】:2018-05-15 10:22:13
【问题描述】:

当我获得 API 调用的结果时,我正在尝试添加一个图像小部件。我的代码是:

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 进行硬编码,那么它可以正常工作。

【问题讨论】:

    标签: dart flutter


    【解决方案1】:

    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 被丢弃并创建一个新图像。

    List&lt;Widget&gt; bodyContent = [menu]; 移出build() 方法并使其成为类级字段,您应该会得到所需的结果。

    【讨论】:

    • 非常感谢甘特!
    猜你喜欢
    • 2021-05-11
    • 2020-09-02
    • 2020-11-15
    • 2021-07-11
    • 1970-01-01
    • 2021-03-02
    • 2019-12-29
    • 2021-01-08
    • 2021-03-04
    相关资源
    最近更新 更多