Home > other >  How can I fix instance of 'class name' printed out Flutter
How can I fix instance of 'class name' printed out Flutter

Time:01-02

I'm trying to print forecast.dart, but I'm getting 'instance of WeatherData' printed out. I added @override String toString() but no changes.. I'm not quite sure why forecast.dart is not printed out.. please help!

in weatherData.dart

class WeatherData {
  String? placeName;
  num? temperature;
  num? feels_like;
  num? pressure;
  num? humidity;
  num? wind_speed;

  WeatherData({
    this.placeName,
    this.temperature,
    this.feels_like,
    this.pressure,
    this.humidity,
    this.wind_speed,
  });
  @override
  String toString();
  
  WeatherData.fromJson(Map<String, dynamic> json) {
    placeName = json['city']['name'];
    temperature = json['list'][0]['main']['temp'];
    feels_like = json['list'][0]['main']['temp'];
    pressure = json['list'][0]['main']['temp'];
    humidity = json['list'][0]['main']['temp'];
    wind_speed = json['list'][0]['main']['temp'];
  }
}

in forecast.dart

import 'package:forecast/models/weather_data.dart';

class ForecastData {
  final List list;

  ForecastData({required this.list});

  factory ForecastData.fromJson(Map<String, dynamic> json) {
    var list = json['list']?.map((e) => e)?.toList(growable: true) ?? [];
    List weatherData = [];
    list.forEach((e) {
      WeatherData w = WeatherData(
          placeName: json['city']['name'],
          temperature: e['main']['temp'],
          feels_like: e['main']['temp'],
          pressure: e['main']['temp'],
          humidity: e['main']['temp'],
          wind_speed: e['main']['temp']);

      weatherData.add(w);
      print(weatherData.toList());
    });

    return ForecastData(list: weatherData);
  }
}

output

I/flutter (21227): [Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 'WeatherData', Instance of 

CodePudding user response:

@override
String toString();

You need to actually add an implementation. return the string you want to see when it prints.

CodePudding user response:

You need to implement toString. For example, you could do it like this:

@override
String toString() => 'Weather for ${placeName ?? 'unknown'}';

Alternatively, you could use https://pub.dev/packages/freezed. It automatically generates useful functions (such as fromJson, toJson, toString) for you. You'll save a lot of time this way.

  • Related