Home > OS >  Why Does Print Statement show "Instance of 'SymbolModel" for Each One of my List Item
Why Does Print Statement show "Instance of 'SymbolModel" for Each One of my List Item

Time:12-24

I am trying to call an API and return a list to a FutureBuilder, but I am not getting the desired output.

Also, tried a few different other ways but I am not get the desired output.

Data:

{
  "count": 24,
  "result": [
    {
      "description": "XPRESSPA GROUP INC",
      "displaySymbol": "XSPA",
      "symbol": "XSPA",
      "type": "Common Stock"
    }
   ]
}

Model:

import 'package:json_annotation/json_annotation.dart';
part 'symbol_model.g.dart';

@JsonSerializable()
class SymbolModel {
  SymbolModel({
    required this.description,
    required this.displaySymbol,
    required this.symbol,
  });

  final String description;
  final String displaySymbol;
  final String symbol;

  factory SymbolModel.fromJson(Map<String, dynamic> json) =>
      _$SymbolModelFromJson(json);

  Map<String, dynamic> toJson() => _$SymbolModelToJson(this);
}

Service:

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'models/symbol_model.dart';

class SymbolService with ChangeNotifier {
  Future<List<SymbolModel>?> fetchSymbol(String symbol) async {
    final url = Uri.parse(
        "https://finnhub.io/api/v1/search?token=sandbox_buojqn748v6s5prikbg0&q=$symbol");

    try {
      final response = await http.get(url);
      List<SymbolModel> loadedProducts = [];
      if (response.statusCode == 200) {
        Map extractedData = jsonDecode(response.body);
        List<dynamic> dataList = extractedData['result'];
        notifyListeners();

        return dataList.map((json) => SymbolModel.fromJson(json)).toList();
      }
    } catch (e) {
      print('error $e');
    }
  }
}

FutureBuilder:

return FutureBuilder(
      future: Provider.of<SymbolService>(context, listen: false)
          .fetchSymbol(query.toLowerCase()),
      builder: (ctx, dataSnapshot) {
        if (dataSnapshot.connectionState == ConnectionState.done &&
            dataSnapshot.hasData) {
          var counter = dataSnapshot.data;
          print('test ${counter}');

The result of print('test ${counter}'):

[Instance of 'SymbolModel', Instance of 'SymbolModel', Instance of 'SymbolModel', Instance of 'SymbolModel', Instance of 'SymbolModel']

What could be the reason why this is happening?

CodePudding user response:

Because your SymbolModel is an object that doesn't override toString() method. That's why print() doesn't know how to convert it to string to be printed and it just outputs "Instance of 'SymbolModel'". If you're using android studio it can help you to generate it easily

  1. Right click your mouse inside SymbolModel class
  2. Select 'Generate'
  3. Select toString() and it will generate the function for you.
  4. You can customize and remove some of the fields if you don't want them to be printed.
  • Related