今回はデータベースのテーブルを定義しましょう。
dogというテーブルを使用するためにDogというクラスを作成します。
class Dog {
int id;
String name;
int age;
Dog(this.name, this.age);
Dog.withId(this.id, this.name, this.age);
}
まずはテーブルの要素を定義します。
今回作成しているアプリでは犬の名前をStringで_name、年齢をintで_ageとします。
またデータベースにはキーとなるIDが必要でintで_idとします。
そして引数を定義したDogとDog.withIdを作成します。
次にDogオブジェクトをMapオブジェクトに変換するtoMap()という関数を作成します。
上記のコードの7行目以下に下記のコードを追加します。
Map<String, dynamic> toMap() {
var map = Map<String, dynamic>();
if (id != null) {
map['id'] = id;
}
map['name'] = name;
map['age'] = age;
return map;
}
Mapとは型の一つでkeyとそれに対応したvalueと2つの値を対で格納するオブジェクトです。
今回はデータベースを管理するためにデータをMap型で扱わなければならないので、Map型に変更する必要があります。
逆にMapオブジェクトからDogオブジェクトを抽出するためMapを引数に定義したDog.fromMapObject(Map<String, dynamic> map)を作成します。
Dog.fromMapObject(Map<String, dynamic> map) {
this.id = map['id'];
this.name = map['name'];
this.age = map['age'];
}
データベースから受け取ったMap型のテーブルデータをDogクラスで扱うために必要となります。
まとめると以下のコードとなりdog.dartとして保存します。
class Dog {
int id;
String name;
int age;
Dog(this.name, this.age);
Dog.withId(this.id, this.name, this.age);
// Convert a Dog object into a Map object(DogオブジェクトをMapオブジェクトに変換します)
Map<String, dynamic> toMap() {
var map = Map<String, dynamic>();
if (id != null) {
map['id'] = id;
}
map['name'] = name;
map['age'] = age;
return map;
}
// Extract a Dog object from a Map object(MapオブジェクトからDogオブジェクトを抽出します)
Dog.fromMapObject(Map<String, dynamic> map) {
this.id = map['id'];
this.name = map['name'];
this.age = map['age'];
}
}
次回は今回作成したdog.dartを利用してデータベースを構築していきます。
コメント