【问题标题】:Im getting a - type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>' error我得到一个 - 类型 'List<dynamic>' 不是类型 'Map<String, dynamic>' 的子类型错误
【发布时间】:2021-05-02 04:17:22
【问题描述】:

我在 json 中有一个地图列表,我试图在列表上呈现“标题”。

我通过 api (http.get) 读取数据然后解析它。

我想在列表中显示标题。

这是我的代码...

import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

获取数据

Future<Welcome> fetchAlbum() async {
  final response = await http.get('https://jsonplaceholder.typicode.com/posts');

  if (response.statusCode == 200) {
    // If the server did return a 200 OK response,
    // then parse the JSON.
    return Welcome.fromJson(jsonDecode(response.body));
  } else {
    // If the server did not return a 200 OK response,
    // then throw an exception.
    throw Exception('Failed to load album');
  }
}

转成json

List<Welcome> welcomeFromJson(String str) =>
    List<Welcome>.from(json.decode(str).map((x) => Welcome.fromJson(x)));

String welcomeToJson(List<Welcome> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

模型类欢迎

class Welcome {
  Welcome({
    this.userId,
    this.id,
    this.title,
    this.body,
  });

  int userId;
  int id;
  String title;
  String body;

  factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
        userId: json["userId"],
        id: json["id"],
        title: json["title"],
        body: json["body"],
      );

  Map<String, dynamic> toJson() => {
        "userId": userId,
        "id": id,
        "title": title,
        "body": body,
      };
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  Future<Welcome> futureAlbum;

  @override
  void initState() {
    super.initState();
    futureAlbum = fetchAlbum();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fetch Data Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Fetch Data Example'),
        ),
        body: Center(
          child: FutureBuilder<Welcome>(
            future: futureAlbum,
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return new Text(snapshot.data.title);
              } else if (snapshot.hasError) {
                return Text("${snapshot.error}");
              }

              // By default, show a loading spinner.
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}

我收到一条错误消息,提示“类型 'List' 不是类型 'Map' 的子类型”

【问题讨论】:

  • 您可以添加服务器对问题的响应吗?
  • 如果我们能看到您收到的 JSON 响应将会很有帮助
  • JSON 响应是什么意思?它得到了 200
  • JSON 响应是指您在 response.body 中获得的内容
  • 你希望每篇文章都显示还是只显示一篇文章

标签: json flutter


【解决方案1】:

将您的 fetchAlbum 函数更改为此

Future<List<Welcome>> fetchAlbum() async {
    final response =
        await http.get('https://jsonplaceholder.typicode.com/posts');

    if (response.statusCode == 200) {
      // If the server did return a 200 OK response,
      // then parse the JSON.
      // return Welcome.fromJson(jsonDecode(response.body));
      var jsonData = jsonDecode(response.body);
      List<Welcome> welcome = [];

      for (var v in jsonData) {
        Welcome w1 = Welcome(
            userId: v['userId'],
            id: v['id'],
            title: v['title'],
            body: v['body']);
        welcome.add(w1);
      }
      return welcome;
    } else {
      // If the server did not return a 200 OK response,
      // then throw an exception.
      throw Exception('Failed to load album');
    }
  }

FutureBuider 小部件将是这个

child: FutureBuilder(
            future: fetchAlbum(),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return ListView.builder(
                    itemCount: snapshot.data.length,
                    itemBuilder: (context, index) {
                      return Container(
                        margin: EdgeInsets.all(8),
                        child: Column(
                          children: [
                            Text("User Id = ${snapshot.data[index].userId}"),
                            Text("Id = ${snapshot.data[index].id}"),
                            Text("Title = ${snapshot.data[index].title}"),
                            Text("Body = ${snapshot.data[index].body}"),
                          ],
                        ),
                      );
                    });
              } else if (snapshot.hasError) {
                return Text("${snapshot.error}");
              }

              // By default, show a loading spinner.
              return CircularProgressIndicator();
            },
          ),

【讨论】:

  • 非常感谢...你能解释一下这段代码吗:``` List welcome = []; for (var v in jsonData) { Welcome w1 = Welcome( userId: v['userId'], id: v['id'], title: v['title'], body: v['body']);欢迎.add(w1); } 返回欢迎; ```
  • 我正在创建一个欢迎对象列表。遍历 jsonData。由于您已经为 Welcome 类定义了一个构造函数,因此我通过将值传递给 Welcome 对象并将它们添加到列表中,将每行 jsonData 转换为 Welcome 对象。
猜你喜欢
  • 2021-04-13
  • 2019-01-22
  • 2021-07-01
  • 2021-12-29
  • 2023-01-08
  • 2021-10-25
  • 2020-07-03
  • 2019-12-05
  • 2023-03-11
相关资源
最近更新 更多