-1

我正在尝试在 Dart 中设置 Map 的类型,例如,就像在 typescript 中一样,您将使用接口:

    interface Record {
        weight: number;
        date: DateTime;
        note: string;
    }

所以我可以在这样的列表中使用它:

List<Record> records = [...]
4

1 回答 1

2

你不能在 Dart 中这样做,但你可以使用类并执行以下操作:

// Create a record class to store its fields
class Record {
    final double weight;
    final DateTime date;
    final String note;

    const Record({this.weight, this.date, this.note});
}

// Populate your list with some records
final List<Record> records = [
    Record(weight: 10.5, date: DateTime(2021, 1, 1), note: "Light"),
    Record(weight: 100.5, date: DateTime(2021, 1, 29), note: "Heavy"),
    Record(weight: 50, date: DateTime(2021, 5, 22), note: "It's ok"),
];

// Access it later
print(records[0].weight);    // 10.5
print(records[0].date);      // DateTime(2021, 1, 1)
print(records[0].note);      // Light

// Access them all
records.forEach((record) {
    print(record.weight);
    print(record.date);
    print(record.note);
});
于 2021-06-01T04:21:07.037 回答