Git Product home page Git Product logo

thenifemi / flutter_polls Goto Github PK

View Code? Open in Web Editor NEW
31.0 2.0 26.0 475 KB

πŸ—³ Customizable Polls for Flutter.

Home Page: https://pub.dev/packages/flutter_polls

License: MIT License

Dart 42.26% Kotlin 0.24% Swift 0.77% Objective-C 0.07% HTML 7.49% CMake 15.69% C++ 32.09% C 1.40%
flutter android ios flutter-polls flutter-apps mobile flutter-package polling polls votes voting dart lib flutter-widget library

flutter_polls's Introduction

Flutter Polls

Customizable Polls for Flutter. Simple, easy to use and highly customizable.

flutter_polls

Flutter Polls on pub.dev

Getting Started

In the pubspec.yaml of your flutter project, add the following dependency:

dependencies:
  ...
  flutter_polls: ^0.1.6

Import it:

import 'package:flutter_polls/flutter_polls.dart';

Example

Check out the example project in the example directory here: example on github

flutter_polls

FlutterPolls(
    pollId: '1',
    onVoted: (PollOption pollOption, int newTotalVotes) {
      print('Voted: ${pollOption.id}');
    },
    pollOptionsSplashColor: Colors.white(),
    votedProgressColor: Colors.greyDark().withOpacity(0.3),
    votedBackgroundColor: Colors.grey().withOpacity(0.2),
    votesTextStyle: themeData.textTheme.subtitle1,
    votedPercentageTextStyle:
        themeData.textTheme.headline4?.copyWith(
    color: Colors.black(),
    ),
    votedCheckmark: Icon(
        Icons.circle_check,
        color: AppColors.black(),
        height: 18,
        width: 18,
    ),
    pollTitle: Align(
    alignment: Alignment.centerLeft,
    child: AutoSizeText(
        poll['title'],
        style: TextStyle(
            fontSize: 20,
        ),
    ),
    pollOptions: poll['options'].map(
    (option) {
        return PollOption(
        id: option['id'],
        title: AutoSizeText(
            option['title'],
            style: tTextStyle(
            fontSize: 20,
        ),
        ),
        votes: option['votes'],
        );
    },
    ).toList(),
    metaWidget: Row(
    children: [
        const SizedBox(width: 6),
        AutoSizeText(
        'β€’',
        style: TextStyle(
            fontSize: 20,
        ),
        ),
        const SizedBox(
        width: 6,
        ),
        AutoSizeText(
        '2 weeks left',
        style: TextStyle(
            fontSize: 20,
        ),
        ),
    ],
    ),
),

Parameters

Parameter Type Description
pollId String The poll id.
hasVoted bool Whether the user has voted.
userVotedOptionId String The user voted option id. If the user hasn't voted, this will be null.
onVoted void Function(PollOption pollOption, int newTotalVotes) The callback when the user voted.
pollTitle Widget The poll title. Can be any widget.
pollOptions List The poll options. Each item is a map with the following keys: id, title, votes.
heightBetweenTitleAndOptions double The height between the poll title and the poll options.
heightBetweenOptions double The height between the poll options.
votesText String Votes text. Can be "Votes", "Votos", "Ibo" or whatever language. If not specified, "Votes" is used.
votesTextStyle TextStyle The style of the votes text.
metaWidget Widget The meta widget. Can be any widget.
createdBy String The poll creator.
userToVote String The user to vote.
pollStartDate DateTime The poll start date.
pollEnded bool If the poll is closed.
pollOptionsHeight double The poll options height.
pollOptionsWidth double The poll options width.
pollOptionsBorderRadius BorderRadius The poll options border radius.
pollOptionsBorder BoxBorder The poll options border.
pollOptionsFillColor Color The poll options fill color.
pollOptionsSplashColor Color The poll options splash color.
votedPollOptionsRadius Radius The voted poll options border radius.
votedBackgroundColor Color The voted poll options background color.
votedProgressColor Color The voted poll options progress color.
voteInProgressColor Color The voted poll options background color when user has voted and its still in progress.
votedCheckmark Widget The voted poll options checkmark.
votedPercentageTextStyle TextStyle The voted poll options percentage text style.
votedAnimationDuration int The voted poll options animation duration.
loadingWidget Widget The loading widget when a user votes. Can be any widget.

flutter_polls's People

Contributors

bislerium avatar danielsgiks avatar f-mehues avatar myconsciousness avatar samuelrbrt avatar shaunramsey avatar thenifemi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

flutter_polls's Issues

RRect argument contained a NaN value

Create Problem:

  1. Pass List of PollOption via pollOptions prameter with corresponding field votes set to 0
  2. set pollEnded parameter to true

Solution: resolve 0/0 = 0, not NaN

line 252. percent: pollOption.votes / totalVotes.value

hasVoted showing `Bad state: No element` when value set to true

hasVoted showing Bad state: No element when value set to true

======== Exception caught by widgets library ======================================================= The following StateError was thrown building FlutterPolls(dirty, useState<bool>: false, useState<bool>: false, useState<bool>: false): Bad state: No element

Revoting Feature

Hey, would you mind adding a revoting feature (or at least an "undo vote" option)?

Thanks in advance.

dependencies

Would be really nice if you could update the pkg deps.
E.g. flutter hooks is now at version 0.20.3.
Many thanks for the work anyway. Very nice.

Make the PollOption id type to String.

    PollOption(
        id: choice.key, <--- Int
        title: AutoSizeText(
          choice.title,
          style: primary14TextStyle,
        ),
        votes: choice.votes,
    );

Currently the PollOption id is an integer, now a days it's very common to use UUID string instead of int to index items in the server side for various reasons. So at the Flutter app side, we usually end up using the same option id returned by the API to uniquely identify the Poll options.

Would it be possible to change the id type to String to accomodate more such use cases?

RRect argument contained a NaN value

Create Problem:

  1. Pass List of PollOption via pollOptions prameter with corresponding field votes set to 0
  2. set pollEnded parameter to true

Solution: resolve 0/0 = 0, not NaN

line 252. percent: pollOption.votes / totalVotes.value

Backend integration support ?

Do you have any plan to support generic integration to make real time polling with firebase or any other backend ?
Any sample with Backend support ?

setState

if we use SetState to update variables , the voting does not work! please fix, or tell us what is the workaround please.

version 0.0.7 broke everything!!

Hi,

I have flutter on upgrade dependencies whenever I flutter pub get from a build script I work with in development mode. I had been using the stable version of flutter_polls 0.0.4 which was mostly bug-free.

For some reason, flutter pub upgraded this dependency today as I was working in parallel on my project. Version 0.0.7 is a proper addition because now finally we can see there's a pollEnded functionality but it traded that functionality with a pestering bug that just killed my mood today.

I'll appreciate it if you got any ideas on how to fix the bug?

The bug!

On first load without the current user taking a vote or interacting with the poll there's no error everything is normal but as the user interacts with the poll this damn error: "type '(dynamic, dynamic) => dynamic' is not a subtype of type '(PollOption, PollOption) => PollOption' of 'combine' ", keeps getting thrown and crashes everything.
Screenshot 2022-06-10 225019
Screenshot 2022-06-10 224939

Image on device
SmartSelect_20220610-224740

SmartSelect_20220610-224703

Add voted poll options border field

As of now, the package only allows to add custom borders to poll options before the user votes. It'd be great to add the same functionality for the voted state

Working in Debug Mode, But not working in Prod (after hosting on netlify).

import 'package:flutter/material.dart';
import 'package:flutter_polls/flutter_polls.dart';

class PollSection extends StatelessWidget {
const PollSection({super.key});

@OverRide
Widget build(BuildContext context) {
return DecoratedBox(
decoration: const BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(12.0)),
color: Colors.black,
),
// height: 300,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: EdgeInsets.fromLTRB(MediaQuery.of(context).size.width * 0.024, 32, MediaQuery.of(context).size.width * 0.024, 16),
child: Row(
children: [
Text(
"Guild's Poll",
),
],
),
),
const Padding(
padding: EdgeInsets.fromLTRB(16, 0, 16, 16),
child: CommunityPollBox(),
),
const SizedBox(height: 8,),
Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
child: Expanded(
child: ElevatedButton(
child: Text(
'CREATE NEW POLL +',
),
onPressed: () {},
),
),
),
],
),
);
}
}

class CommunityPollBox extends StatelessWidget {
const CommunityPollBox({super.key});

@OverRide
Widget build(BuildContext context) {

return FlutterPolls(
pollId: '1',
onVoted: (PollOption pollOption, int newTotalVotes) async {
            await Future.delayed(const Duration(seconds: 1));
            /// If HTTP status is success, return true else false
            return true;
          },
pollOptionsSplashColor: Colors.green,
votedProgressColor: Colors.green,
pollOptionsFillColor: Colors.white,
votedBackgroundColor: Colors.grey,
votesTextStyle: TextStyle(color: $COLOR.GREEN, fontSize: 12),
votedCheckmark: const Icon(
  Icons.check_circle,
  color: Colors.black,
),
pollTitle: Align(
alignment: Alignment.centerLeft,
child: AutoSizeText(
'Who would win?',
style: TextStyle(color: $COLOR.WHITE, fontSize: 12),
),

),
pollOptions: [
PollOption(title: const Text('Zues'), votes: 60),
PollOption(title: const Text('Poseidon'), votes: 40),
],
metaWidget: Row(
children: const [
SizedBox(width: 6),
Text(
' | ',
style: TextStyle(
fontSize: 12,
color: Colors.green,
),
),
SizedBox(
width: 6,
),
Text(
'2 weeks left',
style: TextStyle(
fontSize: 12,
color: Colors.white,
),
),
],
),
);
}
}`

plz just ingore my removal of custom text styles. it is working properly on debug mode but not in prod.

TypeError

I just used the example code and ran into error.

Flutter doctor:

Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 3.0.5, on Microsoft Windows [Version 10.0.22000.795], locale en-US)
[√] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
[√] Chrome - develop for the web
[X] Visual Studio - develop for Windows
    X Visual Studio not installed; this is necessary for Windows development.
      Download at https://visualstudio.microsoft.com/downloads/.
      Please install the "Desktop development with C++" workload, including all of its default components
[√] Android Studio (version 2021.2)
[√] VS Code (version 1.69.1)
[√] Connected device (4 available)
[√] HTTP Host Availability
The following _TypeError was thrown building FlutterPolls(dirty, useState<bool>: false, useState<bool>: true, useState<PollOption?>: Instance of 'PollOption', useState<int>: 572):
type '(dynamic, dynamic) => dynamic' is not a subtype of type '(PollOption, PollOption) => PollOption' of 'combine'

The relevant error-causing widget was
FlutterPolls
lib\…\post_dependent_widgets\poll_card.dart:86
When the exception was thrown, this was the stack
#0      ListMixin.reduce (dart:collection/list.dart)
#1      FlutterPolls.build.<anonymous closure> (package:flutter_polls/flutter_polls.dart:243:42)
#2      MappedListIterable.elementAt (dart:_internal/iterable.dart:413:31)
#3      ListIterator.moveNext (dart:_internal/iterable.dart:342:26)
#4      List.addAll (dart:core-patch/growable_array.dart:319:13)
#5      FlutterPolls.build (package:flutter_polls/flutter_polls.dart:218:26)
#6      StatelessElement.build
package:flutter/…/widgets/framework.dart:4876
#7      HookElement.build (package:flutter_hooks/src/framework.dart:416:27)
#8      ComponentElement.performRebuild
package:flutter/…/widgets/framework.dart:4806
#9      Element.rebuild
package:flutter/…/widgets/framework.dart:4529
#10     BuildOwner.buildScope
package:flutter/…/widgets/framework.dart:2659
#11     WidgetsBinding.drawFrame
package:flutter/…/widgets/binding.dart:891
#12     RendererBinding._handlePersistentFrameCallback
package:flutter/…/rendering/binding.dart:370
#13     SchedulerBinding._invokeFrameCallback
package:flutter/…/scheduler/binding.dart:1146
#14     SchedulerBinding.handleDrawFrame
package:flutter/…/scheduler/binding.dart:1083
#15     SchedulerBinding._handleDrawFrame
package:flutter/…/scheduler/binding.dart:997
#19     _invoke (dart:ui/hooks.dart:151:10)
#20     PlatformDispatcher._drawFrame (dart:ui/platform_dispatcher.dart:308:5)
#21     _drawFrame (dart:ui/hooks.dart:115:31)
(elided 3 frames from dart:async)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.