Flutter: Building a voting app with flutter?

Samuel Ezedi
3 min readJun 27, 2020

--

Have you ever tried building a poll or at least a Twitter poll look alike? Well if you have, great! But if you haven’t or you have and just want to learn something new. I’d like to show you a flutter package that’s invariably a flutter widget which simply represents your voting data in a twitter poll look-alike widget.

Please note the capital of Egypt is Cairo for the purpose of correctness.

First, let's get the package from pub.dev/packages/polls

polls: ^0.1.8

Then we run:

flutter pub get

Few things to take note of, we’ll need a current user identifier, like an email or uid or something, this can be an index number from the database, but for the purpose of this article, I’ll use a hardcoded constant email. We’ll need a dataset of questions, options, users who voted, creator of the polls.

Dataset needed:

  1. Current user (String).
  2. Question (String).
  3. Options 1, 2, 3 and 4 are optional (double).
  4. Users who voted (Map).
  5. Creator of the poll (String).

In your main.dart import the package

import 'package:polls/polls.dart';

Lets take a look at this code snippet

options 1 to 4: are the results values of the poll’s question which should come dynamically from a database or API.

user: This holds the current user who is logged in.

usersWhoVoted: This is a Map datatype which holds the users who have voted and their choices. The user's email as the key and their choice option as the value. I will explain this again ahead.

creator: This is the creator of the polls, we’ll simply use this to identify what the view of the polls should be.

Let see how the poll works now

In the code below

question: This takes in a text widget of the question,

viewType: This determines the view type of the poll if it's

PollsType.readonly: meaning the user can only view the polls and cannot cast a vote, PollsType.creator: meaning this is the creator of the polls and PollsType.voter: meaning the widget is open to voting.

Looking critically on viewType: I did a check to determine how the view should be, so I checked if the current user is contained in usersWhoVoted, show read-only, else if the user is the same as the creator, show creator else if the show voter.

children: This takes in PollsOption, PollsOptions takes in title and values.

userChoice: This takes in the current user choice, so if this user already voted, this will tell the widget which option the user chose.

onVoteBackgroundColor, leadingBackgroundColor and backgroundColor: are colors given to the progress stroke bar.

onVote: this is a callback that returns the choice of the voter when he casts a vote, with this, you can save to your database or send to an API.

That’s it for this article! I hope you enjoyed it, and be sure to follow me for more Flutter articles and comment for any feedback you might have about this article.

--

--