首页 > 解决方案 > 如何从博客 API 在我的颤振应用程序中加载“图像”

问题描述

我正在尝试从谷歌博客 API 加载图像,我成功加载了“标题”,但是当我尝试加载“图像”时,调试控制台中出现错误 -

'package:flutter/src/painting/_network_image_io.dart': Failed assertion: line 22 pos 14: 'url != null': is not true.

来自博客 API 的代码:

"author": {
  "id": "123",
  "displayName": "Rajdeep Thakare",
  "url": "https://www.blogger.com/profile/123",
  "image": {
    "url": "//lh3.googleusercontent.com/abcdefg"
  }
},

我的项目中的一段代码:

body: Center(
  child: _isLoading
      ? CircularProgressIndicator()
      : ListView.builder(
          itemCount: this.items != null ? this.items.length : 0,
          itemBuilder: (context, i) {
            final item = this.items[i];
            return Column(
              children: <Widget>[
                Image.network(item["image"]),
                Text(item["title"]),
                Divider(),
              ],
            );
            //return Text("Row: $i");
          }
        ),
),

API 中是否有问题或博主不允许我或我的图像插入技术错误?

==================================================== ================================

是否可以从博客 API 中检索帖子图像 - "selfLink": "https://www.googleapis.com/blogger/v3/blogs/633372055355686443/posts/8104714868335749943", "title": "second post", "content": "\u003cdiv dir=\"ltr\" style=\"text-align: left;\" trbidi=\"on\"\u003e\n\u003cdiv class=\"separator\" style=\"clear: both; text-align: center;\"\u003e\n\u003ca href=\"https://1.bp.blogspot.com/-CbTldBdA_u8/Xn3R8evahLI/AAAAAAAAHJ0/b9gOD6EfI5QL9tXL-w05Qn2Z4eH_qVduQCLcBGAsYHQ/s1600/micheile-henderson-Xgn6rIpBEWo-unsplash.jpg\" imageanchor=\"1\" style=\"margin-left: 1em; margin-right: 1em;\"\u003e\u003cimg border=\"0\" data-original-height=\"1600\" data-original-width=\"1067\" height=\"320\" src=\"https://1.bp.blogspot.com/-CbTldBdA_u8/Xn3R8evahLI/AAAAAAAAHJ0/b9gOD6EfI5QL9tXL-w05Qn2Z4eH_qVduQCLcBGAsYHQ/s320/micheile-henderson-Xgn6rIpBEWo-unsplash.jpg\" width=\"213\" /\u003e\u003c/a\u003e\u003c/div\u003e\n\u003cbr /\u003e\nthis is my second post\u003c/div\u003e\n", "author": {

标签: flutterdart

解决方案


您不能直接通过访问图像 URL,item["image"]因为在您的 JSON 字符串中,URL 嵌套在Author->Image->URL. 如果我们仔细查看错误,它会告诉我们'url != null': is not true这只是意味着您的 URL(也就是item["image"]变量)== null

要访问 URL,您必须通过 JSON 字符串中的键。这是一个示例代码:

import 'dart:convert';

var jsonString = 
""" 
{
  "author": {
    "id": "123",
    "displayName": "Rajdeep Thakare",
    "url": "https://www.blogger.com/profile/123",
    "image": {
      "url": "//lh3.googleusercontent.com/abcdefg"
    }
  }
}
""";

void main() {
  var obj = json.decode(jsonString);
  print(obj['author']['image']['url']);  // prints out '//lh3.googleusercontent.com/abcdefg'
}

推荐阅读