7

I want to store the color as 'color' in Firestore and retrieve it to add the color of my card ;

but when I add new data then it doesn't get added. Maybe i am storing color value as string and Color doesnot support string. so how can i solve this probleM?

the code is given below -


this is where I call Firestore and add documents(there is a document named 'color')

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

class FirestoreServices {
  final _fireStore = Firestore.instance;

  void addNewMatch(int rScore, int bScore) async {
    if (_fireStore.collection('matches').snapshots() != null) {
      if (rScore > bScore)
        await _fireStore.collection('matches').add({
          'WinnerText': 'Rikesh Wins',
          'RS': rScore,
          'BS': bScore,
          'Score': ('${rScore.toInt()} - ${bScore.toInt()}'),
          'id':
              _fireStore.collection('matches').document().documentID.toString(),
          'date': DateFormat.yMMMd().format(DateTime.now()),
          'color' : Colors.red
        });
      if (bScore > rScore)
        await _fireStore.collection('matches').add({
          'WinnerText': 'Bibin Wins',
          'RS': rScore,
          'BS': bScore,
          'Score': ('${bScore.toInt()} - ${rScore.toInt()}'),
          'id':
              _fireStore.collection('matches').document().documentID.toString(),
          'date': DateFormat.yMMMd().format(DateTime.now()),
          'color' : Colors.green
        });
      if (bScore == rScore)
        await _fireStore.collection('matches').add({
          'WinnerText': 'Drew',
          'RS': rScore,
          'BS': bScore,
          'Score': ('${rScore.toInt()} - ${bScore.toInt()}'),
          'id':
              _fireStore.collection('matches').document().documentID.toString(),
          'date': DateFormat.yMMMd().format(DateTime.now()),
          'color' : Colors.green
        });
    }
  }

  void removeMatch(id) async {
    await _fireStore.collection('matches').document(id).delete();
  }
}



--------------------------------------------------

This is my Streamer Page -

import 'package:bvb_firebase/shareable/constants.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

class HistoryCardStreamer extends StatefulWidget {
  final int rikeshS;
  final int bibinS;

  HistoryCardStreamer({this.rikeshS, this.bibinS});

  @override
  _HistoryCardStreamerState createState() => _HistoryCardStreamerState();
}

class _HistoryCardStreamerState extends State<HistoryCardStreamer> {
  final _firestore = Firestore.instance;

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 300,
      child: StreamBuilder<QuerySnapshot>(
        stream: _firestore.collection('matches').snapshots(),
        builder: (context, snapshot) {
          if (!snapshot.hasData)
            return Center(
              child: CircularProgressIndicator(),
            );

          return Container(
            height: 300,
            child: ListView.builder(
              itemCount: snapshot.data.documents.reversed.length,
              itemBuilder: (context, index) {
                DocumentSnapshot matchDetail = snapshot.data.documents[index];

                return Card(
                  elevation: 0,
                  color: matchDetail['color'],
                  child: Container(
                    margin: EdgeInsets.only(top: 5),
                    child: ListTile(
                      title: Text(
                        matchDetail['WinnerText'],
                        style: kcardtitleTextStyle,
                      ),
                      leading: Container(
                        width: 45,
                        margin: EdgeInsets.only(top: 12, right: 5),
                        child: FittedBox(
                          child: Text(matchDetail['Score'],
                              style: kcardtitleTextStyle),
                        ),
                      ),
                      subtitle: Text(
                          '${DateFormat.yMMMd().format(DateTime.now())}',
                          style: kcardDateStyle),
                      trailing: GestureDetector(
                        onDoubleTap: () async {
                          await _firestore
                              .collection('matches')
                              .document(matchDetail.documentID)
                              .delete();
                        },
                        child: IconButton(
                          icon: Icon(Icons.delete),
                          onPressed: () {},
                        ),
                      ),
                    ),
                  ),
                );
              },
            ),
          );
        },
      ),
    );
  }
}

//
bibin101
  • 81
  • 2
  • 5
  • Check this answer https://stackoverflow.com/a/49835427/5882307 – OMi Shah Nov 12 '19 at 06:01
  • 1
    @OMiShah i did it but same problem. Firestore adds the color document as string so how can i save it as color? – bibin101 Nov 12 '19 at 06:03
  • Can I save the document in firestore as color directly ?? – bibin101 Nov 12 '19 at 06:05
  • I doubt about saving as a Color on firebase. Save it as a string and when you retrieve, change string to color. – OMi Shah Nov 12 '19 at 06:05
  • @OMiShah I followed the instructions from the link that you provided but it says type 'String' is not a subtype of type 'color' – bibin101 Nov 12 '19 at 06:37
  • can you show me the exact lines code how you have done? – OMi Shah Nov 12 '19 at 07:48
  • i used the same exact lines to convert it to string,,Color coloir = new Color(0xff196E3D); String colorStriing = coloir.toString(); // Color(0x12345678) String valueStriing = colorStriing.split('(0x')[1].split(')')[0]; // kind of hacky.. int valiue = int.parse(valueStriing, radix: 16); Color drawColor = new Color(valiue); – bibin101 Nov 12 '19 at 08:04
  • I shared the link of the last answer from the link, not the accepted answer :/ – OMi Shah Nov 12 '19 at 08:24
  • @OMiShah also my list items are appearing in random order. how to fix that? – bibin101 Nov 12 '19 at 09:44
  • any demo video or gif ? – OMi Shah Nov 12 '19 at 10:48

5 Answers5

8

There is a way to store the color value as a number in Firestore.

The class Color has a value method that returns an int of your color.

You can store this int in Firestore and when you get the color back into flutter you can use it within the Color(yourIntValue) class and also with the added withOpacity() method, to get the exact Opacity.

Example:

const customColor = MaterialColor(0xFFf4cce8, {});

customColor.value => is an int of f4cce8 which equals to 16043240

Color(16043240).withOpacity(1)  => 0xFFf4cce8

The .withOpacity is needed to give you back the 0xFF part otherwise you will get 0x00.

In this post you can see which value to use within the .withOpacity to get the needed opacity: Hex transparency in colors

Georgios
  • 861
  • 2
  • 12
  • 30
7

Based on the answer here you can save the color as a string in datastore converting it to a string in the proper format like this:

String colorString = color.toString();

Like this you can save the color on Firestore.

Then when retrieving it you shall convert it from String to Color, for this you can retrieve it like this:

color: new Color(matchDetail['colorString']),

To get the data sorted by date for example you can do it with the following line as explained here:

stream: _firestore.collection('matches').orderBy('date').snapshots()
Soni Sol
  • 2,367
  • 3
  • 12
  • 23
3

You can store the color as string , hex of color.

Color color = Colors.red;
String hexColor = color.hex;

You can retrieve the color as hex string as following.

Color? retrieveColor = getColorFromHex(hexColor);

Color? getColorFromHex(String hexColor) {
  hexColor = hexColor.replaceAll("#", "");
  if (hexColor.length == 6) {
    hexColor = "FF" + hexColor;
  }

  if (hexColor.length == 8) {
    return Color(int.parse("0x$hexColor"));
  }

  return null;
}
nexdev
  • 195
  • 11
2
var storedColorValue = Color.fromRGBO(82, 0, 44, 1.0).value;

you can store the value of the color like this (`your_storing_method( storedColorValue))

and when you want to read it again you can use this value to have the same color like this:

Color returnedColored = Color(storedColorValue);
0

You can store the value of the color as an int like this.

Int mycolor = Colors.blue.value;

Notice the .value added to the color. It is a 32bit value representing the color.

Thus, When passing it into a color argument. You then pass it like this:

color: Color(mycolor);
Pierre C.
  • 1,426
  • 1
  • 11
  • 20