Home Blog Page 84

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.

Mobile Number OTP Verification / SMS OTP verification in Android

0

Hi Guys, Welcome to Proto Coders Point, In this android tutorial we gonna integrate an app for OTP Verification in android.

For this, we gonna make use of the TextLocal SMS Service platform. I have already talked about TextLocal an India’s No 1 SMS service provider

Check out this Post Send SMS using text local an SMS GATEWAY – Android Studio Application

Let’s begin Integrating OTP Verification in our android application.

Mobile Number OTP Verification / SMS OTP verification in Android

Step 1: Creating a new account in textlocal.in or log in

go to textlocal.in create a new account or login with an old account if you have signup below with TextLocal.

After a Successful log In you will see a dashboard something like below

textlocal dashboard
textlocal dashboard

TextLocal provides you Free SMS Credit of 10, using which you can send up to 10 free SMS After you use all the Free SMS Credits you may need to  Buy their services for more SMS benefits. For App testing you can user textlocal otp generator.

Step 2: Creating a new API KEY in Text Local to send OTP

On your text local dashboard go to settings > API KEY.

Then Create a new API KEY

creating new api key in textlocal
creating new API key in textlocal

Note down the API key, because we then in our android application to send OTP to a mobile number via Text local.

Step 3: Creating a new Android Project

Now open  Android Studio as usual and create a new android application and name it as Android OTP Verification in android or anything your wish.

Step 4: Creating an OTP verification UI in android

 step1: create an XML file

under res > drawable > creating an XML file and name it as:

edittext_stroke_borders.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <corners android:radius="10dp" />
    <stroke
        android:width="1dp"
        android:color="@color/colorPrimary" />
</shape>

this above XML code will create a transparent border that we can use to show in EditText view as the background.

border stroke xml android

Step2: login page UI design

main activity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:gravity="center"
    android:orientation="vertical">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Welcome to Proto Coders Point"
        android:textColor="@android:color/black"
        android:textSize="20sp"
        android:layout_gravity="center"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Android Tutorial on OTP VERIFICATION"
        android:textColor="@android:color/black"
        android:textSize="20sp"
        android:layout_gravity="center"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Login "
        android:textColor="@android:color/black"
        android:textSize="30sp"
        android:layout_gravity="center"/>

    <EditText
        android:id="@+id/userphoneno"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:ems="10"
        android:layout_margin="10dp"
        android:padding="5dp"
        android:background="@drawable/edittext_stoke_borders"
        android:inputType="number"
        android:hint="Enter Your  Phone"
        tools:layout_editor_absoluteX="118dp"
        tools:layout_editor_absoluteY="76dp" />
    <Button
        android:id="@+id/getotp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textColor="@android:color/black"
        android:text="SignIN"
        android:layout_marginTop="10dp"
        android:layout_gravity="center"
        android:background="@color/colorAccent"/>


</LinearLayout>
otp verification ui android

Step 3: create a new activity

you need a new activity where we are going verify the OTP, for that you need to create an Activity with an XML file 

right-click on java > new > Activity > Empty Activity

Name it as OTP_Verification_Page

Then open the XML file of OTP Verification page and copy-paste below lines of XML UI code

activity_verify_otp.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Activity.GetOPT"
    android:orientation="vertical"
    android:layout_gravity="center"
    android:gravity="center">

    <Button
        android:id="@+id/get_otp_no"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="20dp"
        android:layout_marginTop="10dp"
        android:background="@color/colorPrimary"
        android:gravity="center"
        android:onClick="GetOTPNO"
        android:text="Get OTP Now"
        android:textColor="@android:color/white" />

    <EditText
        android:id="@+id/otpedittext"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:ems="10"
        android:layout_margin="10dp"
        android:padding="5dp"
        android:background="@drawable/edittext_stoke_borders"
        android:inputType="number"
        android:hint="......"
        android:letterSpacing="0.5"
        android:maxLength="6"
        android:gravity="center"
        tools:layout_editor_absoluteX="118dp"
        tools:layout_editor_absoluteY="76dp" />

    <Button
        android:id="@+id/verifyotp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="20dp"
        android:layout_marginTop="10dp"
        android:background="@color/colorAccent"
        android:gravity="center"
        android:onClick="verifyOTP"
        android:text="Verify"
        android:textColor="@android:color/black" />

</LinearLayout>
otp verification ui android

Step 4: create another Activity

like the same process as above create another Activity,

Here we gonna navigate the user if the OTP Verification mobile number was successful.

activity_successpage.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SuccessLoginIn"
    android:gravity="center">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="25sp"
        android:textColor="@android:color/black"
        android:text="OTP VERIFIED SUCCESSFULLY"/>

</LinearLayout>

Now we are done with OTP Verification UI android, Now let’s add some backend code in MainActivity.java, VerifyOTP.java, SuccessLogin.java.

Step 5: Adding Backend Java code

MainActivity.java

package com.ui.otpverfication;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    Button getotp;
    EditText userphoneno;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getotp=(Button)findViewById(R.id.getotp);
        userphoneno=(EditText)findViewById(R.id.userphoneno);

        getotp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(userphoneno.getText().toString().trim().isEmpty())
                {
                    userphoneno.setError("Enter Phone No");
                }else{
                    Intent i = new Intent(MainActivity.this, VerifyOTP.class);
                    i.putExtra("phone",userphoneno.getText().toString().trim());
                    startActivity(i);
                    finish();
                }

            }
        });
    }
}

Here we are simply passing mobile number entered by users via intent to VerifyOTP.java page.

VerifyOTP.java

package com.ui.otpverfication;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Random;

public class VerifyOTP extends AppCompatActivity {

    int randonnumber;
    String phonenumber;
    Button verifyotp,getVerifyotp;
    EditText otp_edittext;
    String otp_text;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_verify_otp);
        verifyotp=(Button)findViewById(R.id.verifyotp);
        getVerifyotp=(Button)findViewById(R.id.get_otp_no);
        otp_edittext=(EditText)findViewById(R.id.otpedittext);

        final StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);


        Intent intent=getIntent();
        phonenumber=intent.getStringExtra("phone");

        Toast.makeText(VerifyOTP.this, ""+phonenumber, Toast.LENGTH_SHORT).show();

    }

    void initialsendotp(){
        try {
            // Construct data
            String apiKey = "apikey=" + "ERJtdFbCOEk-5vvFn7mjg4SuywzHCcQkNxxxx(Replace with your API KEY)";

            Random random = new Random();
            randonnumber=random.nextInt(99999);
            String message = "&message=" + "Hey, Your OTP is " +randonnumber;
            String sender = "&sender=" + "TXTLCL";
            String numbers = "&numbers=" +phonenumber;

            // Send data
            HttpURLConnection conn = (HttpURLConnection) new URL("https://api.textlocal.in/send/?").openConnection();
            String data = apiKey + numbers + message + sender;
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Length", Integer.toString(data.length()));
            conn.getOutputStream().write(data.getBytes("UTF-8"));
            final BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            final StringBuffer stringBuffer = new StringBuffer();
            String line;
            while ((line = rd.readLine()) != null) {
                stringBuffer.append(line);
            }
            rd.close();
        } catch (Exception e) {
            System.out.println("Error SMS "+e);

        }
    }

    public  void GetOTPNO(View view)
    {
        initialsendotp();
        Toast.makeText(VerifyOTP.this,"OTP SENT< Please Wait you may recieved in a movement",Toast.LENGTH_LONG).show();
        getVerifyotp.setVisibility(View.GONE);
    }

    public void verifyOTP(View view) {
        Toast.makeText(VerifyOTP.this,"Verify Button",Toast.LENGTH_LONG).show();
        otp_text = otp_edittext.getText().toString().trim();

        if(otp_text.equals(String.valueOf(randonnumber)))
        {

            Toast.makeText(VerifyOTP.this,"user login in successfully",Toast.LENGTH_LONG).show();
            finish();
            Intent mainactivity = new Intent(VerifyOTP.this,SuccessLoginIn.class);

            startActivity(mainactivity);
        }
        else{
            Toast.makeText(VerifyOTP.this,"Invalid OTP, Please Try Again",Toast.LENGTH_LONG).show();

        }
    }
}

Here we have 2 buttons, one will send OTP to the registered mobile number and another button will simply verify the OTP entered by the user. and if the OTP entered by the user is correct the user will be navigated to the success page.

verify otp page

SuccessPage.java

package com.ui.otpverfication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

public class SuccessLoginIn extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_success_login_in);
    }
}

here we are simply setting the content view with the layout XML file.

otp verification success page

After all, Don’t forget to set <user-permission> INTERNET under AndroidManifest.xml

AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/> // need to make network calls

Recommended Android Articles

Reading incoming message automatically in android to verify otp

android sms gateway api

How to get Flutter device info with example

1

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we will learn how to get flutter device info such as device id, mobile device model.

Futter comes with a library that helps us to get mobile device information using its library plugin i’e DeviceInfoPlugin

Official Link to get Device Info Library

So let’s started in implementing this Library straight into our flutter project to get device info.

Flutter Device Info

how to get device information in flutter app development

Step1: Add Flutter Device_information dependencies

To get any mobile device information you need to add a dependencies under your flutter project in pubspec.yaml

open pubspec.yaml file

dependencies:
  device_info: ^0.4.1+5 // add this line

Library may get updated with new feature to get device model with more information so better visit official site to get latest version of the library.

Step 2: import the package device_info.dart

Then once you have added required dependencies to get the package into your project now  you will be able to use the device_info package by just importing the package.

import 'package:device_info/device_info.dart';

Step 3: instantiate the DeviceInfoPlugin

creating the object for Device Info

DeviceInfoPlugin deviceInfo = DeviceInfoPlugin(); // instantiate device info plugin

Step 4 : Creating object for individual OS such as android and iOS device

use it to get android and iOS getter to get Platform device information.

Creating object for AndroidDeviceInfo.

AndroidDeviceInfo androidDeviceInfo = await deviceInfo.androidInfo; // instantiate Android Device Information

Creating object for IosDeviceInfo.

IosDeviceInfo iosInfo = await deviceInfo.iosInfo; //to get information from ios device

Now you can user this object you have created to get devices information so use this like this.

androidDeviceInfo.model //this will return you device model name

then like this their are many other properties to get device information such as follow:

  • get Device brand
  • flutter Device hardware name
  • get device host name
  • Flutter get device id
  • Flutter get device model

Here is the images of different properties that can be used :

"different

Complete source code to get Flutter device info with example

Copy paste the below source code in main.dart file

main.dart

import 'package:flutter/material.dart';
import 'package:device_info/device_info.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> {
  DeviceInfoPlugin deviceInfo =
      DeviceInfoPlugin(); // instantiate device info plugin
  AndroidDeviceInfo androidDeviceInfo;
  
  String board, brand, device, hardware, host, id, manufacture, model, product, type, androidid;
  bool isphysicaldevice;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getDeviceinfo();
  }

  void getDeviceinfo() async {
    androidDeviceInfo = await deviceInfo
        .androidInfo; // instantiate Android Device Infoformation

    setState(() {
      board = androidDeviceInfo.board;
      brand = androidDeviceInfo.brand;
      device = androidDeviceInfo.device;

      hardware = androidDeviceInfo.hardware;
      host = androidDeviceInfo.host;
      id = androidDeviceInfo.id;
      manufacture = androidDeviceInfo.manufacturer;
      model = androidDeviceInfo.model;
      product = androidDeviceInfo.product;

      type = androidDeviceInfo.type;
      isphysicaldevice = androidDeviceInfo.isPhysicalDevice;
      androidid = androidDeviceInfo.androidId;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Get Device Info in Flutter"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(12.0),
        child: Column(
          children: <Widget>[
            Center(
              child: Text(
                "Welcome to Proto Coders Point",
                style: TextStyle(
                    fontWeight: FontWeight.w700,
                    fontSize: 25,
                    color: Colors.red),
              ),
            ),
            Text(
              "YOUR DEVICE INFORMATION",
              style: TextStyle(fontSize: 15, fontWeight: FontWeight.bold),
            ),
            SizedBox(
              height: 10,
            ),
            Text(
              "Board   : $board",
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(
              height: 10,
            ),
            Text(
              "Brand   : $brand",
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(
              height: 10,
            ),
            Text(
              "Device   : $device",
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(
              height: 10,
            ),
            Text(
              "Hardware  :  $hardware ",
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(
              height: 10,
            ),
            Text(
              "Host  : $host",
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(
              height: 10,
            ),
            Text(
              "ID   : $id",
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(
              height: 10,
            ),
            Text(
              "Manufacture  : $manufacture",
              style: TextStyle(fontSize: 20),
            ),
            Text(
              "Model  : $model",
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(
              height: 10,
            ),
            Text(
              "Product  :  $product",
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(
              height: 10,
            ),
            Text(
              "Type   : $type",
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(
              height: 10,
            ),
            Text(
              "Is Physical Device : $isphysicaldevice",
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(
              height: 10,
            ),
            Text(
              " Android ID: $androidid ",
              style: TextStyle(fontSize: 20),
            ),
          ],
        ),
      ),
    );
  }
}

Image slider in flutter using Carousel Pro Flutter Library

2

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we will implement Image Slider flutter using Carousel Pro  a image Slider widget library for Flutter.

DEMO

Image slider flutter using Carousel Pro

How to make Image Slider in flutter?

To show an Sliding image in flutter you need to add a library called Carousel Pro using which you can easily add image slider widget in your project, to do so follow below steps.

Step 1: Add Image Slider( carousel pro ) dependencies in your project

Open pubspec.yaml file and add the following depencencies.

dependencies:
  carousel_pro: ^1.0.0 // add this line

how to make image slider in flutter
Adding dependencies

Library may come with latest feature in future so better visit official site to know about the latest version.

Step 2: Importing the carousel pro package

Then once you have added the required library depencencies in you flutter project now you can make use of the library just by importing the package of carousel pro package wherever required.

import 'package:carousel_pro/carousel_pro.dart';

Step 3: Snipped code of image slider flutter example

Carousel(
       images: [
         AssetImage('assets/image1.jpg'),
         NetworkImage(
             'imageurl'),
         AssetImage("assets/image2.jpg"),
         NetworkImage(
             "https://image.shutterstock.com/image-photo/micro-peacock-feather-hd-imagebest-260nw-1127238584.jpg"),
         AssetImage("assets/image3.jpeg"),
         NetworkImage(
             'https://i.pinimg.com/originals/94/dd/57/94dd573e4b4de604ea7f33548da99fd6.jpg'),
       ],
     )

Then to show image slider we can make use of carousel widget that has a images[] properties where you can show any number of slidling images into the widget.

In the above snipped example i have make use of NetworkImage() widget to show images from internet, and AssetImage() to show images that are locally stored in Flutter project.

How to add assets and images in flutter Project

then to add image or assets under you flutter project you need to create a directory and name it as anything(in my case it assets).

Right click on your flutter project > New > Directory

creating assets folder in flutter

give a name to you directory and there you go.

creating image assets directory in flutter

once assets directory is ready now you  specify the assets directory in pubspec.yaml file so that our flutter project can easily get to know where assets image are been loacted

pubspec image assets adding

Now once you have added the path then you can add some images into assets folder to use then in your dart code.

Let’s come back to our main motive about this project to show image slider in flutter app.

Properties of Carousel Pro Flutter image slider library

dotSize: 4.0

dotSpacing: 15.0

dotColor: Colors.lightGreenAccent

dotIncreaseSize:2.0

dotColor: Colors.red

Here are list of the properties you can customize in Carousel Pro widget

Carousel pro image slider properties list

Complete Code of Image Carousel slider in flutter using Carousel Pro Library

Just Copy paste the below code in main.dart file and here you go flutter app is ready with carousel image slider

main.dart

import 'package:flutter/material.dart';
import 'package:carousel_pro/carousel_pro.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(
      backgroundColor: Colors.black45,
      appBar: AppBar(
        title: Text("Image Slider in FLutter "),
      ),
      body: Center(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(15.0),
              child: Text(
                "Image Slider Example in Flutter using Carousel_Pro Library",
                style: TextStyle(
                    color: Colors.blue,
                    fontSize: 25.0,
                    letterSpacing: 2,
                    fontStyle: FontStyle.italic,
                    fontWeight: FontWeight.bold),
              ),
            ),
            SizedBox(
                height: 300.0,
                width: double.infinity,
                child: Carousel(
                  images: [
                    AssetImage('assets/image1.jpg'),
                    NetworkImage(
                        'https://lh3.googleusercontent.com/proxy/BUNdJ4Jn2u00bBtQ_qNRLUoSGaaHsBqQzSsGnd3lRwQm6GSU8IAGlpAnRL5SWy1bx27ZZoSuOPUKA3Etyg1ND4PPO24fj5Y6a9IRHACrkbbMNf9k8fCnr3aOQJ_iWoEHcF4nwrCUDnzhKbywlPgXYamSdQ'),
                    AssetImage("assets/image2.jpg"),
                    NetworkImage(
                        "https://image.shutterstock.com/image-photo/micro-peacock-feather-hd-imagebest-260nw-1127238584.jpg"),
                    AssetImage("assets/image3.jpeg"),
                    NetworkImage(
                        'https://i.pinimg.com/originals/94/dd/57/94dd573e4b4de604ea7f33548da99fd6.jpg'),
                  ],
                  dotColor: Colors.red,
                )),
          ],
        ),
      ),
    );
  }
}

 

Shared Preferences in Flutter – shared preferences to keep user logged?

3
Shared Preferences in Flutter - shared preferences to keep user logged

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we will learn how to use shared preferences in Flutter Application Development to keep users logged In.

In this example we gonna make use of flutter shared Preferences library, to keep logged in users data.

Brief about Shared Preferences?

In mobile app development their are many ways to shore data of an application. One of the way to shore data in mobile device itself is by making use of Shared Preferences.

It allows you to save and retrieve data in a form of key,value pair.

Video Tutorial

so Let’s begin adding and implementing Shared Preferences in Flutter with example of keeping users logged in.

In order to use this library, you need to first add the package in your flutter project to do so follow below 2 steps

Step 1 : Adding SharedPreferences Dependencies code

Visit the official website to get latest version of this library here

dependencies:
  shared_preferences: ^0.5.6+2 //add this line

Under you Flutter Project open pubspec.yaml file and add the dependences as show in below image.

adding shared preferences flutter dependences library

Step 2: Import the Flutter Shared Preferences package

Now, once you have added the dependencies in your flutter project now you can make use of the package through out your project just by importing the package.

How to import SharedPreferences ?

import 'package:shared_preferences/shared_preferences.dart';

Open dart file where you want to use shared Preferences to store and retrieve data, in my case it main.dart.

Note : This plugin must be used only to hold small data, in other words this plugin should not be used to store any kind of critical data.

In order to use shared preferences, you have to call a method getSharedPreferences() that returns a SharedPreference instance pointing to the file that contains the values of preferences.

You need to call  a method SharedPreferences.getInstance and create a dart object names prefsdata.

SharedPreferences prefsdata = await SharedPreferences.getInstance();

Then, you can make use of this object ( prefsdata ) to store and retrieve data from sharedpreferences database.

How to store data in shared Preferences in flutter?

logindata.setString('username', username);

Here ‘username’ is a key and username is a value.

shared preferences key value example

How to retrieve data from shared Preferences?

String user = logindata.getString('username');

In the above snippet code ‘username’ is the key that holds the value.

Shared Preferences in Flutter – shared preferences to keep user logged?

In this Flutter tutorial for shared Preferences example i am going to create a simple login form note : without any backend database ( it’s just a dummy project )

for this project you need two dart pages. First to display login page (main.dart), Second to show successfully logged in user data ( mainpage.dart )

main.dart

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'mainpage.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: MyLoginPage(),
    );
  }
}

class MyLoginPage extends StatefulWidget {
  @override
  _MyLoginPageState createState() => _MyLoginPageState();
}

class _MyLoginPageState extends State<MyLoginPage> {
  // Create a text controller and use it to retrieve the current value
  // of the TextField.
  final username_controller = TextEditingController();
  final password_controller = TextEditingController();

  SharedPreferences logindata;
  bool newuser;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    check_if_already_login();
  }

  void check_if_already_login() async {
    logindata = await SharedPreferences.getInstance();
    newuser = (logindata.getBool('login') ?? true);

    print(newuser);
    if (newuser == false) {
      Navigator.pushReplacement(
          context, new MaterialPageRoute(builder: (context) => MyDashboard()));
    }
  }

  @override
  void dispose() {
    // Clean up the controller when the widget is disposed.
    username_controller.dispose();
    password_controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(" Shared Preferences"),
      ),
      body: Center(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Text(
              "Login Form",
              style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
            ),
            Text(
              "To show Example of Shared Preferences",
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ),
            Padding(
              padding: const EdgeInsets.all(15.0),
              child: TextField(
                controller: username_controller,
                decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  labelText: 'username',
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(15.0),
              child: TextField(
                controller: password_controller,
                decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  labelText: 'Password',
                ),
              ),
            ),
            RaisedButton(
              textColor: Colors.white,
              color: Colors.blue,
              onPressed: () {
                String username = username_controller.text;
                String password = password_controller.text;

                if (username != '' && password != '') {
                  print('Successfull');
                  logindata.setBool('login', false);

                  logindata.setString('username', username);

                  Navigator.push(context,
                      MaterialPageRoute(builder: (context) => MyDashboard()));
                }
              },
              child: Text("Log-In"),
            )
          ],
        ),
      ),
    );
  }
}

The above dart code will result UI something like below screenshot

Login screen for shared preferences example

mainPage.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttersharedpreferences/main.dart';
import 'package:shared_preferences/shared_preferences.dart';

class MainPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyDashboard(),
    );
  }
}

class MyDashboard extends StatefulWidget {
  @override
  _MyDashboardState createState() => _MyDashboardState();
}

class _MyDashboardState extends State<MyDashboard> {
  SharedPreferences logindata;
  String username;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    initial();
  }

  void initial() async {
    logindata = await SharedPreferences.getInstance();
    setState(() {
      username = logindata.getString('username');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Shared Preference Example"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(26.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Center(
              child: Text(
                'WELCOME TO PROTO CODERS POINT  $username',
                style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
              ),
            ),
            RaisedButton(
              onPressed: () {
                logindata.setBool('login', true);
                Navigator.pushReplacement(context,
                    new MaterialPageRoute(builder: (context) => MyLoginPage()));
              },
              child: Text('LogOut'),
            )
          ],
        ),
      ),
    );
  }
}

Result

logged in user welcome screen with retrived data from shared preferences-min

 

Flutter Splash Screen Example with Loading Animation using Spinkit library

1
Flutter Splash Screen Example with Loading Animation using Spinkit library

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we will implement Flutter Splash Screen and showing a loading effect using Flutter Spinkit.

What is Splash Screen?

In any Mobile or Web Application a Splash Screen is the first screen that is visible to the user when it app is been launched… Usually Splash Screen are used to show company logo and then launch the main screen of the application after some time.

There are many way to show a flutter splash screen. In this Flutter Tutorial we gonna learn the simplest way to show the Splash Screen using Timer class.

DEMO

Futter Splash Screen Example

Video Tutorial

So let’s begin implementing this in Flutter project without wasting any time.

Brief about Flutter Spinkit Library

The Flutter Spinkit package library is a collection of pre – animated loading indicator in flutter app development.

This Spinkit package library is been pre-animated with loading effect you just need to use those class wherever required.

How to add Flutter Spinkit package library?

Step 1: Add Spinkit dependencies in Pubspex.yaml file

To make use of spinkit library to show loading animation effect you need to add the library in your project.

dependencies:
  flutter_spinkit: ^4.1.2 // add this line

Step 2: Import the dart class where required

Then you need to import dart code in main.dart file to use the Spinkit library.

import 'package:flutter_spinkit/flutter_spinkit.dart';

Step 3 : Use the Spinkit widgets

SpinKitRotatingCircle(
  color: Colors.white,
  size: 50.0,
);

There are many type of spinkit widget.

Here are the list of all the spinkit loading widget that you can easily use to show loading effect. Experiment them one by one and select any one.

SpinKitRotatingCircle(color: Colors.white)

SpinKitRotatingPlain(color: Colors.white)

SpinKitChasingDots(color: Colors.white)

SpinKitPumpingHeart(color: Colors.white)

SpinKitPulse(color: Colors.white)

SpinKitDoubleBounce(color: Colors.white)

SpinKitWave(color: Colors.white, type: SpinKitWaveType.start)

SpinKitWave(color: Colors.white, type: SpinKitWaveType.center)

SpinKitWave(color: Colors.white, type: SpinKitWaveType.end)

SpinKitThreeBounce(color: Colors.white)

SpinKitWanderingCubes(color: Colors.white)

SpinKitWanderingCubes(color: Colors.white, shape: BoxShape.circle)

SpinKitCircle(color: Colors.white)

SpinKitFadingFour(color: Colors.white)

SpinKitFadingFour(color: Colors.white, shape: BoxShape.rectangle)

SpinKitFadingCube(color: Colors.white)

SpinKitCubeGrid(size: 51.0, color: Colors.white)

SpinKitFoldingCube(color: Colors.white)

SpinKitRing(color: Colors.white)

SpinKitDualRing(color: Colors.white)

SpinKitRipple(color: Colors.white)

SpinKitFadingGrid(color: Colors.white)

SpinKitFadingGrid(color: Colors.white, shape: BoxShape.rectangle)

SpinKitHourGlass(color: Colors.white)

SpinKitSpinningCircle(color: Colors.white)

SpinKitSpinningCircle(color: Colors.white, shape: BoxShape.rectangle)

SpinKitFadingCircle(color: Colors.white)

SpinKitPouringHourglass(color: Colors.white)

Flutter Splash Screen Example with Loading Animation using Spinkit library

In this Flutter Tutorial we gonna make use of Timer() which loads page2 after 5 second.

To do so you need two Flutter dart pages, I have create 2 dart pages namely main.dart and HomePage.dart

Creating a dart page

To create a new dart file lib (right click) > New >  Dart File

creating new dart file in flutter
creating new dart file in flutter

Then i have named it HomePage.dart

My Project Structure

Flutter project structure

Snippet Code of Timer() in main.dart file

@override
  void initState() {
    // TODO: implement initState
    super.initState();

    Timer(
      Duration(seconds: 5),
      () => Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => HomePage()),
      ),
    );
  }

Here i will be waiting in main.dart file for 5 second to show Flutter loading Spinkit then after 5 second i will navigate from main.dart page —>  HomePage.dart this will work like a Flutter Splash Screen.

Complete Code Flutter Splash Screen with Spinkit library.

main.dart

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

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:flutterspinkit/Home_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
  void initState() {
    // TODO: implement initState
    super.initState();

    Timer(
      Duration(seconds: 5),
      () => Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => HomePage()),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Stack(
      fit: StackFit.expand,
      children: <Widget>[
        Container(
          decoration: BoxDecoration(color: Colors.redAccent),
        ),
        Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              "   Loading....",
              style: TextStyle(
                  color: Colors.white,
                  fontSize: 20,
                  fontWeight: FontWeight.bold),
            ),
            SizedBox(
              height: 25,
            ),
            SpinKitWave(
              itemBuilder: (BuildContext context, int index) {
                return DecoratedBox(
                  decoration: BoxDecoration(
                    color: index.isEven ? Colors.white : Colors.green,
                  ),
                );
              },
            ),
          ],
        ),
      ],
    ));
  }
}

The above code will simply show a loading indicator for 5 seconds and then load the new page.

HomePage.dart

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

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Flutter Tutorial"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
                " This is an Example for Splash Screen and Loading Spin Kit Library")
          ],
        ),
      ),
    );
  }
}

This HomePage has simple text at the center of the screen.