flutter 类型“List”的获取错误< dynamic>不是类型“Map〈String,dynamic>”的子类型

lvmkulzt  于 2023-01-02  发布在  Flutter
关注(0)|答案(2)|浏览(251)

我正在创建一个flutter应用程序来显示列表中的用户。我可以获取和打印数据,但我无法显示数据,因为我得到这个错误Exception has occurred. _TypeError (type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>')
我使用dio包来获取数据。下面是用于进行API调用的代码

class DioClient {
  final Dio _dio = Dio();

  final _farmerUrl = 'https://retoolapi.dev/Rzl99e/farmers';

  Future<Users?> getUser() async {
    Users? users;
    try {
      Response userData = await _dio.get(_farmerUrl);
      print('User Info: ${userData.data}');
      users = Users.fromJson(userData.data);
    } on DioError catch (e) {
      if (e.response != null) {
        print('Dio error!');
      } else {
        print('Error sending request! '+ e.message);
      }
    }
    return users;
  }  
}

这是我用来解析json响应的模型类

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

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

class Users {
    Users({
        this.id,
        this.bio,
        this.email,
        this.lastName,
        this.firstName,
        this.phoneNumber,
        this.memberNumber,
    });

    int? id;
    String? bio;
    String? email;
    String? lastName;
    String? firstName;
    String? phoneNumber;
    String? memberNumber;

    factory Users.fromJson(Map<String, dynamic> json) => Users(
        id: json["id"],
        bio: json["bio"],
        email: json["email"],
        lastName: json["last_name"],
        firstName: json["first_name"],
        phoneNumber: json["phone_number"],
        memberNumber: json["member_number"],
    );

    Map<String, dynamic> toJson() => {
        "id": id,
        "bio": bio,
        "email": email,
        "last_name": lastName,
        "first_name": firstName,
        "phone_number": phoneNumber,
        "member_number": memberNumber,
    };
}

这是我用来显示用户列表的代码

body: SingleChildScrollView(
        child: Center(
          child: FutureBuilder<Users?>(
            future: _client.getUser(),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                Users? userInfo = snapshot.data;
                if (userInfo != null) {
                  return ListTile(
                    title: Text(userInfo.firstName! + ' ' + userInfo.lastName!),
                    subtitle: Text(userInfo.phoneNumber!),
                  );
                }
              }
              return CircularProgressIndicator();
            },
          ),
        ),
      ),

为了完全显示用户列表,我可以做哪些更改。

nwnhqdif

nwnhqdif1#

    • 模型类**
class ModelClass {
  int? id;
  String? bio;
  String? name;
  String? email;
  String? phone;
  String? gender;

  ModelClass(
      {this.id, this.bio, this.name, this.email, this.phone, this.gender});

  ModelClass.fromJson(Map<String, dynamic> json) {
    id = json['id'] as int;
    bio = json['bio'] as String;
    name = json['name'] as String;
    email = json['email'] as String;
    phone = json['phone'] as String;
    gender = json['gender'] as String;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['id'] = id;
    data['bio'] = bio;
    data['name'] = name;
    data['email'] = email;
    data['phone'] = phone;
    data['gender'] = gender;
    return data;
  }
}
    • 通过Getx和Dio进行API调用**
import 'package:dio/dio.dart';
import 'package:get/get.dart';

class Controller extends GetxController {
  final modelCalss = RxList<ModelClass>();

  final _dio = Dio();

  void getData() async {
    try {
      final response = await _dio.get(
        'https://retoolapi.dev/Rzl99e/farmers',
      );
      final data = response.data
          .map((json) => ModelClass.fromJson(json as Map<String, dynamic>))
          .toList()
          .cast<ModelClass>() as List<ModelClass>;
      if (data.isNotEmpty) {
        modelCalss.clear();
        modelCalss.addAll(data);
      }
    } on DioError catch (e) {
      print(e.message);
    }
  }
}
    • 页码**
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class TestPage extends StatelessWidget {
  final getDataController = Get.put(Controller());
  @override
  Widget build(BuildContext context) {
    getDataController.getData();
    return Scaffold(
      body: SingleChildScrollView(
        child: Center(
          child: ListView.builder(
              shrinkWrap: true,
              primary: false,
              itemCount: getDataController.modelCalss.length,
              padding: EdgeInsets.symmetric(horizontal: 10, vertical: 20),
              itemBuilder: (context, index) {
                final item = getDataController.modelCalss[index];

                return ListTile(
                  title: Text(item.name!),
                  subtitle: Text(item.phone!),
                );
              }),
        ),
      ),
    );
  }
}
sr4lhrrt

sr4lhrrt2#

解码数据并以列表格式存储,因为API返回列表数据

return UserRes.fromJsonMap(jsonDecode(userData.data));

为用户列表创建响应类

class UserRes{
  List<Users> content;

  UserRes.fromJsonMap(dynamic data)
      : content = List<Users>.from(
      data.map((sat) => Users.fromJson(sat)));
}

并调用API一样,你的未来将返回列表响应:

final _farmerUrl = 'https://retoolapi.dev/Rzl99e/farmers';

  Future<UserRes> getUser() async {
    try {
      Response userData = await _dio.get(_farmerUrl);
      print('User Info: ${userData.data}');
      return UserRes.fromJsonMap(jsonDecode(userData.data));
    } on DioError catch (e) {
      if (e.response != null) {
        print('Dio error!');
      } else {
        print('Error sending request! '+ e.message);
      }
    }
  }

您可以从UI调用

body: SingleChildScrollView(
        child: Center(
          child: FutureBuilder<Users?>(
            future: _client.getUser(),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                List<Users>? userInfo = snapshot.data;
                if (userInfo != null) {
                  return ListTile( // your data is list format you can bind with listBuilder 
                    title: Text(userInfo.first.firstName! + ' ' + userInfo.first.lastName!),
                    subtitle: Text(userInfo.first.phoneNumber!),
                  );
                }
              }
              return CircularProgressIndicator();
            },
          ),
        ),
      ),

相关问题