首页 > 解决方案 > 带有 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>";
}

标签: androidiosfirebaseflutter

解决方案


推荐阅读