dart Flutter:错误:'_Map&lt;String,dynamic&gt;'不是类型'List '的子< dynamic>类型

bihw5rsg  于 11个月前  发布在  Flutter
关注(0)|答案(3)|浏览(131)

我发现了这个错误,我需要帮助解决这个错误:
错误:'_Map<String,dynamic>'不是类型'List '的子类型
URL返回JSON:
{“userId”:1,“id”:1,“title”:“sunt aut facere repelat provisional prosecati excepturi optio reverderit”,“body”:“quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreverderit molestiae ut ut quas totam\nostrum rerum est autem sunt rem eveniet architecto”}**
此代码:API

import 'dart:convert';
import 'dart:ffi';
import 'package:http/http.dart' as http;
import '../model/user_model.dart';

String appUrl = "https://jsonplaceholder.typicode.com/posts/1";

class AppRepostry {
  Future<List<UserModel>> getApp() async {
    http.Response response = await http.get(Uri.parse(appUrl));

    if (response.statusCode == 200) {
      final List resuilt = jsonDecode(response.body);

      return resuilt.map((e) => UserModel.fromJson(e)).toList();
    } else {
      throw Exception(response.reasonPhrase);
    }
  }
}

model:
class UserModel {
  int? userId;
  int? id;
  String? title;
  String? body;

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

  UserModel.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;
  }
}

字符串
用户界面:

class HomePage extends StatelessWidget {
  const HomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return MultiBlocProvider(
        providers: [
          BlocProvider<AppsBloc>(
            create: (BuildContext context) => AppsBloc(AppRepostry()),
          )
        ],
        child: Scaffold(
          appBar: AppBar(
            title: const Text("key app top api"),
          ),
          body: BlocProvider(
            create: (context) => AppsBloc(
              AppRepostry(),
            )..add(LoadAppEvent()),
            child: BlocBuilder<AppsBloc, UsreState>(
              builder: (context, state) {
                if (state is LoadingAppState) {
                  return const Center(
                    child: CircularProgressIndicator(),
                  );
                }
                if (state is LoadedAppState) {
                  List<UserModel> usermodel = state.apps;
                  return ListView.builder(
                      itemCount: usermodel.length,
                      itemBuilder: (_, index) {
                        return Padding(
                          padding:
                              EdgeInsets.symmetric(vertical: 4, horizontal: 8),
                          child: Card(
                            color: Colors.deepPurpleAccent,
                            child: ListTile(
                              title: Text('${usermodel[index].title}'),
                            ),
                          ),
                        );
                      });
                }
                if (state is ErorrAppState) {
                  return const Center(
                    child: Text("No Data ERORR"),
                  );
                }
                return Container();
              },
            ),
          ),
        ));
  }
}

vs3odd8k

vs3odd8k1#

您遇到的错误“_Map<String,dynamic>”不是类型“List”的子类型,这是由于来自API的响应是JSON对象,但您在getApp方法中将其视为列表。
API响应如下所示:
json:

{"userId": 1, "id": 1, "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"}

字符串
它是一个JSON对象({}),而不是一个JSON数组([])。所以,你应该将它解码为Map<String,dynamic>而不是List。
下面是正确的getApp方法:

class AppRepostry {
  Future<List<UserModel>> getApp() async {
    http.Response response = await http.get(Uri.parse(appUrl));

    if (response.statusCode == 200) {
      final Map<String, dynamic> result = jsonDecode(response.body);

      // Since the API returns a single object, we create a List with one element.
      return [UserModel.fromJson(result)];
    } else {
      throw Exception(response.reasonPhrase);
    }
  }
}


通过这种方式,您将响应视为单个项目列表,并将JSON对象解析为UserModel示例。在LoadedAppState块中,您可以像这样访问数据:

List<UserModel> usermodel = state.apps;
UserModel userModel = usermodel[0]; // Since it's a single item list
print(userModel.title); // Accessing the title property


这将解决您面临的错误。

zf9nrax1

zf9nrax12#

https://jsonplaceholder.typicode.com/posts/1响应是一个对象,而不是列表。
目:

{
 ...
 ...
}

字符串
列表中:

{
   [
      ...
   ]
}


因此,在您情况下,更改AppRepostry上的返回值
举例说明:

class AppRepostry {

  /// list ~
  Future<List<PostsEntity>> getPosts() async {
    const endpoint = 'https://jsonplaceholder.typicode.com/posts';
    final http.Response response = await http.get(Uri.parse(endpoint));
    if (response.statusCode == 200) {
      final List<dynamic> result = jsonDecode(response.body);
      return result.map((e) => PostsEntity.fromJson(e)).toList();
    } else {
      throw Exception(response.reasonPhrase);
    }
  }

  /// object
  Future<PostsEntity> getPost(int id) async {
    final endpoint = 'https://jsonplaceholder.typicode.com/posts/$id';
    http.Response response = await http.get(Uri.parse(endpoint));
    if (response.statusCode == 200) {
      // Decode the response body
      var decodedData = json.decode(response.body);
      return PostsEntity.fromJson(decodedData);
    } else {
      throw Exception(response.reasonPhrase);
    }
  }
}

1bqhqjot

1bqhqjot3#

确保来自json的数据是List类型。
不要忘记List不等于List<string,dynamic>。所以List<“1”,User>不等于List。
您必须根据传入的j数据类型创建模型类。

if json came just like this : {...} => Map. So Object. So User
if json came just like this : [{...},{...}] => List. So Object List. So User List

字符串
请看我在medium上的文章,如果还有不明白的地方,告诉我,如果我看到你的留言,我会再帮你的。
我的博客:https://medium.com/@mkiziltay/how-to-generate-model-class-with-dart-from-json-list-555c30289831
如果你阅读并理解了我上面的文章,这将对你非常有用。我解释了如何创建模型类,同时从对象和对象列表中获得答案。

相关问题