Home Blog Page 85

Integration of Google Maps in Flutter with Example using a plugin

1

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we gonna integrate Flutter Google Maps in our Flutter Project using a Plugin.

So to add google maps in your flutter project, Google API is needed.

DEMO

google maps flutter example in gif

Step 1: How to get Google Map API key?

To get API key go to the link https://cloud.google.com/maps-platform/ Create a new Google Project under your console.

Follow the Screenshot Steps to get API

step 1 to get API key credentials

create new credential api key

how to get google api key

Then now you have API key with you, keep a note of it.

Step 2 : adding google maps flutter dependencies

Do Follow this link the official site to get latest version here

Open pubspec.yaml file and app the plugin library dependencies file.

dependencies:
  google_maps_flutter: ^0.5.25 // add this line

Step 3: Import the google map flutter library

After you have added the required dependencies now you need to import the library whereever  you need to implement google maps in flutter app.

import 'package:google_maps_flutter/google_maps_flutter.dart';

Step 4 : Specifying the Google API key in AndroidManifest.xml ( ANDROID )

open AndroidManifest.xml file and add the <meta-data> tag inside <application> tag

<manifest ...
  <application>

    <meta-data android:name="com.google.android.geo.API_KEY"
               android:value="YOUR KEY HERE"/>                  // add this line and replace with you API KEY

  </application>
</manifest>

Step 5: Specifying API key in AppDelegate.swift ( for iOS)

in iOS you need to Specify Application delegates  to make use of google maps services in  IOS

To do so navigate ios/Runner/AppDelegate.swift

import UIKit
import Flutter
import GoogleMaps   // add this line 

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GMSServices.provideAPIKey("YOUR KEY HERE")      // add this line replace  with your API KEY
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

 

Snippet code of GoogleMaps widget in flutter

GoogleMap(
      mapType: MapType.normal,
      initialCameraPosition:
          CameraPosition(target: LatLng(15.841461, 74.512202), zoom: 18),
      onMapCreated: (GoogleMapController controller) {
        _controller.complete(controller);
      },
      markers: {belgaum},
    ),

mapType: Specify which kind of map interface do you want to load.

  • normal.
  • satellite.
  •  hybrid.
  • terrain.

MapType in flutter google maps widget

initialCameraPosition: This will load the map with initial camera position may be currect location of the users.

onMapCreated: this will create a map with complete controls to the map you can zoom in, zoom out, go to other location in the map and many things under your controls.

Google Marker

Marker belgaum = Marker(
  markerId: MarkerId("Belgaum"),
  position: LatLng(15.841461, 74.512202),
  infoWindow: InfoWindow(title: "Belgaum"),
  icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueRose),
);

The Marker will keep a marker on the position you have or any be the destination point you want to travel to.

Flutter google maps  Complete Source Code with example

Copy paste the below source code in main.dart file

NOTE: Don’t forget to specify the API KEY, else the google maps will not work/load.

import 'dart:async';

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

void main() => runApp(MyApp());
Completer<GoogleMapController> _controller = Completer();

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("Google Maps in Flutter Example"),
      ),
      body: Stack(
        children: <Widget>[_googleMaps(context)],
      ),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: _goToNextLocation,
        label: Text('To the Next Location'),
        icon: Icon(Icons.directions_boat),
      ),
    );
  }
}

Widget _googleMaps(BuildContext context) {
  return Container(
    height: MediaQuery.of(context).size.height,
    width: MediaQuery.of(context).size.width,
    child: GoogleMap(
      mapType: MapType.terrain,
      initialCameraPosition:
          CameraPosition(target: LatLng(15.841461, 74.512202), zoom: 18),
      onMapCreated: (GoogleMapController controller) {
        _controller.complete(controller);
      },
      markers: {belgaum},
    ),
  );
}

Marker belgaum = Marker(
  markerId: MarkerId("Belgaum"),
  position: LatLng(15.841461, 74.512202),
  infoWindow: InfoWindow(title: "Belgaum"),
  icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueRose),
);

Future<void> _goToNextLocation() async {
  final GoogleMapController controller = await _controller.future;
  controller.animateCamera(
    CameraUpdate.newCameraPosition(
      CameraPosition(
          target: LatLng(37.43296265331129, -122.08832357078792),
          zoom: 19.151926040649414,
          tilt: 59.440717697143555,
          bearing: 192.8334901395799),
    ),
  );
}

 

How to Make Email Validation in Flutter – Using Email Validator Library

0
Flutter Email Validation library
Hi Guys, Welcome to Proto Coders Point,  In this Flutter Tutorial we will integrate Flutter library called Email Validator to validate email address.

Email Validation

Usually Email Validation is done, by a String value that contains alphabets, @ symbols and a .(dot) symbol For Example: contact@protocoderspoint.com, This email address contains all the characters required to be a perfect/valid email address.

Flutter Email Validation Library

Flutter Comes with awesome and easy to use flutter Library/Plugins. This Email validation flutter library is pre defined class that validated email addresses. You just need to call its class. This plugin is very easy to use and understand. Visit official site to learn more here Let’s start adding the library in our Flutter Project.

Adding Dependencies in our project

Open Pubspec.yaml and add the dependencies
dependencies:
  email_validator: ^1.0.4 // add this line

Import the email validator dart class

you need to import the email_validator.dart file, where you want to make use validator library. In my case i have imported it in main.dart file
import 'package:email_validator/email_validator.dart';
And their you go now you can use the library.

Snippet Code Example how to use it

    const String email = 'contact@protocoderspoint.com';
    final bool isValid = EmailValidator.validate(email);

    print('Email is valid? ' + (isValid ? 'yes' : 'no'));
The above code is snippet code, Their is a string that holds email address, a boolen type variable that stored true or false based on email address, is the email is valid it will store true else false. (isValid ? ‘yes’ : ‘no’) :  is similar to if else statement.

Complete code on Email Validation in flutter

In my flutter project i have 2 dart files. main.dart is with TextFormField() where we will check if email is valid, if entered email is valid that the user will be navigated to page2.dart main.dart Copy paste the below code in main.dart
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:email_validator/email_validator.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'page2.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.yellow,
      ),
      home: MyHomePage(),
    );
  }
}

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

class _MyHomePageState extends State<MyHomePage> {
  final _emailcontroller = TextEditingController();
  bool isvalid = false;

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    return Scaffold(
      appBar: AppBar(
        title: Text("Email Validate Example"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Center(
          child: Column(
            children: <Widget>[
              Text(
                "Example on Email Validation",
                style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.bold,
                    fontStyle: FontStyle.italic),
              ),
              Container(
                height: 10,
              ),
              TextFormField(
                controller: _emailcontroller,
                decoration: InputDecoration(
                    labelText: "Email",
                    labelStyle: TextStyle(color: Colors.blue),
                    focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.red),
                        borderRadius: BorderRadius.circular(10.0)),
                    enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: Colors.red),
                        borderRadius: BorderRadius.circular(10.0))),
              ),
              SizedBox(
                height: 10,
              ),
              RaisedButton(
                onPressed: () {
                  isvalid = EmailValidator.validate(_emailcontroller.text);
                  if (isvalid) {
                    Navigator.push(context,
                        MaterialPageRoute(builder: (context) => Page2()));
                  } else {
                    Fluttertoast.showToast(
                        msg: "Please Enter a valid Email",
                        toastLength: Toast.LENGTH_SHORT,
                        gravity: ToastGravity.BOTTOM,
                        timeInSecForIos: 1,
                        backgroundColor: Colors.red,
                        textColor: Colors.white,
                        fontSize: 16.0);
                  }
                },
                child: Container(
                  width: width * 0.5,
                  child: Center(
                    child: Text(
                      "Submit",
                      style: TextStyle(color: Colors.white),
                    ),
                  ),
                ),
                color: Colors.blue,
              ),
            ],
          ),
        ),
      ),
    );
  }
}
page2.dart Create a new dart page in lib folder of your flutter project and add below code. the below code is simply a UI where we show a Text.
import 'package:flutter/material.dart';

class Page2 extends StatefulWidget {
  @override
  _Page2State createState() => _Page2State();
}

class _Page2State extends State<Page2> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Email Validator Flutter plugin"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text("Email Address is validate"),
          ],
        ),
      ),
    );
  }
}
Check out Similar Articles on Validation Flutter Password Validation Flutter Form Validation Flutter Email Validation using plugin Flutter Email Regex Pattern

Flutter Sqlite Tutorial using Flutter Sqflite library with example

0
Flutter SqfLite database Insert, Update, Delete

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we will learn how to use SQLITE in Flutter.

What is SQLite ?

SQLite is a Database Library that provides a relational database management system(RDBMS). Here Lite means a very light weight process in term of setup or administration.

Sqlite have very awesome feature : Zero Configuration, Transactional management, Serverless database support and much more.

Flutter SQLite is very small  as small as 400kb in size.

SQLite Source code is open for all the developers any one can use then to develop a data storage.

Now a day’s SQLite are mostly use in storing data locally

For Example : A user plays a games with is completely offline, So all Hs data will be stored in SQLITE DATABASE Locally.

Let’s Start adding the Required Dependencies into our Flutter Project.

Flutter Sqflite library Adding dependencies

Step1: Open Pubspec.yaml file and add dependencies

dependencies:
  sqflite: ^1.3.0 // add this line

NOTE : Latest feature might get added in this flutter plugin so better check out official site for latest version.

Step2: Import Sqlite dart file

Once you have added the dependencies, Now you can easily user the sqlite packages in your flutter project by just importing the dart file.

import 'package:sqflite/sqflite.dart';

How to create a Sqlite Database in Flutter?

Opening a database

Get location of database using getdatabasepath() method.

var databasesPath = await getDatabasesPath();
String path = join(databasesPath, 'student.db');
var db = await openDatabase(path);

here path is a string variable where our database path is been stored.

Closing database which is open.
await db.close();
Opening the database and creating a new TABLE in it.
Database database = await openDatabase(path, version: 1,
    onCreate: (Database db, int version) async {
  await db.execute(
      'CREATE TABLE USER (id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT, ID INTEGER)');
});

Here in above example i have opened the database and created a new table called as USER.

Ok Now let’s implement SQFLite in our Flutter Application

Flutter Sqlite Tutorial with INSERT, UPDATE and DELETE Option.

Create a new Dart file which is actually an SQLITE_DBHelper

Project file > lib (right click) > New > Dart 

create a file and name it as SQLITE_DBHelper.dart

creating new file sqlite db helper

and copy paste below database helper code.

import 'package:flutter/cupertino.dart';
import 'dart:async';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

class DBStudentManager {
  Database _datebase;

  Future openDB() async {
    if (_datebase == null) {
      _datebase = await openDatabase(
          join(await getDatabasesPath(), "student.db"),
          version: 1, onCreate: (Database db, int version) async {
        await db.execute(
            "CREATE TABLE student(id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT,course TEXT)");
      });
    }
  }

  Future<int> insertStudent(Student student) async {
    await openDB();
    return await _datebase.insert('student', student.toMap());
  }

  Future<List<Student>> getStudentList() async {
    await openDB();
    final List<Map<String, dynamic>> maps = await _datebase.query('student');

    return List.generate(maps.length, (index) {
      return Student(
          id: maps[index]['id'],
          name: maps[index]['name'],
          course: maps[index]['course']);
    });
  }

  Future<int> updateStudent(Student student) async {
    await openDB();
    return await _datebase.update('student', student.toMap(),
        where: 'id=?', whereArgs: [student.id]);
  }

  Future<void> deleteStudent(int id) async {
    await openDB();
    await _datebase.delete("student", where: "id = ? ", whereArgs: [id]);
  }
}

class Student {
  int id;
  String name;
  String course;

  Student({ @required this.name, @required this.course,this.id});
  Map<String, dynamic> toMap() {
    return {'name': name, 'course': course};
  }
}

Now you have database helper class that returns all the data you request from main class.

main.dart

Replace all the default code with below code in main.dart file

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

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

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

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

class _MyHomePageState extends State<MyHomePage> {
  final DBStudentManager dbStudentManager = new DBStudentManager();
  final _nameController = TextEditingController();
  final _courseController = TextEditingController();
  final _formkey = new GlobalKey<FormState>();
  Student student;
  int updateindex;

  List<Student> studlist;

  @override
  Widget build(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    return Scaffold(
      appBar: AppBar(
        title: Text("Flutter Sqflite Example"),
      ),
      body: ListView(
        children: <Widget>[
          Form(
            key: _formkey,
            child: Padding(
              padding: const EdgeInsets.all(12.0),
              child: Column(
                children: <Widget>[
                  TextFormField(
                    decoration: InputDecoration(labelText: "Name"),
                    controller: _nameController,
                    validator: (val) =>
                        val.isNotEmpty ? null : "Name Should not be Empty",
                  ),
                  TextFormField(
                    decoration: InputDecoration(labelText: "Course"),
                    controller: _courseController,
                    validator: (val) =>
                        val.isNotEmpty ? null : "Course Should not be Empty",
                  ),
                  RaisedButton(
                    textColor: Colors.white,
                    color: Colors.lightBlue,
                    child: Container(
                        width: width * 0.9,
                        child: Text(
                          "Submit",
                          textAlign: TextAlign.center,
                        )),
                    onPressed: () {
                      submitStudent(context);
                    },
                  ),
                  FutureBuilder(
                    future: dbStudentManager.getStudentList(),
                    builder: (context, snapshot) {
                      if (snapshot.hasData) {
                        studlist = snapshot.data;
                        return ListView.builder(
                          shrinkWrap: true,
                          itemCount: studlist == null ? 0 : studlist.length,
                          itemBuilder: (BuildContext context, int index) {
                            Student st = studlist[index];
                            return Card(
                              child: Row(
                                children: <Widget>[
                                  Padding(
                                    padding: const EdgeInsets.all(16.0),
                                    child: Container(
                                      width: width * 0.50,
                                      child: Column(
                                        children: <Widget>[
                                          Text('ID: ${st.id}'),
                                          Text('Name: ${st.name}'),
                                        ],
                                      ),
                                    ),
                                  ),
                                  IconButton(
                                    onPressed: () {
                                      _nameController.text = st.name;
                                      _courseController.text = st.course;
                                      student = st;
                                      updateindex = index;
                                    },
                                    icon: Icon(
                                      Icons.edit,
                                      color: Colors.blue,
                                    ),
                                  ),
                                  IconButton(
                                    onPressed: () {
                                      dbStudentManager.deleteStudent(st.id);
                                      setState(() {
                                        studlist.removeAt(index);
                                      });
                                    },
                                    icon: Icon(
                                      Icons.delete,
                                      color: Colors.red,
                                    ),
                                  ),
                                ],
                              ),
                            );
                          },
                        );
                      }
                      return CircularProgressIndicator();
                    },
                  )
                ],
              ),
            ),
          )
        ],
      ),
    );
  }

  void submitStudent(BuildContext context) {
    if (_formkey.currentState.validate()) {
      if (student == null) {
        Student st = new Student(
            name: _nameController.text, course: _courseController.text);
        dbStudentManager.insertStudent(st).then((value) => {
              _nameController.clear(),
              _courseController.clear(),
              print("Student Data Add to database $value"),
            });
      } else {
        student.name = _nameController.text;
        student.course = _courseController.text;

        dbStudentManager.updateStudent(student).then((value) {
          setState(() {
            studlist[updateindex].name = _nameController.text;
            studlist[updateindex].course = _courseController.text;
          });
          _nameController.clear();
          _courseController.clear();
          student = null;
        });
      }
    }
  }
}

And there your app is ready to open a datebase/ create a new database , create a new table and store all the data in it and even delete or update the present data base using Sqflite flutter library.

Flutter date time picker library with example

1

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we gonna implement datetime picker flutter library.

Brief about date time picker library

A date time picker is a widget library using which your flutter app user can easily select date or time.

This library comes with different set of languages :

Some of them are : Arabic(ar), Armenian(hy) , Azerbaijan(az) ,Chinese(zh) , Dutch(nl) ,English(en) and much more ( Visit official site to know more ).

Ok then Let’s start implementing the date time library in our flutter project.

Step 1: Add the Dependencies

Navigate towords / open pubspec.yaml

Then add the following date time picker dependencies, what this does it that it downloads all the required packages  into our flutter project as External Libraries.

dependencies:
  flutter_datetime_picker: ^1.3.5 //add this line

Then, after adding the dependencies just click on Packages Get.

Step 2: Import the package

once you have added dependencies all the package will be stored in external libraries if you want to use them you need to import the required package

For example : if you want to use the library in main.dart file you need to import it.

import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';

Time picker snippet code

DatePicker.showTime12hPicker(context,
                   showTitleActions: true,
                   currentTime: DateTime.now(), onConfirm: (time) {
                 setState(() {
                   pickedtime = "Picked time is : ${time.hour} : ${time.minute} : ${time.second}";
                 });

DateTime.now() function will fetch the current time from the users mobile phone and store it in time variable.

time picker flutter ui

you can access the time based on your requirement

For example:

Suppose you have time format as : 07 : 50 : 00

time.hour will return : 7

time.minute will return : 50

time.second will return : 00

Date Picker Snippet code

DatePicker.showDatePicker(context,
                        showTitleActions: true,
                        minTime: DateTime(2018, 3, 5),
                        maxTime: DateTime(2026, 6, 7), onChanged: (date) {
                      print('change $date');
                      setState(() {
                        pickeddate = "${date.day}";
                      });
                    }, onConfirm: (date) {
                      print('confirm $date');
                      setState(() {
                        pickeddate =
                            "Picked Date is : ${date.day}/${date.month}/${date.year}";
                      });
                    }, currentTime: DateTime.now(), locale: LocaleType.en);

In date picker you have properties such as:

date picker flutter ui design

minTime : where you can set starting range of date picker in flutter.

maxTime : Where you can set upto or max range of date picker in flutter.

date can accessed in 3 different ways 

those are : day, month, year.

Complete Source code for date time picker library

Copy Paste below lines of code in main.dart file

main.dart

import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.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> {
  var pickeddate;
  var pickedtime;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Flutter Date time Picker"),
        ),
        body: Center(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              SizedBox(
                height: 50.0,
              ),
              FloatingActionButton.extended(
                onPressed: () {
                  DatePicker.showTime12hPicker(context,
                      showTitleActions: true,
                      currentTime: DateTime.now(), onConfirm: (time) {
                    setState(() {
                      pickedtime =
                          "Picked time is : ${time.hour} : ${time.minute} : ${time.second}";
                    });
                  });
                },
                label: Text("Set Time"),
                icon: Icon(Icons.timer),
              ),
              SizedBox(
                height: 25,
              ),
              FloatingActionButton.extended(
                onPressed: () {
                  DatePicker.showDatePicker(context,
                      showTitleActions: true,
                      minTime: DateTime(2018, 3, 5),
                      maxTime: DateTime(2026, 6, 7), onChanged: (date) {
                    print('change $date');
                    setState(() {
                      pickeddate = "${date.day}";
                    });
                  }, onConfirm: (date) {
                    print('confirm $date');
                    setState(() {
                      pickeddate =
                          "Picked Date is : ${date.day}/${date.month}/${date.year}";
                    });
                  }, currentTime: DateTime.now(), locale: LocaleType.en);
                },
                label: Text("Set Date"),
                icon: Icon(Icons.date_range),
              ),
              SizedBox(
                height: 50,
              ),
              Container(
                child: (pickeddate == null)
                    ? Text("Select a date Please")
                    : Text("$pickeddate"),
              ),
              SizedBox(
                height: 30,
              ),
              Container(
                child: (pickedtime == null)
                    ? Text("Select a time Please")
                    : Text("$pickedtime"),
              ),
            ],
          ),
        ));
  }
}

Then you flutter app is ready with feature to pick date time in flutter app.

The easiest way to implement image picker in flutter using library example

0
image picker in flutter
image picker in flutter

Hi Guys, Welcome to Proto Coders Point, In this Flutter tutorial we gonna learn how to use the image picker flutter library a package that helps getimage/flutter pick images from a gallery or camera.

Image Picker flutter library

A Flutter Plugin library for both iOS and Android that is been used to pick an images from mobile phone gallery or even you can take a new photo with the camera.

let’s straight away start implement the flutter image picker in our flutter app.

find the latest version of Image picker from official site.

VIDEO TUTORIAL

Step 1: Adding image picker dependency flutter in to our flutter project

Once you have created a new Flutter project or open your existing flutter project to implement image picker flutter library.

Then you need to add image picker dependencies,

Open pubspec.yaml  then add the below lines

dependencies:
  image_picker: ^0.6.3+4 //add this line in pubspec.yaml file

Step 2: Import image_picker.dart file in main.dart

Now, as you have added the required library in your project now you need to import the picker library wherever required.

import 'package:image_picker/image_picker.dart';

For Example : In my case i have imported the library in main.dart file whcih is my main activity screen.

Step 3: Configuration

1. ANDROID IMAGE PICKER CONFIGURATION

When it comes to android their is no configuration required – the plugin should work out of the box.

Just we need to set request Legacy External Storage to true Android > app > src > main >AndroidManifest.xml

By adding the above request Legacy External Strorage the app will auto ask user to grant permission to make use of storage.

2. IOS IMAGE PICKER CONFIGURATION

Add the following keys to your Info.plist file, located in

Project > ios > Runner > Info.plist

adding flutter permission for ios devices in info.plist

Copy paste the below permission in info.plist

<key>NSPhotoLibraryUsageDescription</key>
<string>This app requires read and write permission Photo Library</string>

used to ask uses to give permission for accessing photo library. This is Called Privacy – Photo Library Usage Description.

<key>NSCameraUsageDescription</key>
<string>This app requires read and write permission from the user.</string>

Used to take photo from device camera itself.

<key>NSMicrophoneUsageDescription</key>
<string>This app requires get access to micro phone</string>

if you intend to record an video by using camera, video offcourse need audio to be recorded, this permission is used to record audio from microphone.

Step4 : Explaination of Image Picker snippet code

File _image; //here we gonna store our image.
var image = await ImagePicker.pickImage(source: ImageSource.gallery);
image picking from gallery

Then, Here we are using ImagePicker Class to pick images from ImageSource.

var image = await ImagePicker.pickImage(source: ImageSource.camera);

Here, ImageSource can either be camera or gallery.

image capture in flutter app

Camera is you want to click a image from device camera.

Gallery is you want to pick/select image from gallery of mobile phone.

Picked image from gallery in flutter app

Complete Code for image picker in flutter

main.dart

import 'dart:ffi';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.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> {
  File _image;

  Future getImagefromcamera() async {
    var image = await ImagePicker.pickImage(source: ImageSource.camera);

    setState(() {
      _image = image;
    });
  }

  Future getImagefromGallery() async {
    var image = await ImagePicker.pickImage(source: ImageSource.gallery);

    setState(() {
      _image = image;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Flutter Image Picker Example"),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Center(
            child: Text(
              "Image Picker Example in Flutter",
              style: TextStyle(fontSize: 20),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Container(
              width: MediaQuery.of(context).size.width,
              height: 200.0,
              child: Center(
                child: _image == null
                    ? Text("No Image is picked")
                    : Image.file(_image),
              ),
            ),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              FloatingActionButton(
                onPressed: getImagefromcamera,
                tooltip: "pickImage",
                child: Icon(Icons.add_a_photo),
              ),
              FloatingActionButton(
                onPressed: getImagefromGallery,
                tooltip: "Pick Image",
                child: Icon(Icons.camera_alt),
              )
            ],
          )
        ],
      ),
    );
  }
}

Here are some best Flutter Library that you can use in your flutter Project

Very useful Libraries in Flutter

Flutter image viewer : Is a simple photo View flutter library using which your app user will be easily able to zoom into the image.

Flutter time picker : A Flutter library that help you in adding date & time picker in your application.

Android Developer Image Libraries

Android Image Filter library : Image processing library is very easy to use as android image filter library.

Image Steps : Can you used as delivery progress indicator.

Flutter Image to base64 string or viceversa base64 to image: Here we have covered 3 example i.e convert image to base64 string, base64 to image, and pick image from gallery and convert it into base64 string.