0

I'm uploading some user data into firebase's database, but one of the variables is the background color, which is of type Color.

Unhandled Exception: Invalid argument: Instance of 'Color'

How can I upload that? Until now I've only used the type string in the collection.

This is what I'm using:

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

What type (for the variable Color) should I choose in the collection? Or should I change something in the code? The code does work though, because for the variables of type string it didn't throw an exception.

Elias Marrero
  • 187
  • 2
  • 15
  • 1
    The Firebase Realtime Database and Cloud Firestore are two separate databases. Please only mark your question with the relevant tag, not with both. – Frank van Puffelen May 26 '20 at 13:42
  • 1
    firebase doesnt know what is `Color`, so you have to convert it to text or some other value which you can decode later when you fetch it. – Adnan karim May 26 '20 at 13:42

2 Answers2

2

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.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
1

Your best option is probably json encoding. Here is a link with a good example.

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

After you have the json you can just store it as text in a DB.

Benedikt J Schlegel
  • 1,707
  • 1
  • 10
  • 23