简体   繁体   中英

How to force Dart/Flutter to reuse same class with same properties

My question is pretty straightforward, i've a Dart class like so

import 'package:equatable/equatable.dart';
import 'package:meta/meta.dart';

class Weather extends Equatable {
  final String cityName;
  final double tempCelsius;
  final double tempFahrneit;

  const Weather({
    @required this.cityName,
    @required this.tempCelsius,
    this.tempFahrneit,
  });

  @override
  List<Object> get props => [
        cityName,
        tempCelsius,
        tempFahrneit,
      ];
  @override
  String toString() {
    return [
      cityName,
      tempCelsius,
      tempFahrneit,
    ].toString();
  }
}

I'm using Equatable to ease the objects comparison, i also used the const keyword on the class constructor (not sure about this i've heard when used on a class constructor it makes Dart look first if it has the same class with same properties before instanciate it).

When i look up on DevTools, i always get multiple class instances when calling a function although it's always the same parameters, and the garbage collector keep it event though i pop up / destroy the view (Scaffold in Flutter context).

For now i'm just testing it with a small class, but this'll be a mess if it's one big of a class, even though i think in this case the garbage collector will surely dispose the unused classes, but i want to know if i can solve this "problem" with some sort of Dart/Flutter ways.

If you create your objects with const Weather(...) you should not see multiple instances anymore.

Watching the garbage collector is usually not a good idea, you can trust that it will destroy your objects when the GC algorithm gets to it.

Dart's garbage collector is optimized for creating many small objects and throwing them away together. So you probably do not have to worry about this at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM