【问题标题】:How to implement listview from nested json data using http request in flutter?如何在flutter中使用http请求从嵌套的json数据中实现listview?
【发布时间】:2021-11-08 07:25:10
【问题描述】:

我是 Flutter 的新手。我想对嵌套的 json 数据使用 http 请求,并希望在列表视图中显示该数据。我提出了获取数据的http请求。我得到了 200。但问题是如何返回我对嵌套 json 数据的响应并将这些数据显示给 listview?我阅读了许多文件,但没有正确理解。谁能教我如何实现这个,如果我做错了什么,是什么错误?

来自 json 我还想在我的列表视图中显示“count”、“idEmployee”、“fullname”。

注意:此 API 和令牌仅用于测试目的。

嵌套的 Json 数据

{
    "success": true,
    "data": {
        "count": 261,
        "data": [
            {
                "idEmployee": 3588,
                "avatar": null,
                "fullName": "Moodle Connection Test",
                "officeID": "1003588",
                "email": "",
                "designation": "Senior Executive",
                "department": "Accounts",
                "mobileNumber": "",
                "workStation": "Work Station 12",
                "businessUnit": "CDA"
            }
        ],
    }
}

ListAlbum 模型类

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

  ListAlbum({
    this.idEmployee,
    this.avatar,
    this.fullName,
    this.officeID,
    this.email,
    this.designation,
    this.department,
    this.mobileNumber,
    this.workStation,
    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'],
    );
  }
}

API 调用

Future<List<ListAlbum>> listData() async {
    final response = await http.post(
      Uri.parse('https://portal-api.jomakhata.com/api/getOrganizationData'),
      headers: {
        'Content-Type': 'application/json',
        'Accept': '*/*',
        'Authorization':
        'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjI4OTksImlzcyI6Imh0dHBzOi8vcG9ydGFsLWFwaS5qb21ha2hhdGEuY29tL2FwaS9hdXRoL2xvZ2luIiwiaWF0IjoxNjMxNDYyNTE3LCJleHAiOjE2MzE1NDg5MTcsIm5iZiI6MTYzMTQ2MjUxNywianRpIjoiY2tXUVAya3RsdEJvTHd4QyJ9.9wkcg2n6XgWC1lAj2ZAwHJFMZIVbtg7cmo_jUN86rBo',
      },
      body: jsonEncode(<String, String>{
        'limit': 5.toString(),
        'orderBy': 'idEmployee',
        'orderType': 'DESC'
      }),
    );

    if (response.statusCode == 200) {
      print(response.statusCode);
      print("ok");
      print(response.body);

      return    // here how to return for nested json data?

    } else {
      throw Exception('Failed to create album.');
    }
}

列表视图

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

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

  @override

      _MyAppState createState() {
        return _MyAppState();
      }
    }
    
    class _MyAppState extends State<MyApp> {
      late Future<List<ListAlbum>> futureAlbum;
    
      @override
      void initState() {
        super.initState();
        futureAlbum = listData();
      }
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Create Data Example',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: Scaffold(
            body: Center(
              child: FutureBuilder<List<ListAlbum>>(
                future: futureAlbum,
                builder: (context, snapshot) {
                  if (snapshot.hasData) {
                    print(snapshot.data);
                    return ListView.builder(
                      itemCount: snapshot.data!.length,
                      itemBuilder: (context, index) {
                        final ListAlbum item = snapshot.data![index];
                        return ListTile(
                          title: Text(item.fullName!),
                          subtitle: Text(item.designation!),
                        );
                      },
                    );
                  } else if (snapshot.hasError) {
                    return Text('${snapshot.error}');
                  }
                  return const CircularProgressIndicator();
                },
              ),
            ),
          ),
        );
      }
    }
    

【问题讨论】:

    标签: json flutter api http listview


    【解决方案1】:

    好的,首先,我当然希望这一行:

    Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjI4OTksImlzcyI6Imh0dHBzOi8vcG9ydGFsLWFwaS5qb21ha2hhdGEuY29tL2FwaS9hdXRoL2xvZ2luIiwiaWF0IjoxNjMxNDYyNTE3LCJleHAiOjE2MzE1NDg5MTcsIm5iZiI6MTYzMTQ2MjUxNywianRpIjoiY2tXUVAya3RsdEJvTHd4QyJ9.9wkcg2n6XgWC1lAj2ZAwHJFMZIVbtg7cmo_jUN86rBo
    

    实际上不是您的身份验证凭据,因为解码它需要很少的努力,并且会危及您的整个应用程序。

    现在,关于你的问题,我可能是错的,但如果我没记错的话,http 包将返回一个 JSON 响应作为字符串,所以首先要使用以下方法将其转换为 json:

    Map<String, dynamic> json = jsonDecode(response.data);
    

    然后你可以使用 map 方法来返回模型:

    return json['data']['data'].map<ListAlbum>((value) => ListAlbum.fromJson(value));
    

    还没有测试过,但我相信应该可以。

    【讨论】:

    • 谢谢,但现在仍然显示错误。 FormantException: Unexpected character (at Character 2737) ... 你能帮我实现 listView 中的完整代码吗?
    • 您的 ListView 代码可能不是问题,您得到的错误代码让我认为问题来自 JSON 响应本身(具体来说,字符 2737 似乎不是有效的 JSON)我会复制并将整个 JSON 响应粘贴到 jsonlint.com 中,看看它是否能找出问题所在。
    • 谢谢...解决后端后我会尽力给你反馈!
    猜你喜欢
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-22
    • 2021-10-12
    • 1970-01-01
    • 2020-07-03
    相关资源
    最近更新 更多