如何在Flutter中从Firestore存储和检索颜色

时间:2019-11-12 05:53:11

标签: firebase flutter google-cloud-firestore

我想在Firestore中将颜色存储为“颜色” 并检索它以添加我卡的颜色;

但是当我添加新数据时,它不会被添加。 也许我将颜色值存储为字符串,而颜色不支持字符串。 那我该如何解决这个问题呢?

下面给出了代码-


这是我调用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: () {},
                        ),
                      ),
                    ),
                  ),
                );
              },
            ),
          );
        },
      ),
    );
  }
}

//

2 个答案:

答案 0 :(得分:0)

根据答案here,您可以将颜色另存为数据存储区中的字符串,将其转换为正确的格式,如下所示:

String colorString = color.toString();

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

然后在检索它时,应将其从String转换为Color,为此,您可以像这样检索它:

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

例如,要获取按日期排序的数据,可以按照here中的说明使用以下行来完成:

stream: _firestore.collection('matches').orderBy('date').snapshots()

答案 1 :(得分:0)

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

Color 具有一个value方法,该方法返回您的颜色的int值。

您可以将此int存储在Firestore中,当颜色变回抖动时,可以在Color(yourIntValue)类中使用它,还可以通过添加的withOpacity()方法来使用它,以获取确切的不透明度。 / p>

示例:

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

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

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

需要.withOpacity才能退还0xFF部分,否则您将获得0x00

在这篇文章中,您可以看到在.withOpacity中使用哪个值来获得所需的不透明度:Hex transparency in colors