簡體   English   中英

如何強制 Dart/Flutter 重用具有相同屬性的相同 class

[英]How to force Dart/Flutter to reuse same class with same properties

我的問題很簡單,我有一個 Dart class 像這樣

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在實例化之前)。

當我查看 DevTools 時,我總是在調用 function 時獲得多個 class 實例,盡管它始終是相同的參數,並且垃圾收集器會保持它的事件,盡管我彈出/破壞視圖(ZC047B107EE763AFB6616 上下文中的腳手架)。

現在我只是用一個小的 class 測試它,但如果它是一個大的 class,這將是一團糟,即使我認為在這種情況下垃圾收集器肯定會處理未使用的類,但我想知道如果我能用某種 Dart/Flutter 方式解決這個“問題”。

如果您使用const Weather(...)創建對象,您應該不會再看到多個實例。

觀察垃圾收集器通常不是一個好主意,你可以相信當 GC 算法到達它時它會破壞你的對象。

Dart 的垃圾收集器針對創建許多小對象並將它們一起丟棄而進行了優化。 因此,您可能根本不必擔心這一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM