Josue Guessennd
Josue Guessennd

Reputation: 33

How to retrieve the array data in my flutter app

Hi I've successfully parse my json data but when i try to print it into my screen got intanse of 'Account' I have a little knowledge of flutter but i'm struggling to successfully make it works

Json response after successfully created one new account

    {
  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 }
}

model:

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,
    };
}

and the part to create new wallet. I can actually retrieve the seed phrase but the account list is not shown

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;
  }
}

Upvotes: 1

Views: 159

Answers (1)

Stoyan Milev
Stoyan Milev

Reputation: 735

In order to have a more meaningful message on the screen, you have to override toString() method in your model. For example in your Account class add:

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

Upvotes: 1

Related Questions