flutter - 如何调用方法并检索嵌套在flutter中的json数组

标签 flutter dart http-post

我新使用了 flutter 。我有模型,但我不知道调用方法并检索要在ui(interface)中显示的数据。我用的是http包。

这是我的代码模型

import 'dart:convert';

MutasiRekResponse myModelFromJson(String str) => MutasiRekResponse.fromJson(json.decode(str));
String myModelToJson(MutasiRekResponse data) => json.encode(data.toJson());

class MutasiRekResponse {
    String responseCode;
    String responseMessage;
    String date;
    String time;
    List<Content> content;

    MutasiRekResponse({
        this.responseCode,
        this.responseMessage,
        this.date,
        this.time,
        this.content,
    });

    factory MutasiRekResponse.fromJson(Map<String, dynamic> json) => MutasiRekResponse(
        responseCode: json["responseCode"],
        responseMessage: json["responseMessage"],
        date: json["date"],
        time: json["time"],
        content: List<Content>.from(json["content"].map((x) => Content.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "responseCode": responseCode,
        "responseMessage": responseMessage,
        "date": date,
        "time": time,
        "content": List<dynamic>.from(content.map((x) => x.toJson())),
    };
}

class Content {
    String postingDate;
    String valueDate;
    String inputDate;
    String inputTime;
    String desc;
    String noReff;
    String amount;
    String balance;

    Content({
        this.postingDate,
        this.valueDate,
        this.inputDate,
        this.inputTime,
        this.desc,
        this.noReff,
        this.amount,
        this.balance,
    });

    factory Content.fromJson(Map<String, dynamic> json) => Content(
        postingDate: json["postingDate"],
        valueDate: json["valueDate"],
        inputDate: json["inputDate"],
        inputTime: json["inputTime"],
        desc: json["desc"],
        noReff: json["noReff"],
        amount: json["amount"],
        balance: json["balance"],
    );

    Map<String, dynamic> toJson() => {
        "postingDate": postingDate,
        "valueDate": valueDate,
        "inputDate": inputDate,
        "inputTime": inputTime,
        "desc": desc,
        "noReff": noReff,
        "amount": amount,
        "balance": balance,
    };
}

我正在使用http发布包,请咨询代码:
    static Future<MutasiRekResponse> (String accNumber, String startDate, String endDate) async {
    String apiURL = "URL";
    var credentials = base64.encode(bytes);
    var headers = {
      "Content-Type": "application/json",
      "Authorization": "Basic $credentials"
    };
    var requestBody = jsonEncode(
        {'accNumber': accNumber, 'startDate': startDate, 'endDate': endDate});
    http.Response apiResult =
        await http.post(apiURL, body: requestBody, headers: headers);
    if (apiResult.statusCode == 200) {
      apiResult.body;
    } else {
      Exception('failed to load data');
    }
    final jsonObject = json.decode(apiResult.body);
    final _postResult = MutasiRekResponse(jsonObject);
    return _postResult;
  }

如何使用正确的http.pos以及如何在ui(interface)中调用方法和检索数据。谢谢。

最佳答案

Future -基于与Future交互的最新快照构建自身的小部件。

我添加了一个代码段,用于在ListView中显示内容列表(降序和日期)。

Widget contentList() {
  return FutureBuilder(
    builder: (BuildContext context, AsyncSnapshot<MutasiRekResponse> dataSnapshot) {
      if (dataSnapshot.connectionState == ConnectionState.none &&
        dataSnapshot.hasData == null) {
        return Container(child: Text('Something went wrong'));
      }
      return ListView.builder(
        itemCount: dataSnapshot.data.content.length,
        itemBuilder: (context, index) {
          return Column(
            children: <Widget>[
              Text(dataSnapshot.data.content[index].desc);
              Text(dataSnapshot.data.content[index].balance);
            ],
          );
        },
      );
    },
    future: getMutasiDetails('your account number', '05/03/2020', '10/03/2020), // Your async function
  );
}

static Future<MutasiRekResponse> getMutasiDetails(String accNumber, String startDate, String endDate) async {
  String apiURL = "your api url";
  var credentials = base64.encode(bytes);
  var headers = {
    "Content-Type": "application/json",
    "Authorization": "Basic $credentials"
  };

  var params = Map<String, dynamic>();
  params['accNumber'] = accNumber;
  params['startDate'] = startDate;
  params['endDate'] = endDate;

  http.Response apiResult =
      await http.post(apiURL, body: params, headers: headers);
  if (apiResult.statusCode == 200) {
    return MutasiRekResponse.fromJson(json.decode(apiResult.body));
  } else {
    throw Exception('failed to load data');
  }
}


@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: Text('Content List'),
    ),
    body: contentList(),
  ); 
}

关于flutter - 如何调用方法并检索嵌套在flutter中的json数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60537740/

相关文章:

flutter - 在 flutter 中更新现有 StatefulWidget 类的小部件

flutter - 为什么 Hero 不能与 Multiprovider 一起使用?

flutter - 使用 Flutter 的 firebase_admob 插件时找不到 FirebaseAdMobPlugin.h 文件

javascript - 如何在网站中做向导?

JAVA发送包含XML字符串的Post请求

android - ui.PictureRecorder() 在 flutter 中给出空白输出?

函数作为另一个函数中的参数 - Dart

dart - Dart:程序跳过一行

android - Flutter - setState 不更新内部有状态小部件

java - 仅在异步任务完成后才需要运行任务