android - 带有 Cloud Firestore 投票应用的 Flutter 应用
问题描述
我正在开发一个应用程序,我想添加一个投票功能。我已按照本教程https://codelabs.developers.google.com/codelabs/flutter-firebase/#8
但是,这确实有效,因为它是一个投票应用程序,我不能让我的用户对同一个选项进行多次投票。我到处寻找解决方案,但一直找不到。我希望有人知道一种简单的方法来做到这一点。这是我的代码:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
class VotingPage extends StatefulWidget {
@override
_VotingPage createState() {
return _VotingPage();
}
}
class _VotingPage extends State<VotingPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Top 10 Företagen!')),
body: _buildBody(context),
);
}
Widget _buildBody(BuildContext context) {
return StreamBuilder<QuerySnapshot>(
stream: Firestore.instance.collection('poll').snapshots(),
builder: (context, snapshot) {
if (!snapshot.hasData) return LinearProgressIndicator();
return _buildList(context, snapshot.data.documents);
},
);
}
Widget _buildList(BuildContext context, List<DocumentSnapshot> snapshot) {
return ListView(
padding: const EdgeInsets.only(top: 20.0),
children: snapshot.map((data) => _buildListItem(context, data)).toList(),
);
}
Widget _buildListItem(BuildContext context, DocumentSnapshot data) {
final record = Record.fromSnapshot(data);
return Padding(
key: ValueKey(record.name),
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
child: Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(5.0),
),
child: ListTile(
title: Text(record.name),
trailing: Text(record.votes.toString()),
onTap: () => record.reference.updateData({'votes': FieldValue.increment(1)})
),
)
);
}
}
class Record {
final String name;
final int votes;
final DocumentReference reference;
Record.fromMap(Map<String, dynamic> map, {this.reference})
: assert(map['name'] != null),
assert(map['votes'] != null),
name = map['name'],
votes = map['votes'];
Record.fromSnapshot(DocumentSnapshot snapshot)
: this.fromMap(snapshot.data, reference: snapshot.reference);
@override
String toString() => "Record<$name:$votes>";
}
解决方案
推荐阅读
- javascript - 如何使用 JINJAVA 将 Java 字符串值或字符串列表传递给 javascript
- php - 来自 PHP CLI 的 gRPC 调用被卡住
- python - 如果值不存在则如何创建条件然后发生一些顺序动作,如果值不存在则发生其他动作
- google-sheets - 使用谷歌表格在图表中保持单元格引用不变?
- jquery - 使用 php 使用 ajax 上传 jquery 文件
- mysql - 两个表之间的查询慢
- javascript - 滚动 - 内容拉伸动画
- google-sheets - 编码索引匹配以搜索多个列
- reactjs - 不能在 React 功能组件中使用History()
- python-3.x - 如何将一个 cdk 类的输出动态绑定到另一个 cdk 类