Flutter - 从 json 中填充未来列表

Flutter - Fill future list from json

我想填写 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 添加 "title" 项目。

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(

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

myList = await fetchTitle();

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

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

  print(myList);
}

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

1- 为 post

创建模型
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 包并从 link https://jsonplaceholder.typicode.com/posts

中获取 post
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 - 使用您在模型中定义的方法来创建包含 posts

的列表
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 return 一个 Future 所以如果你不使用 await 你会得到一个未来而不是列表

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}'));
}

希望对您有所帮助!