как вызвать метод и получить массив json, вложенный во флаттер - PullRequest
1 голос
/ 05 марта 2020

Я новый подержанный флаттер. У меня есть модель, но я не понимаю, чтобы вызвать метод и получить данные для отображения в интерфейсе. Я использую пакеты http post.

это моя модель кода

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 post package, пожалуйста, код совета:

    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 и как вызвать метод и получить данные в пользовательском интерфейсе. спасибо.

1 Ответ

0 голосов
/ 05 марта 2020

Future - Виджет, который создается на основе последнего снимка взаимодействия с Future.

Я добавил фрагмент кода для отображения списка содержимого (des c и дата) в 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(),
  ); 
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...