简体   繁体   English

如何使用ListView.builder管理状态?

[英]How to manage the state with ListView.builder?

So I'm trying to make an app that is requesting images from an API. 因此,我正在尝试制作一个从API请求图像的应用程序。 Before the request is completed, the app displays the error (that red background with yellow letters), but once it has loaded, the widgets are properly displayed. 在请求完成之前,应用程序会显示错误(红色背景和黄色字母),但是一旦加载,就可以正确显示窗口小部件。

加载后我的应用

Each card here is being rendered by a ListView.builder widget, where the data is being passed for each card. 这里的每张卡都由ListView.builder小部件呈现,在该小部件中为每张卡传递数据。 The image of the card is accessed by making a request for an images API, where I randomly select an image through passing a query word (in this case, the name of the country). 可以通过请求图像API来访问卡的图像,其中我通过传递查询词(在本例中为国家/地区名称)来随机选择图像。

The way I'm doing this (not sure if it's the correct way by the way) is by having a getImage method (who has setState call after the request is done) ,that is called in the initState() of the widget. 我这样做的方式(不确定是否是正确的方式)是通过具有getImage方法(在请求完成后调用setState ),该方法在小部件的initState()中调用。

This is part of the code of my card widget: 这是我的卡片小部件代码的一部分:

  String _img;
  bool isLoading = true;

  Future<String> getImage() async {
    String imgURL = await PexelAPI.getImage(widget._country);
    setState(() {
      _img = imgURL;
      isLoading = false;
    });

    return "Data loaded";
  }

  @override
  void initState() {
    super.initState();
    this.getImage();
  }

What I want to do, is access that isLoading , so I can have a CircularProgressIndicator widget before all of the cards are loaded. 我要执行的操作是访问isLoading ,因此在加载所有卡之前,我可以使用CircularProgressIndicator小部件。

How do I do that? 我怎么做?

Since the code is preety big, I'm not sure what I should include here. 由于代码很大,所以我不确定应该在此处包括什么。 So you if need to see any of the code to answer, I'll add it to the post. 因此,如果您需要查看任何要回答的代码,我将其添加到帖子中。

Did you try using a FutureBuilder in the view? 您是否尝试过在视图中使用FutureBuilder? Something like this: 像这样:

Future<String> isDataLoaded;

in the initState(): 在initState()中:

isDataLoaded = getImages();

In the view: 在视图中:

FutureBuilder(
      future: isDataLoaded,
      builder: (BuildContext context, AsyncSnapshot snapshot) {
       return snapshot.hasData 
       ? WIDGET 
       : CircularProgressIndicator();              
      }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM