Home > Blockchain >  Why it returns Instance of instead of the value?
Why it returns Instance of instead of the value?

Time:07-06

Why the getCurrencyFromAPI function returns Intance of currency instead of the value itself. Is there some thing wrong with my model class?

This is the function

import 'dart:convert';
import 'package:app_bloc/data/models/currency.dart';
import 'package:http/http.dart' as http;
import 'package:app_bloc/constants/api_urls.dart';

class Repository {
  Future<dynamic> getCurrencyFromAPI() async {
    final res = await http.get(Uri.parse(coinbaseURL));

    if (res.statusCode == 200) {
      final resData = jsonDecode(res.body);

      final data = resData['data'] as List;
      List<Currency> list = [];
      for (var e in data) {
        final a = Currency.fromJson(e);
        list.add(a);
      }
      print(list);
    } else {
      throw Exception('Error fetching data from API');
    }
  }
}

void main(List<String> args) {
  Repository repo = Repository();
  repo.getCurrencyFromAPI();
}

this is the model class

class Currency {
  String id;
  String name;
  String minSize;

  Currency({required this.id, required this.name, required this.minSize});

  factory Currency.fromJson(Map<String, dynamic> data) {
    final id = data['id'] as String;
    final name = data['name'] as String;
    final minSize = data['min_size'] as String;
    return Currency(id: id, name: name, minSize: minSize);
  }
}

CodePudding user response:

Your Currency class does not have a toString method. That means it inherits the default from Object which returns Instance of 'Currency'.

When you print the List<Currency> it calls toString on every element to get a string representation. So, that's what you see. It is a Currency object.

Try adding:

  String toString() => "Currency(id: $id, name: $name, minSize: $minSize)";

to you Currency class and see if it makes a difference.

CodePudding user response:

Currency currencyModelFromJson(String str) => Currency.fromJson(json.decode(str));

class Currency {
  String id;
  String name;
  String minSize;

  Currency({required this.id, required this.name, required this.minSize});

  factory Currency.fromJson(Map<String, dynamic> data) {
    final id = data['id'] as String;
    final name = data['name'] as String;
    final minSize = data['min_size'] as String;
    return Currency(id: id, name: name, minSize: minSize);
  }
}

Then do this :


class Repository {
  Future<dynamic> getCurrencyFromAPI() async {
    final res = await http.get(Uri.parse(coinbaseURL));

    if (res.statusCode == 200) {
      final resData = jsonDecode(res.body);

      final data = resData['data'] as List;
      List<Currency> list = [];
      for (var e in data) {
        final a = currencyModelFromJson(e); // change here 
        list.add(a);
      }
      print(list);
    } else {
      throw Exception('Error fetching data from API');
    }
  }
}
  •  Tags:  
  • dart
  • Related