首页 > 解决方案 > 如何在我的颤振应用程序中检索数组数据

问题描述

嗨,我已经成功解析了我的 json 数据,但是当我尝试将它打印到我的屏幕上时,intanse of 'Account' 我对颤振有一点了解,但我正在努力让它成功运行

成功创建一个新帐户后的 Json 响应

    {
  result: { ok: 1, n: 1, opTime: { ts: [Timestamp], t: 2 } },
  ops: [
    {
      seed: 'style nothing better nest nation future lobster garden royal lawsuit mule drama',
      account: [Array],
      _id: 604604c38fbb1e00fea541ce
    }
  ],
  insertedCount: 1,
  insertedIds: { '0': 604604c38fbb1e00fea541ce }
}

模型:

import 'dart:convert';

Wallet walletFromJson(String str) => Wallet.fromJson(json.decode(str));

String walletToJson(Wallet data) => json.encode(data.toJson());

class Wallet {
    Wallet({
        this.seed,
        this.account,
    });

    String seed;
    List<Account> account;

    factory Wallet.fromJson(Map<String, dynamic> json) => Wallet(
        seed: json["seed"],
        account: List<Account>.from(json["account"].map((x) => Account.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "seed": seed,
        "account": List<dynamic>.from(account.map((x) => x.toJson())),
    };
}

class Account {
    Account({
        this.privateKey,
        this.address,
    });

    String privateKey;
    String address;

    factory Account.fromJson(Map<String, dynamic> json) => Account(
        privateKey: json["privateKey"],
        address: json["address"],
    );

    Map<String, dynamic> toJson() => {
        "privateKey": privateKey,
        "address": address,
    };
}

以及创建新钱包的部分。我实际上可以检索种子短语,但未显示帐户列表

Future<Wallet> createWallet(String number) async {
  final String apiUrl = "http://localhost:3000/createNewone";
  
  final response = await http.post(apiUrl, body: {"number": number});
  


  if (response.statusCode == 200 || response.statusCode == 201) {
    
    final String responseString = response.body;
    
    
    return walletFromJson(responseString);
  } else {
    return null;
  }
}

标签: flutterdart

解决方案


为了在屏幕上显示更有意义的消息,您必须覆盖toString()模型中的方法。例如在您的Account班级中添加:

@override
String toString() {
    return 'Account{privateKey: $privateKey, address: $address}';
}

推荐阅读