【问题标题】:Flutter/Dart Class Instance and Class VariableFlutter/Dart 类实例和类变量
【发布时间】:2020-09-29 03:47:06
【问题描述】:

我是 dart 新手,在类中存储数据时遇到问题。我知道如何创建实例,但我想将每个实例存储到我可以轻松访问的地图中。下面是我的代码...

class myCar{
  var myMapOfCars = new Map(); // I wanted this to be a class level variable that I can continuously add or remove from. 

  String carName; // Instance

  myCar({this.carName});

  addInfoToMap() {
    // Some logic to increment the index or create the index the 

    myMapOfCars[theKey]  = this.carName; // This should be the class variable.

  }
}

每次我调用“addInfoToMap”时,“myMapOfCars”实例都会重新初始化并再次为空。我想添加/附加到地图中,这样我就可以在其中拥有尽可能多的汽车。我也对其他解决方案持开放态度,我来自 Swift,我知道你可以在 Swift 中做到这一点。它只是让一切都变得非常干净。

感谢您的帮助!!

【问题讨论】:

标签: class flutter variables dart class-variables


【解决方案1】:

文档“Class variables and methods”将适用于此。

静态变量
静态变量(类变量)对于类范围的状态和 常量:

class Queue {
  static const initialCapacity = 16;
  // ···
}

void main() {
  assert(Queue.initialCapacity == 16);
}

静态变量在使用之前不会被初始化。

静态方法
静态方法(类方法)不对实例进行操作,因此 无权访问此内容。但是,他们确实可以访问静态 变量。如以下示例所示,您调用静态方法 直接在一个类上:

import 'dart:math';

class Point {
  double x, y;
  Point(this.x, this.y);

  static double distanceBetween(Point a, Point b) {
    var dx = a.x - b.x;
    var dy = a.y - b.y;
    return sqrt(dx * dx + dy * dy);
  }
}

void main() {
  var a = Point(2, 2);
  var b = Point(4, 4);
  var distance = Point.distanceBetween(a, b);
  assert(2.8 < distance && distance < 2.9);
  print(distance);
}

您可以使用静态方法作为编译时常量。例如,你 可以将静态方法作为参数传递给常量构造函数。

作为附加参考,您也可以访问this blog

【讨论】:

    猜你喜欢
    • 2012-01-31
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    • 2013-08-16
    • 1970-01-01
    • 2013-03-24
    • 2014-09-21
    相关资源
    最近更新 更多