我想在 Flutter App 的 Listview 中显示我的 Json 数据

I want to show My Json Data in Listview in Flutter App

我想在列表视图中显示我所有的 json 数据。但问题是,当我想在列表视图中获取 idEmployee、officeID、avater 和 fullName 时,它​​显示错误。

type 'String' in not a subtype of type 'int'.

当我想使用 FutureBuilder 仅显示 fullName 时。如果我在模型 class 中注释所有没有全名的变量,它工作正常。但是当我想在没有全名的情况下添加任何其他数据时,它显示错误。

这是我想在列表视图中显示的 json 数据

{
    "success": true,
    "data": {
        "count": 259,
        "data": [
            {
                "idEmployee": 3559,
                "avatar": "f8b8ad832a591db9c86a157a3739d98b.jpg",
                "fullName": "A X C",
                "officeID": "1003559",
                "email": "",
                "designation": "Account Manager",
                "department": "Accounts",
                "mobileNumber": "",
                "workStation": "Software Office",
                "businessUnit": "EMD"
            }
        ]
    },
    "id": 2899
}

这是我的模型Class

class ListAlbum {
  final int idEmployee;
  final String avatar;
  final String fullName;
  final int officeID;
  final String email;
  final String designation;
  final String department;
  final String mobileNumber;
  final String workStation;
  final String businessUnit;

  ListAlbum({
    required this.idEmployee,
    required this.avatar,
    required this.fullName,
    required this.officeID,
    required this.email,
    required this.designation,
    required this.department,
    required this.mobileNumber,
    required this.workStation,
    required this.businessUnit,
  });

  factory ListAlbum.fromJson(Map<String, dynamic> json) {
    return ListAlbum(
      idEmployee: json['idEmployee'],
      avatar: json['avatar'],
      fullName: json['fullName'],
      officeID: json['officeID'],
      email: json['email'],
      designation: json['designation'],
      department: json['department'],
      mobileNumber: json['mobileNumber'],
      workStation: json['workStation'],
      businessUnit: json['businessUnit'],
    );
  }
}

这是我的完整代码

现在我想通过解决这些错误在脚手架中创建和添加带有数据的列表视图。谁能给我示例代码或帮助创建此列表视图?提前致谢。

class OrganizationList extends StatefulWidget {
  const OrganizationList({Key? key}) : super(key: key);

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

class _OrganizationListState extends State<OrganizationList> {
  late Future<ListAlbum> futureAlbum;

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: FutureBuilder<ListAlbum>(
          future: futureAlbum,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              print(snapshot.data);
              return Text(snapshot.data!.fullName);
              // return Text(snapshot.data!.officeID.toString());   // in this line error shows. type 'String' in not a subtype of type 'int'
            } else if (snapshot.hasError) {
              return Text('${snapshot.error}');
            }
            return const CircularProgressIndicator();
          },
        ),
      ),
    );
  }
}

Future<ListAlbum> listData() async {
  final token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjI4OTksImlzcyI6Imh0dHBzOi8vcG9ydGFsLWFwaS5qb21ha2hhdGEuY29tL2FwaS9hdXRoL2xvZ2luIiwiaWF0IjoxNjI5NTI2OTc1LCJleHAiOjE2Mjk2MTMzNzUsIm5iZiI6MTYyOTUyNjk3NSwianRpIjoiRktiT295eEYwaEpDUXMxdiJ9.o4eM_C4hlluHe9Azk0MspPJtYZ7agdpFA6xwKiijLj8';
  String url =
      'https://portal-api.jomakhata.com/api/getOrganizationData?token=${token}';

  Dio dio = new Dio();
  dio.options.headers['Content-Type'] = 'application/json';
  final body = {'limit': 10, 'orderBy': 'idEmployee', 'orderType': 'DESC'};
  final response = await dio.post(url, data: body);

  if (response.statusCode == 200) {
    print(response.statusCode);
    print(response.data);
    var data = ListAlbum.fromJson(response.data["data"]["data"][0]);
    return data;
  } else {
    throw Exception('Failed!');
  }
}

根据你的json数据,你的officeID是一个字符串"officeID": "1003559",

但在 ListAlbum 中,属性定义为整数 final int officeID;

ListAlbum 中的 final int officeID; 更改为 final String officeID;

并且不再需要 .toString()

根据 OP 请求进行编辑以获得更多帮助:

Thank you. i understood. what was my problem. it was a silly mistake for me. can u please help me to create listview in Scaffold to show those data?

Future<List<ListAlbum>> listData() async {
  final token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjI4OTksImlzcyI6Imh0dHBzOi8vcG9ydGFsLWFwaS5qb21ha2hhdGEuY29tL2FwaS9hdXRoL2xvZ2luIiwiaWF0IjoxNjI5NTI2OTc1LCJleHAiOjE2Mjk2MTMzNzUsIm5iZiI6MTYyOTUyNjk3NSwianRpIjoiRktiT295eEYwaEpDUXMxdiJ9.o4eM_C4hlluHe9Azk0MspPJtYZ7agdpFA6xwKiijLj8';
  String url =
      'https://portal-api.jomakhata.com/api/getOrganizationData?token=${token}';

  Dio dio = new Dio();
  dio.options.headers['Content-Type'] = 'application/json';
  final body = {'limit': 10, 'orderBy': 'idEmployee', 'orderType': 'DESC'};
  final response = await dio.post(url, data: body);

  if (response.statusCode == 200) {
    print(response.statusCode);
    print(response.data);
    List<Map<String,dynamic>> data = response.data["data"]["data"];
    List<ListAlbum> albums = data.map((json) => ListAlbum.fromJson(json)).toList();

    
    return albums;
  } else {
    throw Exception('Failed!');
  }
}

然后继续将您的 FutureBuilder<ListAlbum> 编辑为 FutureBuilder<List<ListAlbum>> 和 return 为 Listview.builder。有关如何使用的更多信息 Listview.builder https://flutter.dev/docs/cookbook/lists/long-lists