4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

FlutterでColorをFirestoreに保存して、Colorとして取り出す

Posted at

Firestoreではもちろん、Colorという型は保存できません。ですが、FirestoreにColorを保存したい場合どうしたらいいかを考えました。

保存するときはStringで保存する

まずは保存するときは、Stringで保存しました。
FlutterのColorクラスはtoString()にしたときに、いい感じにカラーコードに変換してくれます。

Flutter内部で下記のような実装になっています。

@override
  String toString() => 'Color(0x${value.toRadixString(16).padLeft(8, '0')})';

そこでFirestoreにはこのまま保存しました。

こんな感じ

MaterialColor(primary value: Color(0xff2196f3))

取り出すときはIntで取り出す。

取り出すときはIntで取り出しました。

int get color {
    String valueString = _color.split('(0x')[1].split(')')[0];
    return int.parse(valueString, radix: 16);
  }

そして取り出したら、ColorクラスにこのIntを渡せば、表示されます。

Color(widget.model.color)

以上です。

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?