Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store and retrieve Color from Firestore in Flutter

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: () {},
                        ),
                      ),
                    ),
                  ),
                );
              },
            ),
          );
        },
      ),
    );
  }
}

//
like image 230
bibin101 Avatar asked Nov 12 '19 05:11

bibin101


4 Answers

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

like image 42
Georgios Avatar answered Nov 19 '22 06:11

Georgios


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()
like image 116
Soni Sol Avatar answered Nov 19 '22 05:11

Soni Sol


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;
}
like image 3
nexdev Avatar answered Nov 19 '22 06:11

nexdev


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);
like image 2
mahmood-shamieh Avatar answered Nov 19 '22 06:11

mahmood-shamieh