如何在Flutter中将颜色存储和检索到Firestore?

7
我希望在Firestore中将颜色存储为“color”,并检索它以添加卡片的颜色;但是,当我添加新数据时,它没有被添加。也许我正在将颜色值存储为字符串,而Color不支持字符串。那么我该如何解决这个问题呢?下面是代码示例 -
这是我调用Firestore并添加文档的地方(有一个名为“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();
  }
}



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

这是我的流媒体页面 -
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: () {},
                        ),
                      ),
                    ),
                  ),
                );
              },
            ),
          );
        },
      ),
    );
  }
}

//

请查看此答案 https://dev59.com/clUL5IYBdhLWcg3wx6Zw#49835427 - OMi Shah
1
@OMiShah 我已经做了,但是问题依旧。Firestore 将颜色文档添加为字符串,那么我该如何将其保存为颜色? - bibin101
我可以直接将文档保存在Firestore中作为颜色吗? - bibin101
我对在Firebase上保存颜色存疑。将其保存为字符串,当您检索时,将字符串更改为颜色。 - OMi Shah
你能展示给我具体的代码行,说明你是如何完成的吗? - OMi Shah
显示剩余5条评论
5个回答

8

在Firestore中有一种将颜色值存储为数字的方法。

Color类有一个value方法,返回你所需的颜色值的整型数。

你可以将这个整型数存储在Firestore中,当你将颜色值取回Flutter时,你可以在Color(yourIntValue)类内使用它,并且还可以通过增加withOpacity()方法来获取确切的透明度。

示例:

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

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

Color(16043240).withOpacity(1)  => 0xFFf4cce8
.withOpacity是必需的,以便将0xFF部分返回,否则你将得到0x00
在这篇文章中,你可以看到在.withOpacity内使用哪个值来获得所需的透明度:颜色中的十六进制透明度

7

根据 这里 的回答,你可以将颜色转换成正确格式的字符串并保存到数据存储中,如下所示:

String colorString = color.toString();

像这样,您可以将颜色保存在Firestore中。

然后,在检索时,您应该将其从字符串转换为颜色。对于此操作,您可以按以下方式进行检索:

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

为了按日期排序数据,您可以使用以下行进行操作,如此处所解释的那样:
stream: _firestore.collection('matches').orderBy('date').snapshots()

3

你可以将颜色存储为字符串或十六进制颜色值。

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

您可以按照以下方法将颜色作为十六进制字符串检索。
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;
}

2
var storedColorValue = Color.fromRGBO(82, 0, 44, 1.0).value;

你可以像这样存储颜色的值:(`your_storing_method( storedColorValue)`)
当你想再次读取它时,您可以使用此值来获得相同的颜色,如下所示:
Color returnedColored = Color(storedColorValue);

0

你可以将颜色的值存储为整数,像这样。

Int mycolor = Colors.blue.value;

请注意颜色中添加的.value。它是表示颜色的32位值。
因此,当将其传递到颜色参数中时,您应该这样传递:
color: Color(mycolor);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接