Home Blog Page 87

Flutter Sensors Plugin – Accelerometer and Gyroscope sensor library

0
Flutter Sensors Plugin - Accelerometer and Gyroscope sensor library
Flutter Sensors Plugin - Accelerometer and Gyroscope sensor library

Hi Guys, Welcome to Proto Coders Point , In this Flutter Tutorial we will learn and Implement Flutter Sensor Library.

Introduction to Flutter Sensors Library

A Flutter plugin to access the accelerometer and gyroscope sensors.

Accelerometer sensor mobile x y z asis

AccelerometerEvent  : used to describe the velocity of the device, which also include the effect of gravity in the mobile device, Flutter Accelerometer simply uses accelerometer reading and tell weather the device is currently moving and if moving then in which direction it’s moving. Detail about Accelerometer wiki

UserAccelerometer Event sensor : in function reads the velocity of the device but does not read the gravity.

Gyroscope Event the Reads the Rotations of the device. Gyroscope sensor a device that is used to know the orientation ( portrait or landscape) and also the device angular velocity. Detail about Gyroscope Wiki

Now, As we know basic about those sensor in our mobile device, let’s begin implementation of Flutter Sensor Library.

Flutter Sensors Plugin – Accelerometer and Gyroscope sensors with example

Final Result of the Flutter Sensor Example

Flutter Sensor Accelerameter Gyroscope

Step 1 :  Create a new Flutter Project or open any Existing flutter project

my project Structure

Flutter Sensor Project structure
Flutter Sensor Project structure

Step 2 : Add the Sensors library in pubspec.yaml file

Get the latest version of Flutter Sensor library from official site here

dependencies:
  sensors: ^0.4.1+7   #//add this flutter sensor plugin

when you add the above sensor dependencies, the sensor packages will get added into your flutter project.

Step 3 : Importing the sensor.dart class

Then, as you have added the sensor dependencies library in your project now you can easily use the feature of sensors class just by importing sensors.dart file wherever required in your project.

import 'package:sensors/sensors.dart';

Step 4 : snippet code example

accelerometerEvents.listen((AccelerometerEvent event) {
  print(event);
});
// [AccelerometerEvent (x: 0.0, y: 9.8, z: 0.0)]

userAccelerometerEvents.listen((UserAccelerometerEvent event) {
  print(event);
});
// [UserAccelerometerEvent (x: 0.0, y: 0.0, z: 0.0)]

gyroscopeEvents.listen((GyroscopeEvent event) {
  print(event);
});
// [GyroscopeEvent (x: 0.0, y: 0.0, z: 0.0)]

Step 5 : Example using Accelerometer Sensor

In this Flutter Tutorial sensor Example i am using Accelerometer sensor to get motion data from the Sensor Device

Here is the Snippet code i have used to get the value of X asis, Y Asis , and Z Asis.

@override
  void initState() {
    // TODO: implement initState
    super.initState();
    accelerometerEvents.listen((AccelerometerEvent event) {
      setState(() {
        x = event.x;
        y = event.y;
        z = event.z;
      });
    });
  }

Here i have override initState() method so that sensor start sending data as soon as Flutter Application starts.

As in the above lines of code accelerometerEvent returns data in a form of double. I have initialized 3 double datatype variable that holds value of X,Y,Z Asis.

Then i am using those variable to display the value in Text widget.

Text(x.toStringAsFixed(2), style: TextStyle(fontSize: 20.0)),

Here, Text widget will print only 2 digits after the decimal point.

For Example : 2.59235471 will get trimmed into 2.59

Flutter Senser data UI design

Complete Code of Flutter Accelerometer and Gyroscope sensor library

Just Copy paste the below lines of Flutter Dart code in main.dart file

main.dart

import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:sensors/sensors.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 x, y, z;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    accelerometerEvents.listen((AccelerometerEvent event) {
      setState(() {
        x = event.x;
        y = event.y;
        z = event.z;
      });
    }); //get the sensor data and set then to the data types
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Flutter Sensor Library"),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Padding(
                padding: const EdgeInsets.all(10.0),
                child: Text(
                  "An Example How on Flutter Sensor library is used",
                  style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.w900),
                ),
              ),
              Table(
                border: TableBorder.all(
                    width: 2.0,
                    color: Colors.blueAccent,
                    style: BorderStyle.solid),
                children: [
                  TableRow(
                    children: [
                      Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Text(
                          "X Asis : ",
                          style: TextStyle(fontSize: 20.0),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Text(x.toStringAsFixed(2), //trim the asis value to 2 digit after decimal point
                            style: TextStyle(fontSize: 20.0)),
                      )
                    ],
                  ),
                  TableRow(
                    children: [
                      Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Text(
                          "Y Asis : ",
                          style: TextStyle(fontSize: 20.0),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Text(y.toStringAsFixed(2),  //trim the asis value to 2 digit after decimal point
                            style: TextStyle(fontSize: 20.0)),
                      )
                    ],
                  ),
                  TableRow(
                    children: [
                      Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Text(
                          "Z Asis : ",
                          style: TextStyle(fontSize: 20.0),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.all(8.0), 
                        child: Text(z.toStringAsFixed(2),   //trim the asis value to 2 digit after decimal point
                            style: TextStyle(fontSize: 20.0)),  
                      )
                    ],
                  ),
                ],
              ),
            ],
          ),
        ));
  }
}

And Here you go your Flutter app is ready to get data from device accelerometer and gyroscope sensor.

 

Flutter Dart Server Framework – Angel Server in Flutter with Example

2
Angel dart server in flutter application example
Angel dart server in flutter application example

Hi Guys, Welcome to Proto Coders Point , In this Flutter Tutorial we will implement a Dart Server Framework using Angel Server.

What is Angel Server in Dart ?

An Angel server is an Backend framework in dart language that we can user for geting or putting data from/to server. A polished, production-ready backend framework in dart.

The angel framework comes with various features such as Hot Reloading , GraphQL and ORM, Angel is one of the perfectly built backend dart to give power to build super production apps.

This server also provides supports for server-side templating, webSockets,authentication and much more.

let’s start implementing Angel dart server in our flutter project.

Flutter Dart Server Framework – Angel Server in Flutter with Example

Open the Existing Flutter project or just create a new Flutter project

Step 1 : Adding Required dependencies

Open pubspec.yaml file and add this 3 dependencies under dependencies section

angel_framework: ^2.1.1

angel_hot: ^2.0.6

dio: ^3.0.8

Brief intro to above dependencies

angel_framework : A high-powered HTTP server with support for dependency injection, sophisticated routing and more.

angel hot : Supports hot reloading of Angel servers on file changes. This is faster and more reliable than merely reactively restarting a Process.

dio : A powerful Http client for Dart, which supports Interceptors, Global configuration, FormData, Request Cancellation, File downloading, Timeout etc.

angel framework dart server dependencies pubspec.yaml

Then, just click on Packages get to import all the required packages into our project.

Step 2 : Create a folder and then create a server.dart file

once you add the required dependencies, now it time to create a server.dart file where all the server side coding will be done

Right Click on project > New  > Directory ( name it )

i have created a directory with name angel_backend,

Then, in angel_backend directory create a dart file name ” server.dart “

Snippet Code from Server.dart

import 'package:angel_framework/angel_framework.dart';
import 'package:angel_hot/angel_hot.dart';

import the angel framework and angel hot package to get access to use those classes in server.dart.

Future<Angel> createServer() async {
  var app = Angel();

  app.get("/", (req, res) {
    res.write("Hi Guys, Welcome to Proto Coders Point");
  });

  return app;
}

In the above code createServer is a function which handles certain task in angel server.

app.get(“/”,(req,res) { } : is a Index route that return data in a JSON format, and Here req is request , res is response.

res.write : with send the data to the caller.

main() async {
  var hot = HotReloader(createServer, [
    "/home/rajat/AndroidStudioProjects/flutter_angel_backend/angel_backend"
  ]);

  await hot.startServer("172.20.10.5", 8383);
}

Hot Reloader class comes from Angel_hot library, it accept 2 parameters a function, and a path which need to be reloaded when changed using Flutter HotReload.

Here replace the IP address  with your wifi ip address that you are connected with, In my case its “172.20.10.5” 

Complete Code of Server.dart

server.dart

just copy paste the below lines of code in server.dart file

import 'package:angel_framework/angel_framework.dart';
import 'package:angel_hot/angel_hot.dart';

main() async {
  var hot = HotReloader(createServer, [
    "/home/rajat/AndroidStudioProjects/flutter_angel_backend/angel_backend"
  ]);

  await hot.startServer("172.20.10.5", 8383); // Replace IP Address with yours
}

Future<Angel> createServer() async {
  var app = Angel();

  app.get("/", (req, res) {
    res.write("Hi Guys, Welcome to Proto Coders Point");
  });

  return app;
}

Step 4 : How to start angel server ?

Here is how can we start the angel server

#moving to directory where server code is
/AndroidStudioProjects/flutter_angel_backend$ cd angel_backend  

#start the server
~/AndroidStudioProjects/flutter_angel_backend/angel_backend$ dart --observe server.dart


Result on Successful start the server

Observatory listening on http://127.0.0.1:8181/bE8mdqBRUY8=/

🔥  To hot reload changes while running, press "r". To hot restart (and rebuild state), press "R".
Your Angel server is listening at: http://172.20.10.5:8383

Once you have done coding in server side using Flutter angel server now it’s time to UI design

Step 3 : Designing Flutter UI to show Data from Angel Server

How to request angel server for data ?

Here using initState() method i have called my function to get data from server.

I have made use of Dio library to make http call to get data from server

Here the respense data will be stored in String vairable result that we can used to show data in Text Field in out flutter application.

fetchAngelData() async {
    Response response = await Dio().get("http://172.20.10.5:8383");

    setState(() {
      result = response.data;
    });
  }

 

Open main.dart file  and Copy paste below dart code

main.dart

import 'package:dio/dio.dart';
import 'package:flutter/material.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> {
  String result;

  String text;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    fetchAngelData();
    text = "Above Text is from Angel Server !!!!!!";
  }

  fetchAngelData() async {
    Response response = await Dio().get("http://172.20.10.5:8383"); // replace IP address with yours

    setState(() {
      result = response.data;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Flutter Angel server Example"),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Center(
            child: Text(
              result?.toString() ?? "No Data",
              style: TextStyle(
                  fontStyle: FontStyle.italic,
                  fontWeight: FontWeight.w900,
                  fontSize: 20.0),
            ),
          ),
          Center(
            child: Text(text),
          )
        ],
      ),
    );
  }
}

Their you go now your flutter project is ready to get data from Angel Dart Server Framework.

NOTE : JUST KEEP IN MIND YOU NEED TO REPLACE THE IP ADDRESS WITH YOU IP ADDRESS YOU ARE CONNECTED WITH.

Final Result of this project example

flutter dart angel server example
flutter dart angel server example

 

How to generate qr code in python using pyqrcode library?

0
How to generate QR Code using PYQRCODE

Hey Guys, welcome to Proto Coders Point , in this Python Tutorial we will implement qr code generator using pyqrcode library.

 What is pyqrcode library/module?

The pyqrcode library is a qr code generator, By using this module we can easily develop QR code with pure python.

This Library can be used for building or creating QR codes, Then you can save the QR coder with is generated as SVG,PNG and plain text.

Let’s begin implementation of the library

Step 1 : Create New Python project or  open existing project

Off-Course you need to create a new Python Project to work on this QR code generator tutorial

File > New Project

Step 2 : Create a new Python file to handle QR code generator

You need to create a new python file where you can write python code

Right click on Project > New > Python File

i have created a new python file with name as ” QRCodeGenerator”

Creating new python file

Step 3 : Add pyqrcode library in your python project

How to install the pyqrcode module ?

installing pyqrcode in python

File > Setting > Project Interpretor > Click on ” + ” >  Search for “pyqrcode” then select the package and then click on install package button.

Step 4 : open the python file “QRCodeGenerator”

# Import QRCode from pyqrcode
import pyqrcode
from pyqrcode import QRCode

# String which represent the QR code result
s = "www.protocoderspoint.com"

# Generate QR code
url = pyqrcode.create(s)

# Create and save the png file naming "myqr.png"
url.svg("myqr.svg", scale=8)


As you have added or installed the pyqrcode module in your project now you can just import the pyqrcode library and use them in your code.

we have initialized a string “s” that holds a website address.

then pyqrcode.create(s) :  Here are we passing the string that holds url of website to create a QR Code in PYTHON

and then this url variable is passed to create a new Image of that QR Code with is been generated.

Final Result

Now just Run the project and you will see a QR Code as below image

you can just scan the QR Code and check the result will open the browser with protocoderspoint.com

Result of QR Code in python

Flutter Bot Toast Library – Show Toast message , Toast Notification etc

0
Flutter Toast Message bot library
Flutter Toast Message bot library

Hi Guys, welcome to Proto Coders Point , In this Flutter Tutorial we will discuss and Implement  Flutter Toast Message using Bot Toast Library.

Learn more about this library from Official Site

What is Toast Message?

Some TImes Toast Messages are also called as Toast Notification.

It’s a small message that pop up at the bottom of the device screen and immediately disappears on it’s own after a delay of few seconds,

This are mostly used to show a feedback on the operation that is preformed by the user.

I have Already wrote a post on another flutter toast message library which is very simple and old style to show Toast message example.

So, Let’s Begin Implementing Flutter Bot Toast Message into your Flutter project.

Flutter Bot Toast Library – message, Notification, Attached Widget pop up

Step 1 : offCourse you need new or existing flutter project

I am using Android-studio to work with Flutter Development, Check out  How to add Flutter Plugin in android Studio

Create a new Flutter project

File > New > New Flutter Project

Step 2 : Add bot toast dependencies in pubspec.yaml file

Then, once you Flutter project is been created open pubspec.yaml file and you need to add Bot_Toast dependencies 

dependencies:
  bot_toast: ^2.2.1  //add this line

// version may update check official site for more

then click on Package Get

Step 3 : Import bot toast package

then, when you have successfully added the library into your flutter project, now you will be able to use this bot toast message package where-ever required, just you need to import the bot_toast.dart file.

import 'package:bot_toast/bot_toast.dart';

add this import statement on top of main.dart in your project.

Step 4 : Initialization of Bot Toast

Widget build(BuildContext context) {
    return BotToastInit( // wrap MaterialApp with BotToastInit
      child: MaterialApp(
        title: 'Flutter Demo',
        debugShowCheckedModeBanner: false,
        navigatorObservers: [BotToastNavigatorObserver()], //Register route observer
        navigatorKey: navigatorkey,
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: MyHomePage(),
      ),
    );

Then, to make user of the library you need to :

  • Step 1 : Wrap MaterialApp with BotToastInit
  • Step 2 : Register route Observer

As shown in above Snippet Code.

Step 5 : Different  ways to show Toast message or Toast Notification

1. Simple Text Message

Simple Toast message flutter

RaisedButton(
              child: Text("Simple Text Toast"),
              onPressed: () {
                BotToast.showText(text: "Simple Toast Message Example");
              },
            ),
2. Show a Toast Notification on top of the Screen

Toast Notification Flutter

RaisedButton(
              child: Text("Show Notification Toast"),
              onPressed: () {
                BotToast.showSimpleNotification(
                  title: "Simple Notification Toast Message",
                  subTitle: "This is Sub Title",
                  hideCloseButton: true,
                );
              },
            ),

This Snippet Code will show a Notification when user click on the button,

There are various property that can we used eg :

title : show text on the notification

subTitle : shows description

hideCloseButton : their is a close button on the Toast Notification using which user can close immedietly by clicking on close button, we can hide that button by setting it to true.

3. Show Loading Toast 

loading Bot Toast

RaisedButton(
             child: Text("Show Loading Toast"),
             onPressed: () {
               BotToast.showLoading(
                 clickClose: true,
               ); //when loading toast is clicked it closes
             },
           ),
4. Show Attached Widget

you can use Attached Widget to show any kind of Widget in the Toast Form.

show Attached widget bot toast

RaisedButton(
              child: Text("pop-up an attachment"),
              onPressed: () {
                BotToast.showAttachedWidget(
                    allowClick: true,
                    attachedBuilder: (_) => Center(
                          child: Card(
                            child: Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: Row(
                                
                                crossAxisAlignment: CrossAxisAlignment.center,
                                mainAxisSize: MainAxisSize.min,
                                children: <Widget>[
                                  Icon(
                                    Icons.favorite,
                                    color: Colors.red,
                                  ),
                                  Text("Hit the Like"),
                                ],
                              ),
                            ),
                          ),
                        ),
                    target: Offset(520, 520),
                    duration: Duration(
                        seconds: 3)); //when loading toast is clicked it closes
              },
            ),

In the Above Snippet code i have attached Card with child as Row where Row contain 2 children Icon and Text.

And also we need to set the duration to show the Attached Toast widgets.

Complete Code of this Flutter Tutorial on Bot Toast Message

When you know the basic of this Flutter Bot Toast message libray just Copy paste the below lines of code in main.dart file

main.dart

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

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.

  GlobalKey<NavigatorState> navigatorkey = GlobalKey<NavigatorState>();
  @override
  Widget build(BuildContext context) {
    return BotToastInit(
      child: MaterialApp(
        title: 'Flutter Demo',
        debugShowCheckedModeBanner: false,
        navigatorObservers: [BotToastNavigatorObserver()],
        navigatorKey: navigatorkey,
        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("Flutter Bot Toast"),
      ),
      body: Center(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              "Flutter Bot Toast Message Example",
              style: TextStyle(
                  fontSize: 20.0,
                  fontWeight: FontWeight.w800,
                  fontStyle: FontStyle.italic),
            ),
            SizedBox(
              height: 25,
            ),
            RaisedButton(
              child: Text("Simple Text Toast"),
              onPressed: () {
                BotToast.showText(text: "Simple Toast Message Example");
              },
            ),
            RaisedButton(
              child: Text("Show Notification Toast"),
              onPressed: () {
                BotToast.showSimpleNotification(
                  title: "Simple Notification Toast Message",
                  subTitle: "This is Sub Title",
                  hideCloseButton: true,
                );
              },
            ),
            RaisedButton(
              child: Text("Show Loading Toast"),
              onPressed: () {
                BotToast.showLoading(
                  clickClose: true,
                ); //when loading toast is clicked it closes
              },
            ),
            RaisedButton(
              child: Text("pop-up an attachment"),
              onPressed: () {
                BotToast.showAttachedWidget(
                    allowClick: true,
                    attachedBuilder: (_) => Center(
                          child: Card(
                            child: Padding(
                              padding: const EdgeInsets.all(8.0),
                              child: Row(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                mainAxisSize: MainAxisSize.min,
                                children: <Widget>[
                                  Icon(
                                    Icons.favorite,
                                    color: Colors.red,
                                  ),
                                  Text("Hit the Like"),
                                ],
                              ),
                            ),
                          ),
                        ),
                    target: Offset(520, 520),
                    duration: Duration(
                        seconds: 3)); //when loading toast is clicked it closes
              },
            ),
          ],
        ),
      ),
    );
  }
}

And here you go your app is ready to show toast messages on both iOS and Android

QR Code scanner in flutter with Example – qrscan flutter package

0
QR code scanner in flutter application development
QR code scanner in flutter application development

Hi Guys, Welcome to Proto Coders Point.

In this Flutter Tutorial we will learn How to implement QR Code Scanner or Bar code scanner in our Flutter App.

so to make this work we gonna use flutter library called QRSCAN

Introduction on QR Code Scanner Flutter

When it comes to barcode scanner each QR or bar code will contain uinque identity number that are used to identify the product. Using this QR code scanner, flutter app you will be able to find out the data value stored in that bar code or QR code.

In the end of this tutorial, our Flutter app will be able to scan both Barcode as well as QRCode.

Then now Let’s begin implementing QR Scan flutter library

DEMO

QR code scanner Flutter example Demo

Video Tutorial

QR Code scanner in flutter development with Example

A Flutter plugin  to scanning. Ready for Android  and iOS devices

Step 1 : Add QR Scanner Dependencies in pubspec.yaml file

To make use of this library you need to add the library into your flutter project, to do so you need to add required dependencies in pubspec.yaml file.

dependencies:
  qrscan: ^0.2.17

Step 2 : Add Camera Permission for Android

offcourse to make use of any physical device of mobile you firstly need to ask for the permission from the user.

under your project open android > app > src > main > AndroidManifest.xml  and just add the below permissions.

camera permission android for QR Scanner
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Step 3 : Add Camera Permission for iOS

Then, even you need to add the camera permission on iOS device so that user can make use of camera to scan the QR or bar code.

adding camera permission for iOS

Add this Permission open ios > Runner > Info.plist

<key>NSCameraUsageDescription</key>
<string>Need Camera Permission for Scanning QR</string>

Now, once you add permission your flutter code can easily make use of camera to scan QR code.

Step 4 : Code to open scanner camera

Firstly, you need to import the qrscan.dart package in you main.dart file or where you want to use QR camera Scanner.

import 'package:qrscan/qrscan.dart' as scanner;

Then, on button pressed you need to run this scanner.scan(); method

String cameraScanResult = await scanner.scan();

Here, the String cameraScanResult will hold the value that is scanned by the camera.

Complete Source code to Scan a QR or BarCode using Flutter application

QR Code Scanner Flutter

Copy Paste below code in main.dart

import 'package:flutter/material.dart';
import 'package:qrscan/qrscan.dart' as scanner;
import 'package:flutter/services.dart';

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

class MyApp extends StatelessWidget {
  @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> {
  String result = "Hello World...!";
  Future _scanQR() async {
    try {
      String cameraScanResult = await scanner.scan();
      setState(() {
        result = cameraScanResult; // setting string result with cameraScanResult
      });
    } on PlatformException catch (e) {
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("QR Scanner Example In Flutter"),
      ),
      body: Center(
        child: Text(result), // Here the scanned result will be shown
      ),
      floatingActionButton: FloatingActionButton.extended(
          icon: Icon(Icons.camera_alt),
          onPressed: () {
            _scanQR(); // calling a function when user click on button
          },
          label: Text("Scan")),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
    );
  }
}

And there you go, you Flutter app is now ready to work on both Android and iOS devices to scan QR code.

Check out : QR scanner app development in android 

Flutter Refresh Indicator – A pull to refresh listview with example

1
Flutter Refresh Indicator
Flutter Refresh Indicator

Hi Guys welcome to Proto Coders Point In this Flutter Tutorial we gonna implement Flutter Refresh Indicator that help app user to refresh the data by just pull down to refresh listview.

Brief about Refresh Indicator

The refresh indicator will be the parent of its child or children, The progress loading indicator will appear when a user will scroll descentdant is over-scrolled. An animated circular progress indicator is faded into view.

When the user swipe down to refresh the data, the onRefresh callback property is been called.The callback is expected to update the scrollable’s contents and then complete the Future it returns.

I have already implemented this feature in android application.

Check out Swipe Refresh Layout – Android Pull down to refresh widget

Let’s begin implementing Refresh Indicator in our Flutter Project.

Flutter Refresh Indicator – A pull to refresh listview with example

flutter pull down to refresh indicator
flutter pull down to refresh indicator

Create new Flutter project

offcourse you need to create a new flutter project or just open any existing project, I am using android-studio to implement this widget.

File > New > New Flutter Project

Remove all the Default code that comes, when you create new Flutter project.

Just Copy paste below code in main.dart

The below code is just to get ride of default code generated by flutter.

Find the complete code of RefreshIndicator below at the end of this tutorial.

import 'package:flutter/material.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("Flutter Refresh Indicator"),
      ),
      body: Container(),
    );
  }
}

 Import async & math package

import 'dart:async';
import 'dart:math';

we are making use of async task and math library.

async package is used so that we can use Future,await and async function.

Math package is used to make use of Random method to generate random numbers.

Variable and method we gonna use

var refreshkey = GlobalKey<RefreshIndicatorState>();
var list;
var random;

GlobalKey : A key that is unique across the entire app. learn more

list : a list that holds array of list data.

random : which holds random number 0 – 10 using Random() method.

initState 

This will be called only once when app get open

@override
  void initState() {
    super.initState();
    random = Random();
    refreshlist();
  }

refreshlist() is an Future async function that refresh the list data, we need to user Future function because onRefresh property of RefreshIndicator accept a Future.

Future<Null> refreshlist() async {
   refreshkey.currentState?.show(
       atTop:
           true); // change atTop to false to show progress indicator at bottom

   await Future.delayed(Duration(seconds: 2)); //wait here for 2 second

   setState(() {
     list = List.generate(random.nextInt(10), (i) => " Item $i");
   });
 }

Here when user pull down to refresh the list is been re-generate again with new data.

UI Design snippet code

In the below code we have RefreshIndicator as a parent of ListView.builder

SizedBox which has it child as Card() where card color is orange,

This card() Widget has child as Text() widget to show text inside the cards.

Scaffold(
      appBar: AppBar(
        title: Text("Flutter Refresh Indicator"),
      ),
      body: Column(
        children: <Widget>[
          Expanded(
            child: RefreshIndicator(
              key: refreshkey,
              child: ListView.builder(
                itemCount: list?.length,
                itemBuilder: (context, i) => SizedBox(
                  height: 80.0,
                  child: Card(
                    color: Colors.orange,
                    child: Center(
                        child: Text(
                      list[i],
                      style: TextStyle(
                          fontSize: 15.0,
                          color: Colors.white,
                          fontWeight: FontWeight.w600),
                    )),
                  ),
                ),
              ),
              onRefresh: refreshlist,
            ),
          ),
          Text(
            "Swipe Down to Refresh List",
            style: TextStyle(fontSize: 25.0),
          ),
          SizedBox(
            height: 25.0,
          )
        ],
      ),
    );

Complete Code of Refresh Indicator flutter with example

Copy paste the Below code in main.dart file

main.dart

import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:math';

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> {
  var refreshkey = GlobalKey<RefreshIndicatorState>();

  var list;
  var random;

  @override
  void initState() {
    super.initState();
    random = Random();
    list = List.generate(random.nextInt(10), (i) => " Item $i");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Flutter Refresh Indicator"),
      ),
      body: Column(
        children: <Widget>[
          Expanded( //Expanded is used so that all the widget get fit into the available screen
            child: RefreshIndicator(
              key: refreshkey,
              child: ListView.builder(
                itemCount: list?.length,
                itemBuilder: (context, i) => SizedBox(
                  height: 80.0,
                  child: Card(
                    color: Colors.orange,
                    child: Center(
                        child: Text(
                      list[i], // array list
                      style: TextStyle(
                          fontSize: 15.0,
                          color: Colors.white,
                          fontWeight: FontWeight.w600),
                    )),
                  ),
                ),
              ),
              onRefresh: refreshlist, //refreshlist function is called when user pull down to refresh
            ),
          ),
          Text(
            "Swipe Down to Refresh List",
            style: TextStyle(fontSize: 25.0),
          ),
          SizedBox(
            height: 25.0,
          )
        ],
      ),
    );
  }

  Future<Null> refreshlist() async {
    refreshkey.currentState?.show(
        atTop:
            true); // change atTop to false to show progress indicator at bottom

    await Future.delayed(Duration(seconds: 2)); //wait here for 2 second

    setState(() {
      list = List.generate(random.nextInt(10), (i) => " Item $i");
    });
  }
}