Home Blog Page 88

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");
    });
  }
}

Flutter ListView using Animated List with Example

0
Flutter ListView using Animated List with Example
Flutter ListView using Animated List with Example

Hi Guys, Welcome to Proto Coders Point , In this Flutter Tutorial we will Implement how to display Listview using Flutter Animated List widget with a simple example.

What is Animated List widget in flutter ?

Suppose you have an application that simply show a ListView and some times items may get updated ( inserted or removed from the list but with normal listView application user will not get to know about the update.

For this reason it would be better if we can show some kind of Animation effect while any item is added or removed from the listview, so the user will be aware of the update. In Flutter Development, we can do it easily using AnimatedList Class

In this Flutter Tutorial example, We gonna store the data in :

List<String> where all the data will be stored in Array form.

I am making use of english_words package to randomly generate a work and add it in our list<String>.

Remember you need to add english_words in pubspec.yaml . get Library here

We also need an instance of GlobalKey<AnimatedListState> so that we can store the state of the AnimatedList widget.

Let’s begin implementing AnimatedList in our flutter project.

Demo on how final code looks like

Flutter animated List view GIF video
Flutter animated List view GIF video

Introduction to basic layout of this project

In this example the layout design is very simple, it contain are Three RaisedButton at the bottom of the app, this button consist of child widget as Icon and Texts. It has functionally such as adding new item or removing the last time or removing all the item from ListView at once.

class AnimatedListExampleState extends State<AnimatedListExample> {
  final GlobalKey<AnimatedListState> _listKey = GlobalKey();

  List<String> _data = [
    WordPair.random().toString(),
    WordPair.random().toString(),
    WordPair.random().toString(),
    WordPair.random().toString(),
    WordPair.random().toString(),
  ];

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Animated List Example'),
        backgroundColor: Colors.blueAccent,
      ),
      persistentFooterButtons: <Widget>[
        RaisedButton(
          child: Icon(Icons.add),
          color: Colors.green,
          onPressed: () {
            _addAnItem();
          },
        ),
        RaisedButton(
          child: Icon(Icons.remove),
          color: Colors.red[200],
          onPressed: () {
            _removeLastItem();
          },
        ),
        RaisedButton(
          child: Text(
            'Remove all',
            style: TextStyle(fontSize: 20, color: Colors.white),
          ),
          color: Colors.red,
          onPressed: () {
            _removeAllItems();
          },
        ),
      ],
      body: Container();
  }

Build Animation for Animated ListView

To show an animation effect, we’re going call a function that simple returns a widget, that widget is wraped into any Transaction Such as:

  • SlideTransition
  • ScaleTransition
  • SizeTransition
  • RotationTransition
  • PositionedTransition
  • RelativePositionedTransition
  • DecoratedBoxTransition
  • AlignTransition
  • DefaultTextStyleTransition
  • FadeTransition

For This example, if we use ScaleTransition,

Widget _buildItem(
    BuildContext context, String item, Animation<double> animation) {
  TextStyle textStyle = new TextStyle(fontSize: 20, color: Colors.white);

  return Padding(
    padding: const EdgeInsets.all(2.0),
    child: ScaleTransition(
      child: SizedBox(
        height: 100.0,
        child: Card(
          color: Colors.lightBlueAccent,
          child: Center(
            child: Text(item, style: textStyle),
          ),
        ),
      ),
      scale: animation,
    ),
  );
}

Creating AnimatedList

In the above snippet code of layout , in body property we simply have an empty container(), we need to replace the body with our listview i’e AnimatedList, To be able to build AnimatedList View,

Here we us _listKey as key parameter and number of items as initialItemCount

body: AnimatedList(
        key: _listKey,
        initialItemCount: _data.length,
        itemBuilder: (context, index, animation) =>
            _buildItem(context, _data[index], animation),
      ),

Insert Item in Animated ListView

To be able to insert an item in AnimatedList, we need to first insert it to _data string array, After that,  we can insert the aminated list using insertItem. Each Time an item is been added the itemBuilder will be called.

void _addAnItem() {
   _data.insert(0, WordPair.random().toString()); //
   _listKey.currentState.insertItem(0);  //
 }

Remove Item

Here are have 2 ways to remove an item:

  1.  Remove latest item
  2.  Remove all item

1. Remove latest item from AnimatedList

To remove the latest item, we need to use removeItem method. That remove item from the _data list

void _removeLastItem() {
    String itemToRemove = _data[0];

    _listKey.currentState.removeItem(
      0,
      (BuildContext context, Animation<double> animation) =>
          _buildItem(context, itemToRemove, animation),
      duration: const Duration(milliseconds: 250),
    );

    _data.removeAt(0);
  }

In the above Snippet code, we are keeping note of latest item “itemToRemove”, After that, we are removing that item from _listKey and then finally remove that item from _data List using removeAt() method.

2. Remove All the item from AnimatedList

Likewise to remove all the item from listview, Firstly we are counting total number of item present in _data using length function, then with the help of for loop we are traversing upto last item in _data list and remove all the item from _data List and then just update the AnimatedList.

void _removeAllItems() {
    final int itemCount = _data.length;

    for (var i = 0; i < itemCount; i++) {
      String itemToRemove = _data[0];
      _listKey.currentState.removeItem(
        0,
        (BuildContext context, Animation<double> animation) =>
            _buildItem(context, itemToRemove, animation),
        duration: const Duration(milliseconds: 250),
      );

      _data.removeAt(0);
    }
  }

 

Complete Code of Flutter AnimatedList View

copy paste the below line of dart code in main.dart

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'ListView Example',
      home: AnimatedListExample(),
    );
  }
}

class AnimatedListExample extends StatefulWidget {
  @override
  AnimatedListExampleState createState() {
    return new AnimatedListExampleState();
  }
}

class AnimatedListExampleState extends State<AnimatedListExample> {
  final GlobalKey<AnimatedListState> _listKey = GlobalKey();

  List<String> _data = [
    WordPair.random().toString(),
    WordPair.random().toString(),
    WordPair.random().toString(),
    WordPair.random().toString(),
    WordPair.random().toString(),
  ];

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Animated List Example'),
        backgroundColor: Colors.blueAccent,
      ),
      persistentFooterButtons: <Widget>[
        RaisedButton(
          child: Icon(Icons.add),
          color: Colors.green,
          onPressed: () {
            _addAnItem();
          },
        ),
        RaisedButton(
          child: Icon(Icons.remove),
          color: Colors.red[200],
          onPressed: () {
            _removeLastItem();
          },
        ),
        RaisedButton(
          child: Text(
            'Remove all',
            style: TextStyle(fontSize: 20, color: Colors.white),
          ),
          color: Colors.red,
          onPressed: () {
            _removeAllItems();
          },
        ),
      ],
      body: AnimatedList(
        key: _listKey,
        initialItemCount: _data.length,
        itemBuilder: (context, index, animation) =>
            _buildItem(context, _data[index], animation),
      ),
    );
  }

  Widget _buildItem(
      BuildContext context, String item, Animation<double> animation) {
    TextStyle textStyle = new TextStyle(fontSize: 20, color: Colors.white);

    return Padding(
      padding: const EdgeInsets.all(2.0),
      child: ScaleTransition(
        child: SizedBox(
          height: 100.0,
          child: Card(
            color: Colors.lightBlueAccent,
            child: Center(
              child: Text(item, style: textStyle),
            ),
          ),
        ),
        scale: animation,
      ),
    );
  }

  void _addAnItem() {
    _data.insert(0, WordPair.random().toString());
    _listKey.currentState.insertItem(0);
  }

  void _removeLastItem() {
    String itemToRemove = _data[0];

    _listKey.currentState.removeItem(
      0,
      (BuildContext context, Animation<double> animation) =>
          _buildItem(context, itemToRemove, animation),
      duration: const Duration(milliseconds: 250),
    );

    _data.removeAt(0);
  }

  void _removeAllItems() {
    final int itemCount = _data.length;

    for (var i = 0; i < itemCount; i++) {
      String itemToRemove = _data[0];
      _listKey.currentState.removeItem(
        0,
        (BuildContext context, Animation<double> animation) =>
            _buildItem(context, itemToRemove, animation),
        duration: const Duration(milliseconds: 250),
      );

      _data.removeAt(0);
    }
  }
}

All set the flutter app is ready to use with AnimatedList view Effect

Recommended Articles

listwheelscrollview3D ListView in flutter

Flutter Image Slider

Swipe Refresh Layout – Android Pull down to refresh widget

0
Swipe Refresh Layout
Swipe Refresh Layout

Hi Guys, welcome to Proto Coders Point  In this Android Tutorial we will implement an Swipe Down Refresh Layout with helps app user to simple pull down to refresh for new Contents

You might have be using many android application those have added the pull to refresh android UI that helps to reload or refresh the feed contents. Loading new content get refreshed when user swipe the view downwords to load the data. Here when user pull down a small loader icon will be shown at the top of the screen and get disappears when contents get loaded completly.

Swipe Refresh Layout – Android Pull Down to Refresh Library

Finally, Google released an official version of the pull-to-refresh library! It is called SwipeRefreshLayout.

This Library is very useful and easy to use where user can easily swipe down or pull down to refresh for new data or contents in the Views.

the official documentation is here:

let’s directly start implementing this library in our android project.

Final Result

pull down to load refresh contents
pull down to load refresh contents

Step 1 will be offcourse Creating new project or working with existing android project

Step 2 : Add Dependencies

To user Swipe Refresh Layout you need to add one required depencencies under gradle Script

Open build.gradle( App level ) and add the below depencencie.

dependencies {
    -----------------
     -----------------
     implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.0.0' // add this line
}

As android support libraries have deprecated and is been replaced by AndroidX, you can find the latest library  here.

Step 3 : open activity_main.xml file to add SwipeRefreshLayout

Now open activity_main.xml file where you need to add the xml code for Swipe Refresh  widget

Snippet code of the Refresh Layout

 <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
        android:id="@+id/swipeRefreshLayout"
        android:layout_width="match_parent"
        android:layout_height="546dp">


        // any View 

</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

Add the below code in xml file

activity_main.xml

Copy paste below code in activity_main.xml file

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:context=".MainActivity"
    android:orientation="vertical">


    <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
        android:id="@+id/swipeRefreshLayout"
        android:layout_width="match_parent"
        android:layout_height="546dp">


        <ListView
            android:id="@+id/listView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
           />

    </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

    <TextView
        android:id="@+id/textshow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textStyle="bold"
        android:textSize="25sp"
        android:text="Pull Down to Refresh"
        android:gravity="center"/>



</LinearLayout>

In the above lines of xml code we have SwipeRefreshLayout as a parent which is a pull to refresh the layout, in this i have a ListView where all the data will be displayed in list form, you can use any Views in it.

Step 4 : Create a new XML Layout

Then you need an XML file with TextView in it, so that we can display text in listview.

Create a new XML file under res>layout and name it as listview_text.xml

listview_text.xml

<?xml version="1.0" encoding="utf-8"?>
<!--  Single List Item Design -->

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/label"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dip"
    android:textSize="16dip"
    android:textStyle="bold" >
</TextView>

Step 5 : Add a listener to Swipe Refresh layout – a pull down to refresh class.

Here is a snippet code to add a listener.

Swipe RefreshLayout pullToRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);

       pullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
           @Override
           public void onRefresh() {
               Data_Function(); // your function call code

           }
       });

This setOnRefreshListener will get called whenever a user swipe down

Copy paste the below lines of code in main class or where you are using this widget.

main_activity.java

package com.ui.swiperefreshlayout;

import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    SwipeRefreshLayout pullToRefresh;
  
    ListView listView;

    String[] mobileArray = {"Android","IPhone","WindowsMobile","Blackberry",
            "WebOS","Ubuntu","Windows7","Max OS X"}; //list of data to show in list view

    ArrayAdapter adapter;

    Handler handler; // handler to show data after some seconds

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        adapter = new ArrayAdapter<String>(this,R.layout.listview_text,mobileArray);
       
        listView = (ListView) findViewById(R.id.listView);
        handler = new Handler();

        pullToRefresh = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);

        pullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Data_Function(); // your code

            }
        });
    }

    public  void Data_Function()
    {
      
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                
                listView.setAdapter(adapter);

                pullToRefresh.setRefreshing(false); // swipe Refresh layout is disabled after first refreshed
            }
        },3000);
    }
}

In the above java code i have

List of array : That holds String values ( Operating System Names )

ArrayAdopter : that holds list of array and an textview layout using which we can set the adoptor to listView.

Handler : To show the data in ListView after some seconds

Flutter Share Plugin with Complete Source Code Example

1
flutter share plugin with example
flutter share plugin with example

Hi Guys, Welcome to Proto Coders Point In this Flutter Tutorial we will look into flutter share plugin with example.

What is Flutter Share plugin?

In Flutter share plugin is very useful when user want’s to sharing contents from flutter app to any of his friends via the platform share dialog box.

This plugin is wraped with ACTION_VIEW INTENT as in android and UIActivityViewController as on iOS devices.

whenever the flutter app user wants to share any contents he can just click on share button which simply pop-up a share dialog using which he/she can easily share contents.

Let’s begin implementing Flutter share Plugin library

Flutter Share Plugin with Example

Step 1 : Add dependencies

To make user of this plugin you need to add share plugin depencencies under project pubspec.yaml file

On right side you will see your Flutter project,

your project name > pubspec.yaml

dependencies:
  share: ^0.6.3+5 //add this line

The Version here given may get update so please visit official site here

Step 2 : Import share.dart package

Once you have add the dependencies file, to make use of this share plugin you need to import package share.dart in any dart file where you need to use this flutter plugin.

import 'package:share/share.dart';

Step 3 : Invoke share plugin method where ever required

To invoke or show a share dialog box in Android or iOS device all you need to do is just invoke share method like this :

Share.share('check out my website https://example.com');

This share method also takes an (optional) subject property that can be used when sharing through email

Share.share('check out my website https://example.com', subject: 'Look what I made!');

Flutter Share Plugin with Complete Source Code Example

main.dart file

Just copy paste below flutter source code under main.dart file

import 'package:flutter/material.dart';
import 'package:share/share.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 Share Intent"),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Center(
            child: Text(
              "Example on Share Plugin Flutter",
              style: TextStyle(fontWeight: FontWeight.w600, fontSize: 25.0),
            ),
          ),
          SizedBox(
            height: 25,
          ),
          Center(
            child: MaterialButton(
              elevation: 5.0,
              height: 50.0,
              minWidth: 150,
              color: Colors.blueAccent,
              textColor: Colors.white,
              child: Icon(Icons.share),
              onPressed: () {
                Share.share(
                    'check out my website https://protocoderspoint.com/');
              },
            ),
          ),
          SizedBox(
            height: 25.0,
          ),
          Center(
            child: Text(
              "Share with Subject  works only while sharing on email",
              style: TextStyle(fontWeight: FontWeight.w600, fontSize: 15.0),
            ),
          ),
          Center(
            child: MaterialButton(
              elevation: 5.0,
              height: 50.0,
              minWidth: 150,
              color: Colors.green,
              textColor: Colors.white,
              child: Icon(Icons.share),
              onPressed: () {
                Share.share(
                    'check out my website https://protocoderspoint.com/',
                    subject: 'Sharing on Email');
              },
            ),
          ),
        ],
      ),
    );
  }
}

Result :

UI Design 

flutter share plugin
UI Design

pop-up of share platform dialog box

flutter share plugin dialog on android device

When user clicks on blue share button and select any messenger to share contents

Flutter share on whatsapp

Then when user choice to share on Email

flutter share on email