我正在将一些用户数据上传到firebase的数据库中,但是变量之一是背景色,它是Color类型。
Unhandled Exception: Invalid argument: Instance of 'Color'
我该如何上传?到目前为止,我只在集合中使用了类型字符串。
这就是我正在使用的:
final Color _backgroundColor;
...
onPressed: () {
_firestore.collection('users').add({
'backgroundColor': _backgroundColor,
})
}
我应该在集合中选择哪种类型(对于变量Color)?还是应该更改代码中的某些内容?该代码确实可以工作,因为对于字符串类型的变量,它没有引发异常。
Firestore can only store data of specific types as listed here. As you can see from that documentation, it cannot store Flutter's
Color
type.So you'll need to define your own mapping from
Color
to and from a type that Firestore supports. Most common is to store such data as a string or a 3-bit number. See How to convert Flutter color to string and back to a color, specifically the answer about string conversion and number conversion.最好的选择可能是json编码。这是一个带有示例的链接。
https://codetober.com/json-encode-decode-with-flutter/
拥有json之后,您可以将其作为文本存储在数据库中。