Flutter:在启​​动时执行功能-等待HTTP响应解析器提取图像URL [英] Flutter: Execute a function on Startup - wait for HTTP response parser to extract image URL

查看:26
本文介绍了Flutter:在启​​动时执行功能-等待HTTP响应解析器提取图像URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发Flutter应用,我需要从API中获取几乎所有内容,包括图像,颜色,文本等.因此,我应该做的是构建应用程序的主要结构,然后使用API​​提供的信息填充所有内容.当应用开始获取响应并初始化变量以在应用中使用它们时,我有必要进行API调用(HTTP GET).

I am developing a Flutter app which I need to get almost everything from an API including images, colors, texts, and etc. So what I should do is to build the main structure of the app and then fill-in everything with provided information from API. It is necessary for me to make the API call (HTTP GET) when the app starts to get the response and initialize the variables to use them in the app.

我使用了此处指令来在启动时执行功能.在该函数中,我正在发出HTTP GET请求并解析JSON文件以提取所需的信息.

I used the instruction here to execute a function on startup. In that function, I am making an HTTP GET request and parse the JSON file to extract the information I need.

但是,问题在于flutter不等待HTTP请求的响应,因此我可以使用从接收到的JSON中解析的信息.

However, the problem is that flutter does not wait for the response of the HTTP request so that I can use the parsed information from the received JSON.

因此在下面的代码中,我正在使用getdata()函数来解析JSON,以便从JSON文件中提取ImageURL,然后在NetworkImage中使用该URL.

So here in below code, I am using a getdata() function to parse the JSON in order to extract an ImageURL from a JSON file and then use the URL in NetworkImage.

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(home: HomeScreen());
  }
}

class HomeScreen extends StatefulWidget {
  @override
  HomeScreenState createState() => new HomeScreenState();
}

class HomeScreenState extends State<HomeScreen>
    with AfterLayoutMixin<HomeScreen> {
  @override
  Widget build(BuildContext context) {
    Size screenSize = MediaQuery.of(context).size;

    return Scaffold(
      body: (
      Image.Network(imageurl.toString())
      )
    );
  }
@override
  void afterFirstLayout(BuildContext context) {
    imageURL = getData().toString();
  }

  Future getData() async {
    var res = await http
        .get(Uri.encodeFull(link), headers: {"Accept": "application/json"});
    if (res.statusCode == 200) {
      var data = json.decode(res.body);
      var page = data["page"] as Map;
      var attributes = page["attributes"] as List;

      for (var i = 0; i < attributes.length; i++) {
        if (attributes[i]["key"] == "image") {
          return attributes[i]["value"];
        }
      }
    }
  }
}

在调试时,我意识到当flutter到达getdata()行时,它将执行HTTP请求,但是由于它是异步的,因此它不等待响应,而是继续构建应用程序(因此imageURL变量为为空,因为尚未解析JSON).发生的情况是图像未显示在其位置.

When debugging, I realized that when flutter reaches to getdata() line, it executes the HTTP request but since it is async, it doesn't wait for the response and it continues to build the app (therefore the imageURL variable is empty since the JSON has not been parsed yet). What happens is that the image is not shown in its place.

谢谢.

推荐答案

您的代码内容中包含一些bug,但是如果您确定getData()返回图像链接,则可以使用futureBuilder.然后将您的"build"方法替换为:

your code contents some bugs , but any way , you can use the futureBuilder , if you sure getData() return a image link then replace your "build" method by :

  Widget build(BuildContext context) {
    Size screenSize = MediaQuery.of(context).size;

    return Scaffold(
        body: FutureBuilder<String>(
          future: getData(), // if you mean this method well return image url
          builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
            if(snapshot.connectionState == ConnectionState.done){
              return Image.network(snapshot.data);
            }else if(snapshot.connectionState == ConnectionState.waiting){
              return Text("loading ...");
             }
          },
        )
    );
  }

此代码应显示正在加载",直到getData方法完全执行为止,然后它很好地显示图像取决于返回的URL(应为String)进一步了解" FutureBuilder "

this code should show "loading" until the getData method completely execute , then it well show the image depend on returned URL (should be String) read more about "FutureBuilder"

这篇关于Flutter:在启​​动时执行功能-等待HTTP响应解析器提取图像URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆