Home Blog Page 61

Flutter make call, open a URL website, Send SMS, Email – url_launcher

0
flutter url launcher
flutter url launcher

Hi Guys, Welcome to Proto Coders Point.

In this flutter tutorial, we will make use of url_launcher external package to perform below event.

  1. flutter make a phone call.
  2. flutter launch URL – Load a Website.
  3. flutter send SMS with message to a number.
  4. flutter send email with subject & body message.

So Let’s Begin

Here’s a complete video tutorial of URL_LAUNCHER.


url_launcher flutter package

Flutter url_launcher is a plugin for your flutter project, if you want to add feature in your app such as making a phone call, send a SMS, Email, opening a website(url launch) by taking input from your flutter app users.

Eg:

Make a call: Your app user can simply select a phone number from a list in app and make a direct call in flutter.

Send Email: User can select to whom to send email & enter text in subject & email body and send it.

Open URL from flutter app: Suppose your app display list of website address then user can simply select which website he want to visit and open the website.

Send SMS: A user can send SMS to a number with a message.

Installation of url_launcher

In flutter project open pubspec.yaml file & under dependencies section add url launcher package.

dependencies:
  url_launcher: # latest version

& hit put get button to download and add it.


IOS Setup

Add LSApplicationQueriesSchemes entries in your Info.plist file.

Project > ios > Runner > Info.plist
<key>LSApplicationQueriesSchemes</key>
<array>
  <string>https</string>
  <string>http</string>
</array>

Android Setup

A <queries> element should be added in AndroidManifest.xml

If your app is using https, tel and mailto then add below queries in manifest file.

Project > Android > app > src > main > AndroidManifest.xml
<queries>
  <!-- If your app opens https URLs -->
  <intent>
    <action android:name="android.intent.action.VIEW" />
    <data android:scheme="https" />
  </intent>
  <!-- If your app makes calls -->
  <intent>
    <action android:name="android.intent.action.DIAL" />
    <data android:scheme="tel" />
  </intent>
  <!-- If your app emails -->
  <intent>
    <action android:name="android.intent.action.SEND" />
    <data android:mimeType="*/*" />
  </intent>
</queries>

Import url_launcher.dart

Once you have added the package as external library and make all the platform setup, now you can simply use it just by importing it any where in your project Eg: main.dart

import 'package:url_launcher/url_launcher.dart';

How to use url launcher package in flutter

1] Open a URL in default browser – flutter

http://<url>, https://<url>; eg: https://protocoderspoint.com

launch('https://protocoderspoint.com/');

2] Flutter Make a Phone Call

tel:<phone number>; Eg: tel:+91 8755***8685

launch('tel:+91 88888888888');

3] Flutter send Email with subject and body

mailto:<email address>?subject=<subject>&body=<body>, e.g. mailto:smith@example.org?subject=News&body=New%20plugin

launch('mailto:rajatrrpalankar@gmail.com?subject=This is Subject Title&body=This is Body of Email');

4] Flutter send SMS with message

sms:<phone number>?body=<message>, e.g. sms:5550101234

launch('sms:+91888888888?body=Hi Welcome to Proto Coders Point');

Complete Code flutter url launcher

main.dart

import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.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',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: (){
                launch('tel:+91 88888888888');
              },child: Text("Make A Call"),
            ),
            ElevatedButton(
              onPressed: (){
                launch('sms:+91888888888?body=Hi Welcome to Proto Coders Point');
              },child: Text("Send A SMS"),
            ),
            ElevatedButton(
              onPressed: (){
                launch('mailto:rajatrrpalankar@gmail.com?subject=This is Subject Title&body=This is Body of Email');
              },child: Text("Send A Email"),
            ),
            ElevatedButton(
              onPressed: (){
                launch('https://protocoderspoint.com/');
              },child: Text("Open a URL"),
            ),
          ],
        ),
      )
    );
  }
}

Flutter Rating dialog – Redirect user to app page PlayStore/AppStore

0
how to open playstore from flutter app
how to open playstore from flutter app

Hi Guys, Welcome to Proto Coders Point.

In this flutter tutorial, We will create a Rating dialop popup box with star rating UI & then re-direct users to app page in Google PlayStore or apply AppStore for review rating purpose.

To achieve this we are going to make use of 2 flutter packages.

Video Tutorial


1. Rating_Dialog:

This Library is used to add a beautiful & customizable rating dialog in flutter.

This Package will help us in showing a rating dialog pop, whee we can ask users to share their experience review about app (Rate My App) & then redirect user to app page on Google PlayStore / Apple App Store for review & rating purpose.

I have wrote a complete seperate tutorial on rating_dialog, please check it here.

Add Rating Dialog dependencies in flutter project

Open pubspec.yaml file and under dependencies add it

dependencies:
  flutter:
    sdk: flutter
  rating_dialog: ^2.0.1              #add this line

Import rating_dialog.dart

now you need to just import the library where you want to show dialog rating.

import 'package:rating_dialog/rating_dialog.dart';

Create an Instance of RatingDialog Widget

  final _dialog = RatingDialog(
    // your app's name?
    title: 'Rate Us On App Store',
    // encourage your user to leave a high rating?
    message:
    'Select Number of Stars 1 - 5 to Rate This App',
    // your app's logo?
    image: const FlutterLogo(size: 60),
    submitButton: 'Submit',
    onCancelled: () => print('cancelled'),
    onSubmitted: (response) {
      print('rating: ${response.rating}, comment: ${response.comment}');

      // TODO: add your own logic
      if (response.rating < 3.0) {
        // send their comments to your email or anywhere you wish
        // ask the user to contact you instead of leaving a bad review
      } else {
        //go to app store
        
      }
    },
  );

Then to show the dialog box we make use of flutter showDialog function with will invoke above dialog widget.

showDialog(
              context: context,
              builder: (context) => _dialog,
      );

2. Store_redirect:

By using this library we can redirect users from your app to app page i.e. Google PlayStore or Apple AppStore.

Add Store Redirect dependencies in flutter project

dependencies:
  flutter:
    sdk: flutter
  rating_dialog: ^2.0.1
  store_redirect:                       #add this line

Import store_redirect.dart

now you need to just import the library where you want to use store redirect.

import 'package:store_redirect/store_redirect.dart';

OnButton click natigate user to playstore or appstore

 StoreRedirect.redirect(androidAppId: 'shri.complete.fitness.gymtrainingapp',iOSAppId: 'com.example.rating');

In above StoreRedirect.redirect, we need to pass 2 parameter i.e. your AppId

  • androidAppID: your android AppID.
  • iOSAppId: your iOS AppId.

This Library will automatically control where the user should be redirected, Suppose if user is Android User then he will be navigated to playstore and if the user is iOS User then he will be navigated to Apply AppStore.


Complete Code : Flutter Rating Dialog – Redirect user to playstore/appstore

main.dart

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:rating_dialog/rating_dialog.dart';
import 'package:store_redirect/store_redirect.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 {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  final _dialog = RatingDialog(
    // your app's name?
    title: 'Rate Us On App Store',
    // encourage your user to leave a high rating?
    message:
    'Select Number of Stars 1 - 5 to Rate This App',
    // your app's logo?
    image: const FlutterLogo(size: 60),
    submitButton: 'Submit',
    onCancelled: () => print('cancelled'),
    onSubmitted: (response) {
      print('rating: ${response.rating}, comment: ${response.comment}');

      // TODO: add your own logic
      if (response.rating < 3.0) {
        // send their comments to your email or anywhere you wish
        // ask the user to contact you instead of leaving a bad review
      } else {
        //go to app store
        StoreRedirect.redirect(androidAppId: 'shri.complete.fitness.gymtrainingapp',iOSAppId: 'com.example.rating');
      }
    },
  );


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: ElevatedButton(
          onPressed: (){
            
             // load dialog to show it 
            showDialog(
              context: context,
              builder: (context) => _dialog,
            );
          },child: Text('Show Rating Dialog'),
        ),
      )
    );
  }
}

Flutter web implementing drop down with hover effect

0
Flutter Web hover effect in dropdown list
Flutter Web hover effect in dropdown list

Hi Guys, Welcome to Proto Coders Point.

In this flutter tutorial, we will learn how to implement flutter dropdown with hover effect animation.

Note: Hovering effect in flutter works only on flutter web & By running same code in android & iOS you will not see any hovering animation effect.

Below GIF image is the final output for this tutorial, we have a app which has a flutter dropdown with hover effect, when a mouse pointer is hovered on items of dropdown list, you can see a item is highlighted with a slight animation effect.

Now let’s create this from start…..

1. Create/Open a flutter project

Firstly, create/open any new flutter project where you want to implement hover effect on dropdown list, I make use of Android Studio with is best IDE for Flutter development.

File -> New -> New Flutter Project(finish) // project is ready.


2. Create a custom flutterWidget OnHover.dart

Under lib directory, create a new dart file & name it as OnHover.dart.

So OnHover.dart will be our custom stateful widget which has properties such as animatedContainer & MouseRegion widget which is use to detect when our mouse pointer comes in MouseRegion to perform hover effect in flutter with animation to any widgets.

OnHover.dart

import 'package:flutter/material.dart';

class OnHover extends StatefulWidget {

  final Widget Function(bool isHovered) builder;

  const OnHover({Key? key, required this.builder}) : super(key: key);

  @override
  _OnHoverState createState() => _OnHoverState();
}

class _OnHoverState extends State<OnHover> {

  bool isHovered = false;
  @override
  Widget build(BuildContext context) {

     // on hover animation movement matrix translation
    final hovered = Matrix4.identity()..translate(10,0,0);
    final transform = isHovered ? hovered : Matrix4.identity();

    // when user enter the mouse pointer onEnter method will work
   // when user exit the mouse pointer from MouseRegion onExit method will work
    return MouseRegion(
      onEnter: (_)=> onEntered(true),
      onExit: (_)=> onEntered(false),
      child: AnimatedContainer(
        duration: Duration(milliseconds: 300),
        transform: transform,             // animation transformation hovered.
        child: widget.builder(isHovered),   // build the widget passed from main.dart
      ),
    );
  }

  //used to set bool isHovered to true/false
  void onEntered(bool isHovered){
    setState(() {
      this.isHovered = isHovered;
    });
  }
}

OnHover custom widget can be used to give hover effect to any widget in flutter, you just need to wrap widget with OnHover widget builder.


3. Create a dropdown list in flutter with hover effect

main.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hover_eg/OnHover.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: DropDownPage(),
    );
  }
}


class DropDownPage extends StatefulWidget {
  const DropDownPage({Key? key}) : super(key: key);

  @override
  _DropDownPageState createState() => _DropDownPageState();
}

class _DropDownPageState extends State<DropDownPage> {
  //list of item to show in flutter drop down 
  static final data = ['Lion', 'Tiger', 'Shark', 'Snake', 'Bear','Crocodile','Monkey'];
  String initial = data.first.toString();

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      body: Center(
          child: DropdownButton(
            value: initial,
            icon: Icon(Icons.keyboard_arrow_down),
            items: Textpage.texts.map((String items) {
              return DropdownMenuItem(
                  value: items,
                  child: OnHover(
                     //Wraping the DropDownMenuItem child so then when Items of drop down is hovering we see hovering effect
                    builder: (isHovered){
                      final color = isHovered ? Colors.blue:Colors.black;
                      return Text('$items',style: TextStyle(color: color),);
                    },
                  ));
            }).toList(),
            onChanged: (String? newvalue){
              setState(() {
                initial = newvalue!;
              });
            },
          )
      ),
    );
  }
}

Hover effect in flutter web – hover effect with animation to any widget

0
hover effect in flutter web
hover effect in flutter web

Hi Guys, Welcome to Proto Coders Point.

In this flutter tutorial, we will learn how to give hover effect in flutter web.

Note: Hover effect in flutter can only be implemented on flutter web app, therefore onhover in mobile device will not give any hovering effect.

Video Tutorial

flutter hover effect video tutorial

so let’s begin with the coding.

How to give hover effect to any widget in flutter

1. Create a flutter project

Open you favorite IDE & create/open a new flutter project, I am using android-studio to build flutter projects.

File > New > New Flutter Project ( Give a good name to flutter project & finish) your project will get created.

2. Create a dart file OnHover.dart

Under lib directory, create a new dart file & name it as OnHover.dart.

So OnHover.dart will be our custom stateful widget which has properties such as animatedContainer & MouseRegion widget which is use to detect when our mouse pointer comes in MouseRegion to perform hover effect in flutter with animation to any widgets.

OnHover.dart

import 'package:flutter/material.dart';

class OnHover extends StatefulWidget {

  final Widget Function(bool isHovered) builder;

  const OnHover({Key? key, required this.builder}) : super(key: key);

  @override
  _OnHoverState createState() => _OnHoverState();
}

class _OnHoverState extends State<OnHover> {

  bool isHovered = false;
  @override
  Widget build(BuildContext context) {

    final hovered = Matrix4.identity()..translate(0,-10,0);
    final transform = isHovered ? hovered : Matrix4.identity();

    return MouseRegion(
      onEnter: (_)=> onEntered(true),
      onExit: (_)=> onEntered(false),
      child: AnimatedContainer(
        duration: Duration(milliseconds: 300),
        transform: transform,
        child: widget.builder(isHovered),
      ),
    );
  }

  void onEntered(bool isHovered){
    setState(() {
      this.isHovered = isHovered;
    });
  }
}

3. Add Hover effect to any widget in flutter

Now, our OnHover custom widget is ready(above), so now we can use it to give animation & hover effect to any widget in flutter.

To do that you need to simply wrap any widget with OnHover widget builder to apply Hovering effect.

Examples:

Flutter text animation on hover – change text color

OnHover(builder: (isHovered){
              return Text("Flutter Text on hover - change text color on hovering with animation");
 }),

Change Container Color on Hover

 OnHover(builder: (isHovered){
              final color = isHovered ? Colors.grey : Colors.blue;
              return
                Container(
                  color: color,
                  width: 100,
                  height: 100,
                );

            }),
flutter change container color on hover

Hover elevation flutter

OnHover(builder: (isHovered){
              return
              PhysicalModel(
                color: Colors.blue,
                elevation: isHovered ? 16 : 0,      // if ishovered true then show elevation on hovering
                child: Container(
                  width: 100,
                  height: 100,
                ),
              );

       }),
flutter elevation hover effect

change flutter button color on hover

OnHover(builder: (isHovered){
              final  color = isHovered ? Colors.red : Colors.blue;
              return
               ElevatedButton(
                   style: ElevatedButton.styleFrom(primary: color),
                   onPressed: (){}, child: Text('Change Button Color on hover')
               );

            }),
flutter button color change on hover


main.dart complete code

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hover_eg/OnHover.dart';
import 'package:flutter_hover_eg/text_page.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("Hover Example"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            OnHover(
              builder: (isHovered) {
                final color = isHovered ? Colors.orange : Colors.redAccent;
                return PhysicalModel(
                  color: Colors.white,
                  elevation: isHovered ? 16 : 0,
                  child: Container(
                      height: 50,
                      width: 200,
                      color: color,
                      child: Center(
                        child: Text("Proto Coders Point"),
                      )),
                );
              },
            ),
            SizedBox(
              height: 30,
            ),
            OnHover(builder: (isHovered) {
              return Text(
                  "Flutter Text on hover - change text color on hovering with animation");
            }),
            SizedBox(
              height: 30,
            ),
            //if isHovered is true then show elevation else set elevation to 0
            OnHover(builder: (isHovered) {
              return PhysicalModel(
                color: Colors.blue,
                elevation: isHovered ? 16 : 0,
                child: Container(
                  width: 100,
                  height: 100,
                ),
              );
            }),

            OnHover(builder: (isHovered) {
              final color = isHovered ? Colors.grey : Colors.blue;
              return Container(
                color: color,
                width: 100,
                height: 100,
              );
            }),
            SizedBox(
              height: 30,
            ),
            OnHover(builder: (isHovered) {
              final color = isHovered ? Colors.red : Colors.blue;
              return ElevatedButton(
                  style: ElevatedButton.styleFrom(primary: color),
                  onPressed: () {},
                  child: Text('Change Button Color on hover'));
            }),
          ],
        ),
      ),
    );
  }
}

Prime Number program in dart

0
CHECK PRIME NUMBER Dart Program
CHECK PRIME NUMBER Dart Program

Hi Guys, Welcome to Proto Coders Point, In this dart tutorial we will learn, What is a prime number, check if a given number in prime or not & a dart program to print prime number from 1 to N.

What is a Prime Number?

A Prime Number in math are the numbers that are greater then 1 & are divisible by 1 or itself.

In other Words, A number that can’t be divided by any other number, rather then 1 or itself.

Prime Number Examples

Eg:

5 => 5 can’t be divided by any other numbers.
3 => 3 can’t be divided by any other numbers.
7 => 7 can’t be divided by any other numbers.
13 => 13 can’t be divided by any other numbers.

Not a Prime Number Examples

Eg:

4 => 4 is divisible by 2 so it not a prime number.
6 => 6 is divisible by 2 so it not a prime number.
8 => 8 is divisible by 2 so it not a prime number.
10 => 10 is divisible by 2 so it not a prime number.

If you observe you can see that, all the even number are not a prime number, except 2.

NOTE: 0 and 1 are always said to be not a prime number.

How to check if a number is prime or not in dart

Let’s write dart programs to check if a number is prime or no.

1. Dart Program to check a number prime or no

In this dart program, we will initialize a Integer with a number value & then check if that number is prime or no.

void main(){
  int i,m=0,flag=0;
  int num = 5;

  m=num~/2;

  for(i = 2;i<=m;i++){
    if(num%i == 0){
      print('$num is not a prime number');
      flag=1;
      break;
    }
  }

  if(flag==0){
    print('$num is prime number');
  }
}

2. check prime number using method in dart program

void main(){
     // call method by passing a integer value to it
     checkPrime(5);
     checkPrime(8);
     checkPrime(13);
     checkPrime(76);
     checkPrime(7);
}

// a method that checks prime or not prime
void checkPrime(int num){
   int i,m=0,flag=0;
 
  m=num~/2;


  for(i = 2;i<=m;i++){
    if(num%i == 0){
      print('$num is not a prime number');
      flag=1;
      break;
    }
  }

  if(flag==0){
    print('$num is prime number');
  }
}
dart program check prime number

3. Prime number dart program – take input from user

So now in below code, the number to be checked is not predefined, Here the dart code will ask the user to enter a number to be checked whether it a prime or not

import 'dart:io';
import 'dart:math';
void main(){
  

   print('Enter number to check prime or no');

   int? num = int.parse(stdin.readLineSync()!); 

  print('$num');

  if(CheckPrime(num)){
           print('$num is a prime');
  }else{
    print('$num is not a prime');
  }

}

bool CheckPrime(int num){

  if(num<=1){
     return false;
  }
  
  for (int i = 2;i<=sqrt(num);i++){
    if(num%i == 0){
      return false;
    }
  }
  return true;

}
prime number program in dart
prime number program in dart

4. Dart program to print prime number from 1 to N

Now let’s write a dart program to print all the prime numbers from 1 to N.

import 'dart:io';
import 'dart:math';

void main(){
      print('Enter Nth');
      int? N = int.parse(stdin.readLineSync()!);
      print('----------------------------');
      for(int i=2;i<= N;i++){
        checkPrime(i);
      }
}

void checkPrime(int num){
   int i,m=0,flag=0;
   m=num~/2;
  for(i = 2;i<=m;i++){
    if(num%i == 0){
      flag=1;
      break;
    }
  }

  if(flag==0){
    print('$num');
  }
}
print prime number 1 to N


Similar dart programs to learn dart language

Generate Random number in dart

palindrome program in dart

ArmStrong number program in dart

Fibonacci sequence in dart

pattern program in dart

string to ascii

prime number program in dart

How to dismiss keyboard in flutter – lose textfield focus

0
how to dismiss keyboard in flutter
how to dismiss keyboard in flutter

Hi Guys, Welcome to Proto Coders Point. OK so your are looking for a solution that, when a user tap outside TextField you need to dismiss the keyboard from the screen and want to textfield lose focus.

So In this Flutter Tutorial, let’s Learn how to dismiss the keyboard in flutter when user tap on the screen.

Two Examples how to dismiss a keyboard

  1. Example 1: When user tap on any Empty space on the Mobile screen, The keyboard should get dismissed and the textfield which is focused should also get unfocused.
  2. Example 2: Suppose you have a Listview with lists of widget(Text Input Field) in it, then user fill the textfield and scroll down, than the keyboard should get dismissed and flutter textfield lose focus on listview scroll.

Example 1 – To dismiss the keyboard and lose focus

Step 1: Wrap Scaffold with GestureDetector

You must implement a tap detector (GestureDetector onTap), when user tapped outside the current active textField.

GestureDetector(
  onTap: () {},
  child: ...//Eg: Scafford
)

You can Simply achieve this by using GestureDetector widget, which makes it simple and easiest way to detect onTap outside the focused TextField.

Step 2: On Tap Dismiss the keyboard

To close keyboard / to hide the keyboard you need to simply remove focus from textfield & thus it automatically dismiss the keyboard.

So to remove focus from textfield you just need to run FocusScope unfocus, when user tap outside the textfield.

FocusScope.of(context).unfocus();
Snippet code

GestureDetector(
      onTap: ()=> FocusScope.of(context).unfocus(), // on tap run this code
      child: ...// Scaffold Widget
    );

Complete Code for Example 1 to dismiss keyboard in flutter

import 'package:flutter/material.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> {
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: ()=> FocusScope.of(context).unfocus(),
      child: Scaffold(
        appBar: AppBar(title: Text('KeyBoard Example'),),
        body: Padding(
           padding: const EdgeInsets.all(16.0),
           child:TextField(
           decoration: InputDecoration(
             border: OutlineInputBorder(),
             labelText: 'Enter your Name'
           ),
         ),
        ),
      ),
    );
  }
}


Example 2 – On ListView Scroll dismiss keyboard

Suppose you have a Listview with lists of widget(Text Input Field) in it, then user fill the textfield and scroll down, than the keyboard should get dismissed and flutter textfield lose focus on listview scroll.

In that case you can make user of Listview keyboardDismissBehaviour with ScrollViewKeyboardDismissBehavior.onDrag

 ListView(
        keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
        children: [
           // list of childs
        ],
      )

keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag: When a keyboard is active and user scroll through the listview then keyboard will get dismissed automatically

Check out the example in below gif image.

Complete Code to dismiss keyboard on scroll

import 'package:flutter/cupertino.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> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('KeyBoard Example'),),
      body: ListView(
        keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
        children: [
          Padding(
            padding: const EdgeInsets.all(16.0),
            child:TextField(
              decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  labelText: 'Enter your Name'
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(16.0),
            child:TextField(
              decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  labelText: 'Enter your Name'
              ),
            ),
          ),
          Text("Enter Some Text here",style: TextStyle(fontSize: 30),),
         // add more widgets here 
        ],
      )
    );
  }
}