将数据上传到Cloud Firestore的数据库中

问题描述 投票:0回答:1

我正在将一些用户数据上传到Firebase的数据库中,但是变量之一是背景色,它是Color类型。

Unhandled Exception: Invalid argument: Instance of 'Color'

我该如何上传?到目前为止,我只在集合中使用了type string

这是我正在使用的:

final Color _backgroundColor;
...
onPressed: () {
  _firestore.collection('users').add({
    'backgroundColor': _backgroundColor,
  })
}

我应该在集合中选择什么[[类型(对于变量Color)?还是应该更改代码中的某些内容?该代码确实有效,因为对于type string的变量,它没有引发异常。

firebase flutter google-cloud-firestore
1个回答
0
投票
Firestore只能将特定类型的数据存储为listed here。从该文档中可以看到,它无法存储Flutter的Color类型。

因此,您需要定义自己的从Color到Firestore支持的类型的映射。最常见的是将此类数据存储为字符串或3位数字。请参阅How to convert Flutter color to string and back to a color,特别是有关string conversionnumber conversion的答案。


0
投票
您最好的选择可能是json编码。这是一个带有示例的链接。

https://codetober.com/json-encode-decode-with-flutter/

有了json之后,您可以将其作为文本存储在数据库中。

© www.soinside.com 2019 - 2024. All rights reserved.