【问题标题】:Flutter - Fill future list from jsonFlutter - 从 json 填充未来列表
【发布时间】:2020-07-21 22:30:35
【问题描述】:

我想从 json 中填写一个列表。

Future<List<Titles>> fetchTitle() async {
  String url = "https://jsonplaceholder.typicode.com/posts";

  final response = await http.get(url,headers: {'Content-Type': 'application/json'});
  return titlesFromJson(utf8.decode(response.bodyBytes));

如何使用 fetchTitle 方法填写以下列表。我想从 json 添加“标题”项。

final List myLists = [];


Expanded(
            child: GridView.count(
              crossAxisCount: 2,
              crossAxisSpacing: 10,
              mainAxisSpacing: 10,
              childAspectRatio: 1,
              padding: EdgeInsets.only(left: 20, top: 20, right: 20),
              children:List.generate(myLists.length, (index) {
                return InkWell(

【问题讨论】:

    标签: list flutter future


    【解决方案1】:

    要将 JSON 结果添加到列表中,您可能需要等待响应并将其添加到列表中。由于fetchTitle() 方法返回Future&lt;List&lt;Titles&gt;&gt;,当你等待它时,你会得到一个List&lt;Titles&gt;,它可以分配给你的myList。

    myList = await fetchTitle();
    

    由于我们使用的是await,我们可能需要使用async关键字标记方法。

    void main() async {
      List myList = [];
      myList = await fetchTitle();
    
      print(myList);
    }
    

    【讨论】:

    • await 表达式只能在异步函数中使用。尝试用“async”或“async*”标记函数体。
    • myList 返回“0”项。
    • List.generate(myList .length, (index)
    • 你能更新一下代码吗?如果您正在等待该方法,并在 await 方法调用下方使用您的列表,它应该可以工作。
    • 您的代码运行良好,我看到了这种调试模式。但如果我在 List.generate 中调用它,它会返回“0”
    【解决方案2】:

    从官方文档来看,这是如何从 json 获取数据并将响应转换为模型列表的方法:

    1- 为帖子创建模型

    class Post {
      int userId;
      int id;
      String title;
      String body;
    
      Post({this.userId, this.id, this.title, this.body});
    
      Post.fromJson(Map<String, dynamic> json) {
        userId = json['userId'];
        id = json['id'];
        title = json['title'];
        body = json['body'];
      }
    
      Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['userId'] = this.userId;
        data['id'] = this.id;
        data['title'] = this.title;
        data['body'] = this.body;
        return data;
      }
    }
    

    2 - 导入http包并从链接https://jsonplaceholder.typicode.com/posts获取帖子

    import 'package:http/http.dart' as http;
    
    Future<List<Post>> fetchPosts(http.Client client) async {
      final response = await client
          .get('https://jsonplaceholder.typicode.com/posts');
    
      return parsePosts(response.body);
    }
    

    3 - 使用您在模型上定义的方法创建包含帖子的列表

    import 'dart:convert';
    
    List<Post> parsePosts(String responseBody) {
          final parsed = json.decode(responseBody).cast<Map<String, dynamic>>();
    
          return parsed.map<Post>((json) => Post.fromJson(json)).toList();
        }
    

    4 - 要测试您的代码是否正常工作,请创建一个简单的异步主方法,该方法使用 await 前缀调用 fetchPosts,因为 fetchPosts 返回一个 Future,因此如果您不使用 await,您将得到一个未来而不是 List

    void main() async {
    
      List posts = await fetchPosts(http.Client());
      // this will print the id and the title of posts
      posts.forEach((post) => print('Post id: ${post.id}  |  Post title: ${post.title}'));
    }
    

    希望对你有所帮助!

    【讨论】:

    • 好的,我正在调用这个帖子列表,但返回“0” List.generate(posts.length, (index)
    • 您是否导入了我编写并执行的代码,因为它可以工作,这就是您组织代码应遵循的方式,如果您愿意,该示例会打印列表内的结果长度使用 print(posts.length);
    • 好的,我将代码更改为 FutureBuilder 它可以工作。谢谢。
    猜你喜欢
    • 2019-07-21
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 2019-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多