Home Blog Page 83

How to create rating bar dialog in Flutter App – a smooth star rating flutter dialog

0
flutter smooth star rating dialog
flutter smooth star rating dialog

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we will discuss & implement 2 different flutter plugin/library, that is been used to ask use to 5 star rating review in our flutter application.

I have found best rating plugin in flutter

  1. smooth star rating flutter 
  2. rating_dialog – flutter app rating dialog

Video Tutorial

1. Flutter Smooth Star rating ( library 1)

smooth star rating flutter plugin library

This library is the best library as it comes with a star rating with touch and even it enables to swipe rating to star review. It’s named as smooth star rating flutter because this library will detect this gesture you make on the flutter star rating icon to give the rating.

This are the feature of this library:

Change the default star icons with your desired Icons.

Give user to rate using half rate or full ( Eg : 2.5 rating or  4.5 rating )

swiping on icon will increment/decrement the rating bar star.

and many more feature.

To learn more visit official site here

  • Supports replacing default star icons with desired IconData
  • Supports half rate and full rate (1.0 or 0.5)
  • Swipe for incrementing/decrementing rate amount
  • Change star body and boundary colors independently
  • Control size of the star rating
  • Set your desired total Star count
  • Supports click-to-rate
  • Spacing between stars

Installation smooth  star rating 

Add dependencies

open pubspec.yaml and all the following dependencies line.

dependencies:
  smooth_star_rating: ^1.0.4+2   // add this line

Then, just click on package_get this will download all the required classes in your flutter project.

Import the package class file

Then, after adding  the library, you need to import the smooth_star_rating.dart  wherever you need to show star review rating bar.

import 'package:smooth_star_rating/smooth_star_rating.dart';

Snippet code of showing star rating widget

SmoothStarRating(
               rating: rating,
               size: 35,
               filledIconData: Icons.star,
               halfFilledIconData: Icons.star_half,
               defaultIconData: Icons.star_border,
               starCount: 5,
               allowHalfRating: false,
               spacing: 2.0,
               onRatingChanged: (value) {
                 setState(() {
                   rating = value;
                 });
               },
             ),

Different parameters you can use here:

allowHalfRating                 -   Whether to use whole number for rating(1.0  or 0.5)
onRatingChanged(int rating)     -   Rating changed callback
starCount                       -   The maximum amount of stars
rating                          -   The current value of rating
size                            -   The size of a single star
color                           -   The body color of star
borderColor                     -   The border color of star
spacing                         -   Spacing between stars(default is 0.0)
filledIconData                  -   Full Rated Icon
halfFilledIconData              -   Half Rated Icon
defaultIconData                 -   Default Rated Icon


2. Flutter Rating Dialog ( Library 2 )

This flutter rating dialog is awesome as it provide beautiful and customizable Rating star icon dialog package for flutter application development.

rating dialog futter library

Installation of Flutter rating dialog plugin

Adding depencencies

Open pubspec.yaml file and all the below raiting dialog depencencies

dependencies:
  rating_dialog: ^1.0.0   // add this line

Then, just click on package_get this will download all the required classes in your flutter project.

Import the package class file

Then, after adding  the library, you need to import the rating_dialog.dart  whereever you need to show rating dialog box.

import 'package:rating_dialog/rating_dialog.dart';

Snippet Code to show AlertDialogin flutter with rating dialog

void show() {
    showDialog(
        context: context,
        barrierDismissible: true, // set to false if you want to force a rating
        builder: (context) {
          return RatingDialog(
            icon: const Icon(
              Icons.star,
              size: 100,
              color: Colors.blue,
            ), // set your own image/icon widget
            title: "Flutter Rating Dialog",
            description: "Tap a star to give your rating.",
            submitButton: "SUBMIT",
            alternativeButton: "Contact us instead?", // optional
            positiveComment: "We are so happy to hear 😍", // optional
            negativeComment: "We're sad to hear 😭", // optional
            accentColor: Colors.blue, // optional
            onSubmitPressed: (int rating) {
              print("onSubmitPressed: rating = $rating");
              // TODO: open the app's page on Google Play / Apple App Store
            },
            onAlternativePressed: () {
              print("onAlternativePressed: do something");
              // TODO: maybe you want the user to contact you instead of rating a bad review
            },
          );
        });
  }

The above snippet code has a method show() which have showDialog() widget that will return/display RatingDialog() which is a class of this library.

RatingDialog() widget have various parameters or we can say features.

icon : when you can display your flutter app logo

title: basically to title text

description :  text to ask user for there valuable star reviews.

submitButton : will show a simple button for submission of the review.

alternativeButton : you may use this button to navigate user to URL of your company website to know more.

positiveComment : if you select more the 3 star rating then you can show a positive message to user.

negativeComment: if you select 3 or less star rating then you can show different message to user.

onSubmitPressed(){} : what action to be performed when used click of submit review button

onAlternativePressed(){} : where the used should be navigated when user click on more info  button.

Complete Source Code with above 2 rating bar dialog example in flutter

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:smooth_star_rating/smooth_star_rating.dart';
import 'package:rating_dialog/rating_dialog.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  double rating = 4.0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text("App Rating stars")),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                "Library First :  'Smooth Star Rating' ",
                style: TextStyle(fontSize: 20),
              ),
              SizedBox(
                height: 10,
              ),
              SmoothStarRating(
                rating: rating,
                size: 35,
                filledIconData: Icons.star,
                halfFilledIconData: Icons.star_half,
                defaultIconData: Icons.star_border,
                starCount: 5,
                allowHalfRating: true,
                spacing: 2.0,
                onRatingChanged: (value) {
                  setState(() {
                    rating = value;
                    print(rating);
                  });
                },
              ),
              Text(
                "You have Selected : $rating Star",
                style: TextStyle(fontSize: 15),
              ),
              SizedBox(
                height: 15,
              ),
              Text(
                "Library Second:  'Rating_Dialog ' ",
                style: TextStyle(fontSize: 20, color: Colors.deepOrange),
              ),
              RaisedButton(
                onPressed: () {
                  show();
                },
                child: Text("Open Flutter Rating Dialog Box"),
              )
            ],
          ),
        ));
  }

  void show() {
    showDialog(
        context: context,
        barrierDismissible: true, // set to false if you want to force a rating
        builder: (context) {
          return RatingDialog(
            icon: const Icon(
              Icons.star,
              size: 100,
              color: Colors.blue,
            ), // set your own image/icon widget
            title: "Flutter Rating Dialog",
            description: "Tap a star to give your rating.",
            submitButton: "SUBMIT",
            alternativeButton: "Contact us instead?", // optional
            positiveComment: "We are so happy to hear 😍", // optional
            negativeComment: "We're sad to hear 😭", // optional
            accentColor: Colors.blue, // optional
            onSubmitPressed: (int rating) {
              print("onSubmitPressed: rating = $rating");
              // TODO: open the app's page on Google Play / Apple App Store
            },
            onAlternativePressed: () {
              print("onAlternativePressed: do something");
              // TODO: maybe you want the user to contact you instead of rating a bad review
            },
          );
        });
  }
}
flutter smooth rating dialog plugin

Recommended Articles

android alert dialog example

Alert dialog in flutter

bottom popup android – bottom sheet dialog fragment

How to make a Expandable Card in Flutter? ExpansionTile Widget Flutter

0
ExpansionTile Widget Flutter example

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we will learn how to make a Expandable Card in Flutter using ExpansionTile Widget.

What is Expansion Tile Widget in Flutter ?

Expansion is Similar to Expandable CardView in android,Using this Expansion Tile Widget one can Tap on the card to Expands or just collapses the view of the children inside it.

In other words, Expansion Tile is a simple ListTile with a traling icon or image that works some thing like expands or collapses the tile to open the hidden children widget in it.

Video Tutorial

 

Snippet Code of ExpansionTile widget Flutter

ExpansionTile(
            leading: Icon(FontAwesomeIcons.sign),
            title: Text("Expansion Title"),
            subtitle: Text("  Sub Title's"),
            children: <Widget>[
              Text(
                "In Children use can use any flutter Widget",
                style: TextStyle(fontSize: 20),
              ),
              SizedBox(
                height: 20,
              ),
              Center(
                child: Text(
                    "Children Widgets are expanded/ visible when Expansion Tile Widget is Clicked"),
              )
            ],
          ),

In above, snippet code of ExpansionTile i have included ExpansionTile properties such as title,subtitle,children, and a leading icon.

leading: Leading is the first properties of this widget, here you may include any widgets of your choice, In my case i have added an Icon

title: giving a title to the Expansion tile.

subtitle : giving a subtitle to Expansion tile.

children: <Widget>[] : define  widgets inside the Expansion Tile, this children widget will be visiable when user clicks on the expansion tile card.

When user click on the Tile, it expands(open) or collopses(closes).

Result of above snippet code.

after expanding expansiontile widget

Complete Source Code with Example of using Expansion Tile Widget

main.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutterexpandablelibrary/ExpandableCardViewFlutter.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Expandable Card View Widget"),
      ),
      body: SingleChildScrollView(
          child:
              MyExpanableCardViewFlutter()), //Wrapped into SingleChildScrollView because when click on TextField  keyboard will open and you may get error on screen "bottom overflowed by pixels flutter"
    );
  }
}

Create a new dart file in lib directory and name it as “MyExpanableCardViewFlutter”

MyExpandableCardviewFlutter.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

class MyExpanableCardViewFlutter extends StatefulWidget {
  @override
  _MyExpanableCardViewFlutterState createState() =>
      _MyExpanableCardViewFlutterState();
}

class _MyExpanableCardViewFlutterState
    extends State<MyExpanableCardViewFlutter> {
  //controller for TextField
  final username_controller = TextEditingController();
  final password_controller = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Container(
        child: Card(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Container(
              width: MediaQuery.of(context)
                  .size
                  .width, // container width depending on user device screen width
              height: 260.0,
              decoration: BoxDecoration(
                  image: DecorationImage(
                      fit: BoxFit.fill,
                      image: NetworkImage(
                          "https://images.unsplash.com/photo-1558981852-426c6c22a060?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80"))),
            ),
          ),
          ExpansionTile(
            title: Text("Harley-Davidson"),
            subtitle: Text("  Explore the world of H-D"),
            children: <Widget>[
              IconTheme(
                data: IconThemeData(
                  color: Colors.amber,
                  size: 32,
                ),
                child: StarDisplay(value: 3),
              ),
              Text("This image has 3 star rating ")
            ],
          ),
          ExpansionTile(
            title: Text("LOGIN FORM"),
            trailing: Icon(FontAwesomeIcons.signInAlt),
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.all(15.0),
                child: TextField(
                  controller: username_controller,
                  decoration: InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'username',
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(15.0),
                child: TextField(
                  controller: password_controller,
                  decoration: InputDecoration(
                    border: OutlineInputBorder(),
                    labelText: 'Password',
                  ),
                ),
              ),
              RaisedButton(
                textColor: Colors.white,
                color: Colors.blue,
                onPressed: () {
                  String username = username_controller.text;
                  String password = password_controller.text;

                  if (username != '' && password != '') {
                    print('Successfull');

                    print(" Value Entered in USERNAME " + username);
                    print("Password entered is : " + password);
                  }
                },
                child: Text("Log-In"),
              )
            ],
          ),
        ],
      ),
    ));
  }
}

class StarDisplay extends StatelessWidget {
  final int value;
  const StarDisplay({Key key, this.value = 0})
      : assert(value != null),
        super(key: key);
  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: List.generate(5, (index) {
        return Icon(
          index < value ? Icons.star : Icons.star_border,
        );
      }),
    );
  }
}

Note : I have made use of FontAwesomeIcon flutter library, So make sure you add it’s dependencies in pubspec.yaml file

dependencies:
  font_awesome_flutter: ^8.8.1   // this line

Result of above futter expension Tile Flutter Example

expension tile widget example

 

Flutter Push Notifications using flutter firebase messaging with example

0
Flutter Push Notifications using flutter firebase messaging with example
Flutter Push Notifications using flutter firebase messaging with example

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we will learn how to implement firebase flutter push notifications service in flutter app.

Using which you can send Firebase Cloud messages to your flutter app user using firebase console that is flutter push notifications.

DEMO OUTPUT

flutter firebase push notification example
flutter firebase push notification example

Let’s start

Flutter Firebase Push Notification

Step 1: Adding Firebase Messaging dependencies

Using this Flutter Plugin we can use the Firebase Cloud Messaging  Service (FCM).

With the use of this plugin, your Flutter application will be ready to process and receive the push notification from the firebase console server as well as data messaging on android and iOS devices.

link to firebase messaging plugin here

Open pubspec.yaml file and under dependencies: line add this –

dependencies:
  firebase_messaging: ^6.0.13  // add this line

Step 2: Create a new project on firebase console

Open Firebase Console

1. Add / Create Project :

Give a name to your firebase project as “Firebase-Push-Notification”, Just fill all the common required details for creating the firebase project.

2. Add firebase to your android application

Then, After successful creating firebase project, you will see an Add app with list of platform where you can integrate firebase eg : android, iOS, web, unity3D.

Select Android playform

3. Register app with android package name

Came back to IDE (Android Studio)  Navigate towords Androidmanifest.xml file to get android package name

Flutter Project > Android > app > src > main > AndroidManifest.xml

Under this manifest file you will find package name copy it and paste it into firebase console as below screenshot.

Add Firebase to you flutter android app

adding firebase to your android app

Hit Next.

Add google-services.json Config file to your flutter android app

Download the firebase google-services.json file and paste it in your flutter project in android section.

download firebase project config json file

project > Android > app > (paste) google-services.json

adding google-services json

Add Firebase SDK

Open build-gradle ( project level )

futter project > Android > build-gradle(project level)

add this classpath:-

buildscript {
    repositories {
        google() // add this if not there
        jcenter()
    }

    dependencies {
       
        classpath 'com.google.gms:google-services:4.3.3' //add here line 
    }
}

as shown in the below screenshot

add firebase SDK build.gradle project level

Note: check if google() repositories is added, if not then add it

Then, open build-gradle(app level)

project > Android > app  > build-gradle

Add the google services apply plugin

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'   // add the plugin on top or at the bottom og build-gradle (app-level)

apply plugin google services

Step 3:  Add FLUTTER_NOTIFICATION_CLICK <intent-filter>

Open AndroidManifest.xml file and add the intent-filter

project > Android > app > main > AndroidManifest.xml
<intent-filter>
                <action android:name="FLUTTER_NOTIFICATION_CLICK" />
                <category android:name="android.intent.category.DEFAULT" />
 </intent-filter>

add flutter notification click intent filter in <activity tag as show in screenshot below

flutter notification click intent filter

Step 4: Create a directory DataModel and create a  datamodel class file

(right click) on lib > New > Package

Name the package as DataModel  under the directory create a new dart file named “FirebaseMessage.dart”

Then add the below lined of code in it.

import 'package:flutter/cupertino.dart';

class FirebaseMessage {
  final String title;
  final String body;

  const FirebaseMessage({@required this.title, @required this.body});
}

This class will hold the value received firebase cloud messaging services.

Step 5: Copy below code in main.dart file

main.dart

import 'package:flutter/material.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutterpushnotification/DataModel/FirebaseMessage.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
  final List<FirebaseMessage> messageList = [];
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _firebaseMessaging.configure(
        onResume: (Map<String, dynamic> message) async {
      print("on Resume : $message");
    }, onLaunch: (Map<String, dynamic> message) async {
      print("on Launch  : $message");
      final notification = message['notification'];
      setState(() {
        messageList.add(FirebaseMessage(
            title: notification['title'], body: notification['body']));
      });
    }, onMessage: (Map<String, dynamic> message) async {
      print("on Message : $message");
      final notification = message['notification'];
      setState(() {
        messageList.add(FirebaseMessage(
            title: notification['title'], body: notification['body']));
      });
    });
    _firebaseMessaging.requestNotificationPermissions(
      const IosNotificationSettings(sound: true, badge: true, alert: true),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Firebase Push Notification"),
      ),
      body: ListView(
        children: messageList.map(createListTile).toList(),
      ),
    );
  }
}

Widget createListTile(FirebaseMessage message) => ListTile(
      title: Text(message.title),
      subtitle: Text(message.body),
    );

There you go, our flutter app all is ready to receive message from firebase cloud messaging server.

Step 6 : Sending Push notification from firebase Console to your flutter project

Goto firebase console  to send push notification to your flutter project application.

On the left navigation bar Grow > Cloud Messaging

Click on send your first message

 

sending push notification flutter target

Do you remember? we have added <intent-filter> in our flutter AndroidManifest.xml

their we have have initial intent filter action as FLUTTER_NOTIFICATION_CLICK 

custom-data

key= click_action and value = FLUTTER_NOTIFICATION_CLICK

sending push notification additional optional

Then Click on Publish Button, then Firebase will send the push notifications to your flutter application as show in the above mobile screenshot.

Flutter VelocityX Library–How to use velocity x Card on any Flutter Widgets

2
Flutter VelocityX Library–How to use VelocityX Card on any Flutter Widgets

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we gonna introduce you with a latest product called VELOCITY X” Library developed using Flutter SDK by Pawan Kumar.

Installation of this Velocity X library is defined here

Brief Introduction to the Library

What is Flutter Velocity X?

The Velocity X library in flutter development is a minimalist flutter framework that helps you in building custom Application design Rapidly.

Velocity X comes with various properties that we can apply to our flutter widget such as Color, Padding, Text , Box, Card, SizedBox and many more.

So in this Flutter tutorial, we will look into How to use VelocityX Card on any Flutter Widgets

How to use VelocityX Card on any Flutter Widgets

Note: when you are done with card properties then just use .make() to complete like of code as widget.

Velocity x Card

You can use card properties on any of the flutter widgets & wrap it to a card widget.

Eg:-

Text("Hello World")
                      .text
                      .center
                      .makeCentered()
                      .card
                      .white
                      .make()
                      .wh(150, 50),

This will result card widget on top of Text, as you can see in below picture.

Padding to the VelocityX card

Eg:-

Text("Giving Padding to Card").card.py16.make(),

This will set a Padding to the card with padding size of 16 px vertically.

velocityx card padding

Color to the velocityX card

Color to the velocityX card can be set using color methods.

Eg:-

Text("Color to the card").card.red600.make(), //red color card

then this code will fill the card with color properties as red.

Setting Color using Hex Code

you can even set the card color using Hex Color Code properties.

Text("Hex Code to set VelocityX Card Color")
                      .card
                      .hexColor('#FFF00d')
                      .make(),

this will set the flutter card color to Yellow.

velocityx card coloring using hex color code

Applying VelocityX Card to Image.network widget

Image.network(
                          "https://i.ytimg.com/vi/65hpqxG8k3E/maxresdefault.jpg")
                      .card
                      .py12
                      .roundedLg //this will set card border radius to 30
                      .make(),

Here, i have used Image.network Flutter widget, that will simply load a image from the url alloted and wrap the whole image widget into card widget with some Border Radius properties.

Result:

velocityx card border radius

Rounding(Border radius) Velocity X

This library offers you many predefined rounded radius properties for card widget.

Here are some predefined properties that you can use:

  • roundedNone – 0
  • roundedSM – 7.5
  • rounded – 15
  • roundedLg – 30

Eg:- Text(‘Velocityx’).card.roundedLg.make(); // sets the radius size as 15.

Converting String into TextWidget the Wrapping it to Card Widget using VelocityX

"Changing String to Text Widget with Velocity X text Properties and then change card color"
                      .text
                      .white
                      .center
                      .make()
                      .card
                      .blue700
                      .py12
                      .make(),
string to text in velocity ex

Using All Together

"All Together"
                      .text
                      .xl3
                      .blue700
                      .semiBold
                      .makeCentered()
                      .card
                      .roundedLg
                      .make()
                      .wh(180, 180),

Then, Here wh(width,height) defines width and height of the card widget.