https://flutterdevs.com Hire Flutter Developer – Flutter App Development Company Tue, 27 Jul 2021 06:04:36 +0000 en-US hourly 1 https://wordpress.org/?v=5.9.3 https://flutterdevs.com/wp-content/uploads/2020/05/cropped-favicon-32x32.png https://flutterdevs.com 32 32 Staggered GridView In Flutter https://flutterdevs.com/uncategorized/staggered-gridview-in-flutter/ https://flutterdevs.com/uncategorized/staggered-gridview-in-flutter/#respond Wed, 30 Dec 2020 06:46:24 +0000 https://flutterdevs.com/?p=13995

flutter_staggered_grid_view | Flutter Package

A Flutter staggered grid view which supports multiple columns with rows of varying sizes. Configurable cross-axis count…

pub.dev

Flutter:

Introducing Flutter

Flutter – Beautiful native apps in record time

Paint your app to life in milliseconds with Stateful Hot Reload. Use a rich set of fully-customizable widgets to build…

flutter. dev

Staggered GridView:

Normal GridView
Image for post

Image for post

Demo Output

Features:

Implementation:

flutter_staggered_grid_view: ^0.3.3
transparent_image: ^1.0.0
import 'package:transparent_image/transparent_image.dart';
import'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
org.gradle.jvmargs=-Xmx1536M
android.enableR8=true
android.useAndroidX=true
android.enableJetifier=true

How to implement code in dart file :

List<String> imageList = [
  'https://cdn.pixabay.com/photo/2019/03/15/09/49/girl-4056684_960_720.jpg',
  'https://cdn.pixabay.com/photo/2020/12/15/16/25/clock-5834193__340.jpg',
  'https://cdn.pixabay.com/photo/2020/09/18/19/31/laptop-5582775_960_720.jpg',
  'https://media.istockphoto.com/photos/woman-kayaking-in-fjord-in-norway-picture-id1059380230?b=1&k=6&m=1059380230&s=170667a&w=0&h=kA_A_XrhZJjw2bo5jIJ7089-VktFK0h0I4OWDqaac0c=',
  'https://cdn.pixabay.com/photo/2019/11/05/00/53/cellular-4602489_960_720.jpg',
  'https://cdn.pixabay.com/photo/2017/02/12/10/29/christmas-2059698_960_720.jpg',
  'https://cdn.pixabay.com/photo/2020/01/29/17/09/snowboard-4803050_960_720.jpg',
  'https://cdn.pixabay.com/photo/2020/02/06/20/01/university-library-4825366_960_720.jpg',
  'https://cdn.pixabay.com/photo/2020/11/22/17/28/cat-5767334_960_720.jpg',
  'https://cdn.pixabay.com/photo/2020/12/13/16/22/snow-5828736_960_720.jpg',
  'https://cdn.pixabay.com/photo/2020/12/09/09/27/women-5816861_960_720.jpg',
];
StaggeredGridView.countBuilder(
    crossAxisCount: 2,
    crossAxisSpacing: 10,
    mainAxisSpacing: 12,
    itemCount: imageList.length,
    itemBuilder: (context, index) {
    },
   ),
itemBuilder: (context, index) {
  return Container(
    decoration: BoxDecoration(
        color: Colors.transparent,
        borderRadius: BorderRadius.all(
            Radius.circular(15))
    ),
    child: ClipRRect(
      borderRadius: BorderRadius.all(
          Radius.circular(15)),
      child: FadeInImage.memoryNetwork(
        placeholder: kTransparentImage,
        image: imageList[index],fit: BoxFit.cover,
      ),
    ),
  );
},

transparent_image | Dart Package

A simple, transparent image. Represented as a Uint8List, which was originally extracted from the Flutter codebase (was…

pub.dev

staggeredTileBuilder: (index) {
  return StaggeredTile.count(1, index.isEven ? 1.2 : 1.8);
}
Image for post

Image for post

Final Output

Code File:

import 'package:flutter/material.dart';
import 'package:transparent_image/transparent_image.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';

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

class _MyHomePageState extends State<MyHomePage> {
  List<String> imageList = [
    'https://cdn.pixabay.com/photo/2019/03/15/09/49/girl-4056684_960_720.jpg',
    'https://cdn.pixabay.com/photo/2020/12/15/16/25/clock-5834193__340.jpg',
    'https://cdn.pixabay.com/photo/2020/09/18/19/31/laptop-5582775_960_720.jpg',
    'https://media.istockphoto.com/photos/woman-kayaking-in-fjord-in-norway-picture-id1059380230?b=1&k=6&m=1059380230&s=170667a&w=0&h=kA_A_XrhZJjw2bo5jIJ7089-VktFK0h0I4OWDqaac0c=',
    'https://cdn.pixabay.com/photo/2019/11/05/00/53/cellular-4602489_960_720.jpg',
    'https://cdn.pixabay.com/photo/2017/02/12/10/29/christmas-2059698_960_720.jpg',
    'https://cdn.pixabay.com/photo/2020/01/29/17/09/snowboard-4803050_960_720.jpg',
    'https://cdn.pixabay.com/photo/2020/02/06/20/01/university-library-4825366_960_720.jpg',
    'https://cdn.pixabay.com/photo/2020/11/22/17/28/cat-5767334_960_720.jpg',
    'https://cdn.pixabay.com/photo/2020/12/13/16/22/snow-5828736_960_720.jpg',
    'https://cdn.pixabay.com/photo/2020/12/09/09/27/women-5816861_960_720.jpg',
  ];

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        backgroundColor: Colors.white24,
        appBar: AppBar(
          title: Text("Flutter Staggered GridView Demo"),
          centerTitle: true,
          automaticallyImplyLeading: false,
        ),
        body: Container(
          margin: EdgeInsets.all(12),
          child:  StaggeredGridView.countBuilder(
              crossAxisCount: 2,
              crossAxisSpacing: 10,
              mainAxisSpacing: 12,
              itemCount: imageList.length,
              itemBuilder: (context, index) {
                return Container(
                  decoration: BoxDecoration(
                      color: Colors.transparent,
                      borderRadius: BorderRadius.all(
                          Radius.circular(15))
                  ),
                  child: ClipRRect(
                    borderRadius: BorderRadius.all(
                        Radius.circular(15)),
                    child: FadeInImage.memoryNetwork(
                      placeholder: kTransparentImage,
                      image: imageList[index],fit: BoxFit.cover,),
                  ),
                );
              },
              staggeredTileBuilder: (index) {
                return StaggeredTile.count(1, index.isEven ? 1.2 : 1.8);
              }),
        ),
      ),
    );
  }
}

Conclusion :

]]>
https://flutterdevs.com/uncategorized/staggered-gridview-in-flutter/feed/ 0
Video Calling In Flutter https://flutterdevs.com/blog/video-calling-in-flutter/ https://flutterdevs.com/blog/video-calling-in-flutter/#respond Wed, 30 Dec 2020 06:42:16 +0000 https://flutterdevs.com/?p=13991

agora_rtc_engine | Flutter Package

中文 This Flutter plugin is a wrapper for Agora Video SDK. Agora.io provides building blocks for you to add real-time…

pub. dev

Table Of Contents::

Introduction:

Demo Module ::

Image for post

Image for post

Demo Screens

Setup:

Image for post

Image for post

Image for post

Image for post

Image for post

Image for post

Implementation:

agora_rtc_engine: ^3.1.3
permission_handler: ^5.0.1
import 'package:agora_rtc_engine/rtc_engine.dart';
import 'package:permission_handler/permission_handler.dart';
org.gradle.jvmargs=-Xmx1536M
android.enableR8=true
android.useAndroidX=true
android.enableJetifier=true

Device Permission:

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<!-- The Agora SDK requires Bluetooth permissions in case users are using Bluetooth devices.-->
<uses-permission android:name="android.permission.BLUETOOTH" />

How to implement code in dart file :

const APP_ID = Your App_ID
const Token = Your Token
Row(
  children: <Widget>[
    Expanded(
        child: TextField(
      controller: _channelController,
      decoration: InputDecoration(
        errorText:
            _validateError ? 'Channel name is mandatory' : null,
        border: UnderlineInputBorder(
          borderSide: BorderSide(width: 1),
        ),
        hintText: 'Channel name',
      ),
    ))
  ],
),
Padding(
  padding: const EdgeInsets.symmetric(vertical: 20),
  child: Row(
    children: <Widget>[
      Expanded(
        child: RaisedButton(
          onPressed: onJoin,
          child: Text('Join'),
          color: Colors.blueAccent,
          textColor: Colors.white,
        ),
      )
    ],
  ),
)
Future<void> onJoin() async {
  setState(() {
    _channelController.text.isEmpty
        ? _validateError = true
        : _validateError = false;
  });
  if (_channelController.text.isNotEmpty) {
    await _handleCameraAndMic(Permission.camera);
    await _handleCameraAndMic(Permission.microphone);
    await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => VideoCall(
          channelName: _channelController.text,
          role: _role,
        ),
      ),
    );
  }
}
Image for post

Image for post

Final Output

Code File:

Conclusion:

]]>
https://flutterdevs.com/blog/video-calling-in-flutter/feed/ 0
Share Data To Another Application In Flutter https://flutterdevs.com/blog/share-data-to-another-application-in-flutter/ https://flutterdevs.com/blog/share-data-to-another-application-in-flutter/#respond Wed, 30 Dec 2020 06:36:28 +0000 https://flutterdevs.com/?p=13987

share | Flutter Package

A Flutter plugin to share content from your Flutter app via the platform’s share dialog. Wraps the ACTION_SEND Intent…

pub. dev

Table Of Contents::

Share Data

Demo module ::

Image for post

Image for post

Demo Module

Implementation :

share: ^0.6.5+4
image_picker:
import 'package:image_picker/image_picker.dart';
import 'package:share/share.dart';
org.gradle.jvmargs=-Xmx1536M
android.enableR8=true
android.useAndroidX=true
android.enableJetifier=true

How to implement code in dart file :

Image for post

Image for post

Share Data With Fields
TextField(
  decoration: const InputDecoration(
    labelText: 'Share text:',
    labelStyle: TextStyle(color: Colors.blue),
    hintText: 'Enter some text and/or link to share',
  ),
  maxLines: 2,
  onChanged: (String value) => setState(() {
    text = value;
  }),
),
TextField(
  decoration: const InputDecoration(
    labelText: 'Share subject:',
    labelStyle: TextStyle(color: Colors.blue),

    hintText: 'Enter subject to share (optional)',
  ),
  maxLines: 2,
  onChanged: (String value) => setState(() {
    subject = value;
  }),
),
String text = '';
String subject = '';
Builder(
  builder: (BuildContext context) {
    return RaisedButton(
      color: Colors.orangeAccent[100],
      child: const Text('Share'),
      onPressed: text.isEmpty
          ? null
          : () => _onShareData(context),
    );
  },
),
_onShareData(BuildContext context) async {

  final RenderBox box = context.findRenderObject();
 {
    await Share.share(text,
        subject: subject,
        sharePositionOrigin: box.localToGlobal(Offset.zero) & box.size);
  }
}
Image for post

Image for post

Final Output
Image for post

Image for post

Share Data With Empty Fields

We will make a button and onPressed method called _onShareWithEmptyFields() widget on this button.

Builder(
  builder: (BuildContext context) {
    return RaisedButton(
      color: Colors.orangeAccent[100],
      child: const Text('Share With Empty Fields'),
      onPressed: () => _onShareWithEmptyFields(context),
    );
  },
),
_onShareWithEmptyFields(BuildContext context) async {
  await Share.share("text");
}
Image for post

Image for post

Final Output
Image for post

Image for post

Share Image Inside Our Gallery
ListTile(
  leading: Icon(Icons.add),
  title: Text("Add image"),
  onTap: () async {
    final imagePicker = ImagePicker();
    final pickedFile = await imagePicker.getImage(
      source: ImageSource.gallery,
    );
    if (pickedFile != null) {
      setState(() {
        imagePaths.add(pickedFile.path);
      });
    }
  },
),
String pickedFile = imagePaths ==null?"":imagePaths.toString();
String trimmedFileName = pickedFile.split("/").last;
Builder(
  builder: (BuildContext context) {
    return RaisedButton(
      color: Colors.orangeAccent[100],
      child: const Text('Share'),
      onPressed: text.isEmpty && imagePaths.isEmpty
          ? null
          : () => _onShareData(context),
    );
  },
),
_onShareData(BuildContext context) async {

  final RenderBox box = context.findRenderObject();

  if (imagePaths.isNotEmpty) {
    await Share.shareFiles(imagePaths,
        text: text,
        subject: subject,
        sharePositionOrigin: box.localToGlobal(Offset.zero) & box.size);
  } else {
    await Share.share(text,
        subject: subject,
        sharePositionOrigin: box.localToGlobal(Offset.zero) & box.size);
  }
}
Image for post

Image for post

Final Output

Code File

Conclusion:

]]>
https://flutterdevs.com/blog/share-data-to-another-application-in-flutter/feed/ 0
SwitchListTile Widget In Flutter https://flutterdevs.com/blog/switchlisttile-widget-in-flutter/ https://flutterdevs.com/blog/switchlisttile-widget-in-flutter/#respond Tue, 15 Dec 2020 09:53:21 +0000 https://flutterdevs.com/?p=13879

Flutter, to build any application, we start with widgets. The structure block of flutter applications. Widgets depict what their view ought to resemble given their present setup and state. It incorporates a text widget, row widget, column widget, container widget, and some more.

Every component on a screen of the Flutter application is a widget. The screen’s perspective totally relies on the widgets’ decision and sequence used to build the application. What’s more, the structure of the code of an application is a tree of widgets.

In this article, we will explore SwitchListTile Widget In Flutter. We will also implement a demo program, describe properties, and use them in your flutter applications.

Table Of Contents::

Flutter

SwitchListTile

Properties

Code Implementation

Code File

Conclusion



Flutter :

Flutter is Google’s UI toolkit that helps you build beautiful and natively combined applications for mobile, web, and desktop in a single codebase in record time.

To begin with, you’ll need the necessary information on Flutter, Git, and GitHub. If you are new to flutter, you can get started by reading the official documentation on flutter. Dev.

SwitchListTile :

A ListTile with a Switch. At the end of the day, a switch with a mark. It is likewise a Widget that has no capacity state. Need to control the state through stateful parent widgets.

Demo Video

OnChanged is considered when the condition of the Switch changes. The callback boundary is bool, and the genuine methods it is chosen. False methods are unchecked. Value property Indicates if to empower, control the condition of the Switch by controlling this. We can click and can slide too.

Properties :

The following are the basic properties of the SwitchListTile:

  • > value: In this property to initialize whether this Switch is selected. True means checked, false means unchecked.
  • > onChanged: In this property, when dragging, the callback changes state /when opening and closing.
  • > activeColor: In this property, the background color of the button when the value is true. Then, the color was changed.
  • > activeTrackColor: In this property, when selected, the color of the slide was changed.
  • > activeThumbImage: In this property, the picture of the slider when selected.
  • > inactiveThumbImage: In this property, the picture of the slider when unchecked.
  • > title: In this property, title Typical is Text.
  • > subtitle: In this property, subtitles Below the title is typically Text.
  • > inactiveThumbImage: In this property, the image on the slider when the value is false. If inactiveThumbColor is also set, the inactiveThumbImage will prevail.
  • > secondary: In this property, one thing on the left side.

How to implement code in dart file :

You need to implement it in your code respectively:

Create a new dart file called switch_list_tile_demo.dart inside the lib folder.

SwitchListTile only title set

In this switchListTile, we will use only the title and the title can take any widget, but it is generally going to be a Text widget.

Card(
  color: Colors.white,
  child: SwitchListTile(
    title: Text('Flutter Devs',style: TextStyle(
        color: Colors.blue,
        fontWeight: FontWeight.w800,
        fontSize: 20
    ),
    ),
    value: _flutter,
    activeColor: Colors.red,
    inactiveTrackColor: Colors.grey,
    onChanged: (bool value) {
      setState(() {
        _flutter = value;
      });
    },
  ),
),

We will wrap SwitchListTil() on the Card widget, add active color was red, inactive track color was grey. We will make a bool variable and call it on value and onChanged method.

bool _flutter = false;
SwitchListTile adds image and subtitle.

We will add an image and subtitle; the image will be shown in the leading position, and subtitles will show smaller text below the title.

Card(
  color: Colors.white,
  child: SwitchListTile(
    title: Text('Flutter Devs',style: TextStyle(
        color: Colors.blue,
        fontWeight: FontWeight.w800,
        fontSize: 20
    ),
    ),
    value: _flutter,
    activeColor: Colors.red,
    inactiveTrackColor: Colors.grey,
    onChanged: (bool value) {
      setState(() {
        _flutter = value;
      });
    },
    secondary: Image.asset("assets/devs.jpg",),
    subtitle: Text('Software Company',style: TextStyle(
      color: Colors.blueGrey[600],
    ),
    ),
  ),
),

We will add an image on the secondary method, then run the code image on your devices.

SwitchListTile slider position

We will change the slider positioned on the contolAffinity method. In this method, you will be set your slider positioned.

controlAffinity: ListTileControlAffinity.leading,

When we run the application, we ought to get the screen’s output like the underneath screen video.

Output Video

This video shows how to create a SwitchLisTtile in a flutter and shows how SwitchLisTile will work in your flutter applications using properties, and then they will be shown on your device.

Code File :

import 'package:flutter/material.dart';


class SwitchListTileDemo extends StatefulWidget {
  @override
  _SwitchListTileDemoState createState() => _SwitchListTileDemoState();
}

class _SwitchListTileDemoState extends State<SwitchListTileDemo> {

  bool _flutter = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white24,
      appBar: AppBar(
        title: Text('Flutter SwitchListTile Demo'),
        centerTitle: true,
        automaticallyImplyLeading: false,
      ),
      body: Center(
        child: Card(
          color: Colors.white,
          child: SwitchListTile(
            title: Text('Flutter Devs',style: TextStyle(
                color: Colors.blue,
                fontWeight: FontWeight.w800,
                fontSize: 20
            ),
            ),
            value: _flutter,
            activeColor: Colors.red,
            inactiveTrackColor: Colors.grey,
            onChanged: (bool value) {
              setState(() {
                _flutter = value;
              });
            },
            secondary: Image.asset("assets/devs.jpg",),
            subtitle: Text('Software Company',style: TextStyle(
              color: Colors.blueGrey[600],
            ),
            ),
            controlAffinity: ListTileControlAffinity.trailing,
          ),
        ),
      ),
    );
  }
}

Conclusion :

In the article, I have explained the SwitchListTile widget in a flutter; you can modify this code according to your choice. This was a small introduction to SwitchListTile On User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information in Trying up the SwitchListTile widget in your flutter projects. We will show you what is SwitchListTile, some property using in SwitchListTile, and make a demo program for working SwitchListTile in your flutter applications, So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap ? If this article helps you.

find the source code of the Flutter SwitchListTile Demo:

]]>
https://flutterdevs.com/blog/switchlisttile-widget-in-flutter/feed/ 0
How to create Splash Screens in Flutter https://flutterdevs.com/uncategorized/how-to-create-splash-screens-in-flutter/ https://flutterdevs.com/uncategorized/how-to-create-splash-screens-in-flutter/#respond Mon, 12 Oct 2020 19:23:46 +0000 https://flutterdevs.com/?p=13602 Flutter Splash Demo was created to understand how we can create different types of Splash Screens both for Android and iOS.

As most of iOS developers would agree that creating iOS Splash screens can be a bit of a hassle due to the OS specific limitations, on the other hand, creating Android Splash screens is merely a cake walk. Now, with the advent of Flutter, I think this can is greatly reduced.

The Problem Statement

To create an app that showcases different types of splash screens namely:

  1. Image Splash
  2. Video Splash
  3. Animated Splash

 

Import Image/Video Files

We need to import the image files into the project. It is common practice to put image files in a images or assets folder at the root of a Flutter project. Since we had to use both images and videos we created separate folders and added them in assets folder.

 

Declare the assets in the pubspec.yaml

It is imperative that you add all the assets in the pubspec.yaml file. You can check more about adding assets from this link.

 

Let’s Code It

As soon as you start to code you get a lot of boilerplate code ready to be worked upon. If we take a look at our main.dart file you can see that we have removed all that code and it’s a bit different than what we see on every other code snippet.

We have used something called as Routes, which is used for routing screens or you can say navigating to different screens of the app.

So, we’ve created 4 named routes namely HOME_SCREEN, VIDEO_SPLASH, IMAGE_SPLASH, ANIMATED_SPLASH that will be used to navigate to the different pages of the demo app.

 

VideoSplashScreen.dart Class

how-to-create-splash-screen-flutter-4

VideoSplashScreen extends a StatefulWidget since we need to change it’s state during runtime so we require a StatefulWidget.

 

VideoState Class

VideoState class extends VideoSplashScreen class. It contains the whole logic of showing the video and moving to the next screen. Let’s take a look at some of the important methods used in this class.

initState Method

If you’re an Android developer then initState is your OnCreate method and if you’re an iOS developer then ViewdidLoad/viewWillAppear is same as initState method.

initializeVideo Method

This method is used to instialize VideoPlayerController.

startTime Method

This method is used to create a timer to move to the next screen as soon as the video or timer finishes.

 

ImageSplashScreen.dart Class

how-to-create-splash-screen-flutter-5

ImageSplashScreen extends a StatefulWidget since we need to change it’s state during runtime so we require a StatefulWidget.

 

SplashScreenState Class

SplashScreenState class extends ImageSplashScreen class. Some of the important methods used in this class are mentioned below.

startTime Method

This method creates an async that is called after 2 seconds to move to the next screen.

 

AnimatedSplashScreen.dart Class

how-to-create-splash-screen-flutter-6

AnimatedSplashScreen extends a StatefulWidget since we need to change its state during runtime so we require a StatefulWidget.

We’ve created an AnimationController with a duration of 2 seconds and we added an animation by the name of CurvedAnimation.

So that completes all the details for this Splash Demo App. Let us know if you have any issues with the project.

You can get the full source code from our GitHub repository.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on hourly or full-time basis as per your requirement! You can connect with us on Facebook and Twitter for any flutter related queries.

]]>
https://flutterdevs.com/uncategorized/how-to-create-splash-screens-in-flutter/feed/ 0
Creating a Flutter Plugin for Android and iOS | Image Gallery https://flutterdevs.com/uncategorized/creating-a-flutter-plugin-for-android-and-ios-image-gallery/ https://flutterdevs.com/uncategorized/creating-a-flutter-plugin-for-android-and-ios-image-gallery/#respond Mon, 12 Oct 2020 19:20:30 +0000 https://flutterdevs.com/?p=13600 What is Flutter plugin?

Flutter plugin is the wrapper of the native code like android( Kotlin or java) and iOS(swift or objective c).

MethodChannel is used to communicate the native code of Android and iOS to flutter (dart code).

This is the basic understanding of the flutter plugin now let’s see why plugins are required.

Why Plugin is Required?

Flutter does not support many things like geolocation, payment SDK, video calling SDK etc and if we want to implement these features in our flutter project then we can write our own plugin in the native code Android and iOS and achieve these custom features.

How to create a plugin:

These are the steps to create a plugin:

Open the android studio got to File>> New >> New flutter project.

 

Click on the New flutter project >>Select the Flutter plugin option.

 

Set name of plugin :

 

Now if you see the file under project_name -> lib , you will find the default code as

import 'dart:async';

import 'package:flutter/services.dart';

class FlutterGalleryPlugin {
  static const MethodChannel _channel =
      const MethodChannel('flutter_gallery_plugin');

  static Future<String> get platformVersion async {
    final String version = await _channel.invokeMethod('getPlatformVersion');
    return version;
  }
}

Above code will communicate with the native code that you will write in Android and iOS files.

Android Native code(java code):

You will find this code in the Android section (project_name -> android)

package com.example.fluttergalleryplugin;

import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry.Registrar;

/** FlutterGalleryPlugin */
public class FlutterGalleryPlugin implements MethodCallHandler {
  /** Plugin registration. */
  public static void registerWith(Registrar registrar) {
    final MethodChannel channel = new MethodChannel(registrar.messenger(), "flutter_gallery_plugin");
    channel.setMethodCallHandler(new FlutterGalleryPlugin());
  }

  @Override
  public void onMethodCall(MethodCall call, Result result) {
    if (call.method.equals("getPlatformVersion")) {
      result.success("Android " + android.os.Build.VERSION.RELEASE);
    } else {
      result.notImplemented();
    }
  }
}

Same applied to the iOS, you will find an initial default code in

( project_name -> ios)

iOS Native code(swift code):

import Flutter

import UIKit

public class SwiftFlutterGallaryPlugin: NSObject, FlutterPlugin {

public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(name: "dialog_box_plugin", binaryMessenger: registrar.messenger())

let instance = SwiftFlutterGallaryPlugin()

registrar.addMethodCallDelegate(instance, channel: channel)

}

public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {

result("iOS " + UIDevice.current.systemVersion)

}

}

As we want to invoke the method that will return the output( in our case we will receive all the images), invoke method will be written in dart code

Dart file (project_name -> lib):

import 'dart:async';

import 'package:flutter/services.dart';

class FlutterGalleryPlugin {
  static const MethodChannel _channel =
      const MethodChannel('flutter_gallery_plugin');

  static Future<String> get platformVersion async {
    final String version = await _channel.invokeMethod('getPlatformVersion');
    return version;
  }
}

Android Native code(project_name -> android -> src):

https://gist.github.com/flutter-devs/7a63b0585183580a8e165c77da82ec9f

iOS Native code(project_name -> iOS -> Classes):

https://gist.github.com/flutter-devs/be36131c0fe5a5bd9be6271bb1d07152

Now, your first plugin is ready to use.

Go the folder example/lib and replace with below code:

https://gist.github.com/flutter-devs/be36131c0fe5a5bd9be6271bb1d07152

Here is a Screenshot of output:

How to publish plugin:

These are the following command to publish plugin into https://pub.dartlang.org/

flutter packages pub publish--dry-run
flutter packages pub publish

You can get the full source code of this demo from this Github repository.

https://github.com/flutter-devs/image_gallery

Don’t forget to give star ⭐and share the repo, this might help someone else!!

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on hourly or full-time basis as per your requirement! You can connect with us on Facebook and Twitter for any flutter related queries.

]]>
https://flutterdevs.com/uncategorized/creating-a-flutter-plugin-for-android-and-ios-image-gallery/feed/ 0
Know Your Widgets: Row and Column https://flutterdevs.com/uncategorized/know-your-widgets-row-and-column/ https://flutterdevs.com/uncategorized/know-your-widgets-row-and-column/#comments Mon, 12 Oct 2020 19:15:13 +0000 https://flutterdevs.com/?p=13598 So, the next widget in our series is not just a single widget, in fact, we would be covering two different widgets in this blog, namely Row and Column. The reason behind integrating two widgets together is the fact these two widgets have similar properties which will help you understand them efficiently.

So, by now you must be familiar with what flutter is and what widgets are. We know everything in Flutter is a widget that means everything you see on a screen is a widget in a Flutter and flutter have lots of widgets, widgets for almost every functionality you wanna put it, if you head over to flutter widgets at flutter.dev you will find a whole list of widgets.

Similarly, Row and Column are also widgets in Flutter and mostly every layout can be broken down in row and column, it’s that important. So let’s explore them individually …

Row

Let’s suppose you want to display a number of widgets in a horizontal manner on the screen, like a Text and an Image and I’m pretty sure you will find this minute requirement everywhere in a layout. That’s where Row widget comes in use, which displays the widgets in a horizontal manner.

A row is a multi-child layout widget which takes in a list of widgets as its children. A row displays the widgets within the visible view i.e. it doesn’t scroll. Use ListView widget to create a scrollable list of widgets, we’ll discuss this widget further in the series.
For now, consider this code snippet which contains Row widgets containing Text widget wrapped in Flexible widget and a FlutterLogo widget.

 

 

This code will display a text and flutter logo in a row as shown in the pic below.

 

 

Note: Flexible widget is used to wrap the text because if the content of the row is wider than the row itself, then the row is said to have overflowed. When a row overflows, the row does not have any remaining space to share between its children and the row reports this by drawing a yellow and black striped warning box on the edge that is overflowing. Refer to the code snippet and the output below for the overview of the issue and importance of Flexible or Expanded.
We will talk about the Flexible and Expanded widgets in other blogs, for now just understand its use.

 

 

Column

Now, we know that to lay the widgets in a horizontal manner we can use a Row widget but what to do when you have to lay the widgets in a vertical manner, that’s where Column widget comes in play.

Column widget alike row is a multi-child layout widget which takes in a list of widgets as its children.
Consider this code snippet which contains a Column widgets containing two flutter logos and a text widget.

This code will display a Text between two Flutter logos as shown in the pic below,

 

Note: Here we didn’t have to wrap the children inside Column with either Flexible or Expanded widgets because for now the content of the children fit the column view perfectly but you might come across a situation where your content of the Column exceeds the amount of space available, in that case the Column overflows resulting in your content getting clipped and a warning is display in the form of yellow and black striped bar indicated at the overflowing edge with a message telling by how much your content has overflowed. Refer to the code snippet and the output below to get an overview of the overflow situation. One can use the Flexible or Expanded widgets to restrict the content to the visible view of the screen but if you want a scrollable vertical list of widgets then use a ListView instead of Column.

 

 

 

Properties of Row & Column

By now you must have a vivid overview of,

    1. What are Row and Column widgets?
    2. How to use Row and Column.
    3. When to use and when not to use?
    4. Basic problems faced with Row and Column
    5. And how to deal with it.

 

Now moving forward let’s look for their properties and see what functionality either of the widgets offers though Row and Column have the same set of properties but works in a slightly different manner. Let’s see those properties.

Row properties:

Here is the constructor of the row with some default values,

Column properties:

Here is the constructor of the column with default values,

 

It’s clear from the constructors that they have similar properties but their usage differs, so we’ll discuss each property by comparing their usage in both row and column.

mainAxisAlignment
This property positions children widgets along the main axis of the layout.

center
This positions the children as close to the middle of the main axis as possible.

end
This positions the children as close to the middle of the main axis as possible depending on the textDirection.

spaceAround
This distributes the free space evenly between the children and half of that free space is used before and after the first and last child respectively.

spaceBetween
This distributes the free space evenly between the children.

spaceEvenly
This distributes the free space evenly between the children and before and after the first and last child respectively.

start
This positions the children close to the start of the main axis depending on the textDirection.

 

 

mainAxisSize
This property directs how much space the children should occupy in the main axis. In the layout, after allocating spaces for the children there might be some free space. mainAxisSize tells whether to maximize or minimize the free space.

min
It minimizes the amount of free space along the main axis.

max
It maximizes the amount of free space along the main axis.

 

 

crossAxisAlignment
This property positions children widgets along the cross axis of the layout.

start
This positions the children start edge to the start side of the cross axis.
For ex: if this is used in a column with the textDirection set to TextDirection.ltr, it aligns the left edge of the children to the left edge of the column.

end
This positions the children as close to the end of the cross axis.
For ex: if this is used in a column with the textDirection set to TextDirection.ltr, it aligns the right edge of the children to the right edge of the column.

center
This positions the children such that their center aligns to the middle of the cross axis. By default the value of crossAxisAlignment is center.

stretch
This lets the children to completely occupy to the cross axis.

baseline
This positions the children such that their baseline match.

 

textBaseline
It’s the horizontal line used for aligning the text.

textDirection
This property determines the order in which to lay the children horizontally.

rtl
It lays the children from right to left direction.

ltr
It lays the children from left to right direction.

 

verticalDirection
This property determines the order in which to lay the children vertically.

children
Both these widgets, Row and Column, takes a list of widgets as its children.

 

So, these were the properties that are included in Row and Column widget, the purpose was to give you an overview of Row and Column widget in the flutter, now it’s your time to explore them and get more familiar with the in-hand experience. remember, the basic rule that we are made familiar with right from childhood is If you don’t practice, you don’t learn. Implement these properties yourself and let us know if we made a mistake or left out something.

If you want to read more about row and column head over to the flutter docs of Row and Column.

 

Related articles:
Keep exploring other widgets with FlutterDevs, from:

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on hourly or full-time basis as per your requirement! You can connect with us on Facebook and Twitter for any flutter related queries.

 

]]>
https://flutterdevs.com/uncategorized/know-your-widgets-row-and-column/feed/ 1
Machine Learning in Flutter  https://flutterdevs.com/blog/machine-learning-in-flutter/ https://flutterdevs.com/blog/machine-learning-in-flutter/#comments Mon, 12 Oct 2020 19:13:52 +0000 https://flutterdevs.com/?p=13596 So, I know Machine Leaning is there in open and it has been there for quite long. It goes way back in the previous century when it was first coined and brought into existence, now you find it everywhere in daily life so important that your life is probably surrounded by it and you may even not know, consider your smartphones they are called “smart” for a particular reason and in today’s time they are “smartest” while getting even more n more from day to day, because they are learning about you from you itself the more you’re using it the more your smartphone gets to know you and all of that is just the machine with lines of code evolving with time like humans. It’s not just limited to smartphones, it’s extensive in technology.
But talking about smartphones consisting of apps which makes your life easier on a daily basis, using Machine Learning is a smarter way to build apps and with Flutter building cross-platform apps have been fun for a while and what if you are able to build an intelligent app with fun using Flutter? Don’t worry we got you sorted and we got it from basics giving you an overview step-by-step which will help you build Flutter apps using Machine Learning.

Machine Learning overview:

Field of study that gives computers the capability to learn without being explicitly programmed.

In a laymen language, one must define Machine Learning as the scientific study of statistical models and algorithms that a computer uses to effectively perform specific tasks without having to provide explicit instructions. It is an application of Artifical Intelligence that enables a system to learn and improvise through experience, where a system can collect the data and learn from it.

 What does Learning mean to a Computer?

A computer program is said to learn from experience E with respect to some class of tasks T and performance measure P if its performance at tasks in T, as measured by P, improves with experience E.

For example: Take an example of playing chess
Here,
E = the experience gained from playing chess
T = the task of playing chess
P = probability of winning the next game

Examples of implementation of machine learning in real life:

You know the general practice to understand something or making someone understand a thing is always try exploring its real-time use in your life. So, following that practice lets us consider some real-life scenarios where one come across Machine Learning in day to day basis.

1. Google photos, we guess everyone is aware of this app on your phone made and maintained by Google, one special and an excellent feature that it practice is the use of machine learnings Face Recognition algorithm in its app. It helps to recognize the people in your photos based on their facial identification. Never encountered it? Head over to the Photos app and experience it yourself.

2. Google Lens, released in the second half of 2017, this Google app helps image recognition in real time, just hover your camera to an image or ask google assistant to scan an image using this app to get insightful information extracted from the image. Be it taking an action in the text like saving the contact, fetching the e-mail ID or finding a dress you like in the image over the web or exploring the places nearby or identify plants and animals. This app makes you explore smartly giving you the futuristic feel and all of this is possible because of one thing i.e. Machine Learning.

3. Shopping Online, This is another most come practiced implementation of Machine Learning. Did you ever notice that when you’re trying to buy a product from an online platform frequently but you didn’t buy it somehow be it because of any reason then your social media like Facebook, your webpages or even the shopping store start recommending you that particular product? This is all possible not because of some human being sitting on a desk and pushing you these adverts NO, in fact, this is Machine Learning algorithms that does it.

4. Medical Enhancements, Yes!, Machine Learning plays a crucial role in the medical field too. Nowadays, the detection of various disease is done just by looking at the slide(cell image) and all of this is performed by machines using the model’s scientists have developed, for something which humans would take a significant amount of time.

And frankly speaking this list of examples is quite long, just imagine anything that learns from its past experience and grows in time.

Firebase and Machine Learning:

So, that was just an overview of Machine Learning giving you a brief about What is Machine Learning? and Where do you come across it in a day to day activity? Well, don’t worry we didn’t lose the track of our objective here which by the way is to get familiar with Machine Learning in Flutter. Heading forward with our objective the next topic to explore is about Firebase. We will start with why we have to explore Firebase here.

Firebase is Google’s mobile and web app development platform that provides developers with a plethora of tools and services to help them develop high-quality apps usually by providing a backend to the app. Most developers use it to create a database to their apps as it helps build apps faster without having to take care of the managing infrastructure.
We will be using firebase because of Firebase ML kit which is a mobile SDK that brings Google’s machine learning expertise to Android and iOS apps in a powerful yet easy-to-use package. Whether you’re new or experienced in machine learning, you can implement the functionality you need in just a few lines of code. There’s no need to have deep knowledge of neural networks or model optimization to get started. On the other hand, if you are an experienced ML developer, ML Kit provides convenient APIs that help you use your custom TensorFlow Lite models in your mobile apps.

Main highlights of Firebase ML kit:

1. Production ready:
Firebase ML Kit comes with a set of ready to use APIs such as Image recognition, Text recognition, face detection, land identification, barcode scanning, image labeling, and language identification. You just have to use the libraries and it feeds you with the information you need.

2. Importing Custom Model:
Suppose you have your own models of ML that you have made in Tensor Flow, don’t worry Firebase got you all covered making it easy for you by letting you import your Tensor flow lite models, just upload your models in firebase and firebase will take care of hosting and serving it to you. Firebase acts as the API layer to your custom model.

3. Cloud or On-device:
Whether you want to use it for cloud services or on-device, firebase ML kit works smoothly, securely and efficiently everywhere. Their APIs works both on the cloud and as well as on-device. On-device it even works when there are network issues while on-cloud it is powered by Google’s cloud platform machine learning technology.

Work Methodology:

So, you must be wondering how does all of this even works and if that is the case trust us, we were in the same position as you are right now until the moment we started to dig and it came out all as easy as pie, ML kit implements Google’s Machine Learning Technology, such as Google Cloud Vision API, TensorFlow lite and Android Neural Network API in a single SDK. Now just imagine the power of all these technologies under one hood; whether you want to hold the power of cloud processing or be it the real-time potential of mobile-optimized models or even your custom models, all of it is just handled in few lines of code.

Implementation:

The path of implementation includes just three steps, yes! just three:

1. SDK integration:
Integrate the SDK using gradle.

2. Prepare input data:
Let us explain it with an example, if you’re using a vision feature, capture an image from the camera and generate the necessary metadata such as image rotation, or prompt the user to select a photo from their gallery.

3. Apply the ML model to your data:
Using the ML model to your data, you can generate a wide spectrum of insights such as the emotional state of detected faces or the objects and concepts that were recognized in the image, depending on the feature you used. Then you can implement these insights to power features in your app like photo embellishment, automatic metadata generation.

Various ready-to-use APIs:

1. Text Recognition:
By using ML Kit’s text recognition API you can identify text in any Latin-based languages which in general sense means almost all languages. It can maneuver the tedious data by itself and by using the cloud-based API you can even extract text from the picture of documents and also apps can track real-time objects.

2. Face Detection:
By using ML Kit’s face detection API you can detect faces from an image and identify their key facial features like locate eyes, nose, ears, cheeks, mouth and even get contours of the detected faces. The information collected through this API can help embellish your selfies like when you want to add beauty to your face in real-time and help capture portraits in portrait mode. It helps perform face detection in real-time so you can use it to generate emojis or add filters in a video call or snap.

3. Barcode scanning:
By using ML Kit’s barcode scanning API you can scan the barcodes to get the encoded data. Barcodes are a convenient way to pass information of the real world to your app. It can encode structured data such as wifi credentials or contact information.

4. Image Labeling:
By using ML kit’s image labeling API you can recognize various entities in an image without having to provide any additional metadata from your side either using on-device or cloud-based API. Basically, image labeling gives you an insight about the content in your image. When you use this API you get the list of entities that were recognized such as people, places, activities and more. Each label comes with a score that mentions the confidence level of the ML model on its observation.

5. Landmark Recognition:
By using landmark recognition API you can recognize the popular landmarks in the image provided to the API by you. After passing the image to it, you get the landmarks that were recognized in the image, along with the coordinates and the place where the landmark is located.

6. Language Identification:
By using language identification API you can determine the language from the given text. This is helpful when working with user-provided text where the information about the language isn’t provided.

Integrating Machine Learning Kit in Flutter:

Phewww! That was a lot of background knowledge but NO that was not to just to spam it with words, in fact, all of that was to give you an overview of Machine Learning and Firebase’s ML Kit and if you were already aware of them then you know how crucial it was to know before moving any further.
But finally, we’re at the part where we integrate Firebase’s ML Kit with Flutter and its just a piece of cake now onwards.

1. Installing plugins:
The basic requirement is to install a Flutter’s ML vision plugin which has been built by the flutter dev team itself and to explore more from them click here. You can use a couple of more plugins depending on your requirement like if you gonna use the Image identification then use image picker plugin which makes you choose either from clicking an image using a camera or get an image from the gallery.

2. Setup the firebase project:
If you are already know how to setup a firebase project then you are good to go for this step and if you aren’t aware of it then below is a video which will help you setup a firebase project using Firebase’s Cloud Firestore over Firebase Real-Time database.

 

 

 

To know about Cloud Firestore, watch

Now, you’re done and good to go with the fundamental requirements and knowledge required to use Machine Learning in Flutter. You can use the various APIs that are available with Firebase ML Kit to get your work done. On this blog, we won’t be discussing the codelab for Machine Learning but we’ll be bringing a codelab in our next blog so stay tuned. This blog was to give you an overview of Machine Learning, Firebase ML Kit and Flutter integration.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on hourly or full-time basis as per your requirement! You can connect with us on Facebook and Twitter for any flutter related queries.

]]>
https://flutterdevs.com/blog/machine-learning-in-flutter/feed/ 1
Know Your Widgets: Cupertino PageScaffold in Flutter https://flutterdevs.com/blog/know-your-widgets-cupertino-pagescaffold-in-flutter/ https://flutterdevs.com/blog/know-your-widgets-cupertino-pagescaffold-in-flutter/#respond Mon, 12 Oct 2020 19:08:14 +0000 https://flutterdevs.com/?p=13592 Well, no doubt that Flutter is all about widgets and just widget and Yes! we know that we have been emphasizing this point with greater importance but that’s what makes us fall in love with Flutter, isn’t it? By now you must have explored flutter.io  and will be aware of the fact that there are lots of widget in Flutter, I mean lot!. When you open the Flutters widget catalog you can see widgets distinguished on some category like Accessibility which enlists all the widgets focusing accessibility capability, Animation and Motion which enlists all the animation related widgets in the flutter, Basics which enlists all the basic widgets used in Flutter development and many more, you can explore more on Flutters widget catalog page.
Among this widget catalog category, you may come across a set of widgets called Cupertino(iOS-style widget) this set of widget enlists all the widgets which will help you design iOS native design in Flutter. This contains a handful of widgets which can help you build an iOS design based app using Flutter like CupertinoActivityIndicator, CupertinoAlertDialog, CupertinoButton, CupertinoDatePicker, etc all the widgets which give you a native feel of iOS. This is our second blog on Cupertino widgets, our first blog was on CupertinoActionSheet which you can read from here which helps you learn about the widget and its implementation in Flutter.

So, let’s start with CupertinoPageScaffold without much further ado. The very first genuine and curious question you might have is what is it? What is CupertinoPageScaffold? Don’t worry, as usual, we got it covered for you and that’s why we here.

What is CupertinoPageScaffold?

Well, we are aware of what Scaffold is in general and if you haven’t read about our scaffold blog please do so from here.
Basically, to brief you about it, Scaffold is what provides the structure to your app implementing material design layout. CupertinoPageScaffold is similar to that which provides you the structure to your iOS application page layout, targeting your iOS design. The Cupertino scaffold lays out the navigation bar on the top and the content between or behind the navigation bar.
Like, the Scaffold widget, CupertinoPageScaffold widget also has certain properties which help you build your UI. Let’s have a look at the CupertinoPageScaffold’s constructor to see what functionality it contains:

We can see what CupertinoPageScaffold contains, it contains a navigation bar, background color, a child and a resizeToAvoidBottomInset property, which we’ll discuss in detail. The constructor also tells us what property is must to have, using the @required tag, the child is mandatory when using the CupertinoPageScaffold, it also tells which property is already given a default value, like resizeToAvoidBottomInset which is set to true by default.
When using any widget it’s constructor always proves to be helpful giving us the heads up while developing, so do have a look.

 

CupertinoPageScaffold

 

Now, let’s explore each of their properties individually:

navigationBar:

The navigationBar is like the appBar in general, drawn at the top of the screen giving you the power to build accessibility feature for the app. navigationBar property uses the CupertinoNavigationBar widgets properties by using CupertinoNavigationBar. The CupertinoNavigationBar is itself a widget so we’ll talk about in an individual blog.

We basically made a simple and basic navigation bar which contains an icon on the left side, a text in the middle and another icon on the right side. This is the least of CupertinoNavigationBar properties that we have used, as we already said we won’t be discussing CupertinoNavigationbar widget in this blog. This line of code produces this screen:

Navigation Bar

 

backgroundColor:

The backgroundColor property, as the names say it provides the background color to the page. It takes the property of the Color class which takes the color using three different ways,

1. Color(int value): which takes the 32-bit color value
2. Color.fromARGB(int a, int r, int g, int b): it takes an Alpha ‘a'(which is used to set the transparency), Red color value, Green color value, and Blue color value.
3. Color.fromRGBO(int r, int g, int b, int o): it takes Red color value, Green color value, Blue color value, and Opacity value.

So, here we used the first way of using the color, you can use any of the three based on your requirement to give the background color. This gives the scaffold a grey color.

Grey background color

resizeToBottomInset:

This property tells whether the child of the scaffold should resize itself to avoid the window’s bottom inset. Let me explain it with you an example: You must have always come across the situation on every app where the keyboard pops up from the bottom and you start typing, this is the property that makes sure that your content doesn’t hide behind the on-screen keyboard and your app body should resize itself to avoid any overlapping. This property takes the boolean value and by default, it is set to true.

 

child:

This property enables you the take any other widget that is to be shown in the main content area. For example, you can take any widget in it, be it a text widget, icon widget, image widget, just to name the least.

 

Here, we took the text widget to display the text in the main content area.

Text as the child of CupertinoPageScaffold

 

 

So, this was all the properties of CupertinoPageScaffold and we hope that was sufficient to know about it, if you have any doubts or if we missed something then feel free to let us know. You can head over to https://flutter.dev to explore flutter.

If you want to read more about row and column head over to the flutter docs of CupertinoPageScaffold.

 

Related articles:
Keep exploring other widgets with FlutterDevs, from:

 FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on hourly or full-time basis as per your requirement! You can connect with us on Facebook and Twitter for any flutter related queries.

 

 

]]>
https://flutterdevs.com/blog/know-your-widgets-cupertino-pagescaffold-in-flutter/feed/ 0
Data Persistence with SQLite | Flutter https://flutterdevs.com/uncategorized/data-persistence-with-sqlite-flutter/ https://flutterdevs.com/uncategorized/data-persistence-with-sqlite-flutter/#comments Mon, 12 Oct 2020 19:06:49 +0000 https://flutterdevs.com/?p=13590 Whenever you need to store the data on the local then you need to use SQLite to persist the user data.

 

Why Data Persistence?

Persisting data is important for users since it would be inconvenient for them to type their information every time or wait for the network to load the same data again. In situations like this, it would be better to save their data locally.

Why we use SQLite?

SQLite is a popular choice as embedded database software for local/client storage in application software such as web browsers.

How to use SQLite in a flutter?

Before using SQLite, you should know that

SQLite is not available in a flutter SDK as Android but we have a plugin sqflite that exactly performs all the operation on the database just like in Android and iOS.

Flutter plugin is the wrapper of the native code written in Kotlin or java for Android and swift or objective-c for iOS.
P.S : Plugin can also be created only with dart code

If you are new to SQLite, go through SQLite Tutorial site here.

Implementation

Step 1: Add the dependencies

To work with SQLite databases, import the sqflite and path packages

1. The sqflite package provides classes and functions that allow you to interact with a SQLite database.
2. The path_provider package provides functions that allow you to correctly define the location to store the database on disk such as TemporaryDirectory and ApplicationDocumentsDirectory.

Step 2: Create a Model class

SQLite creates a table for the model class, the fields in the class correspond to columns in the table. Therefore, the classes tend to be small model classes that don’t contain any logic. Our Person class represents the model for the data in the database.

If we want to insert into the database then we need to convert the Person into a Map

And if we want to retrieve from the database then we need to convert the Map into the Person

This is how our PODO class will look like

Step 3: Create a database

We will make a separate class as database.dart to make the code more modular and add all the requirements meths for managing the database that can be accessed anywhere in the app.

Create a singleton class DatabaseProvider

Why Singleton?
We use the singleton pattern to ensure that we have only one class instance and provide global point access to it.

How to create a Singleton in Dart?
Create a private constructor that can be used only inside the class.

Step 4: Open the Database

Before you read and write data to the database, you need to open a connection to the database. This involves two steps:

1. Define the path to the database file using the getDatabasesPath from the sqflite package combined with the pathfunction from the path package
2. Open the database with the openDatabase function from sqflite

Step 5: Create the table

You need to create a table to store information.
For example, In our case, we create a table called Person that defines the data that can be stored. In this case, each Person contains an id, name, and city. Therefore, these will be represented as three columns in the Person table.

1. The id is a Dart int, and will be stored as an INTEGER SQLite Datatype. It is also good practice to use an id as the primary key for the table to improve query and update times.

2. The name is a Dart String, and will be stored as a TEXT SQLite Datatype

3. The city is also a Dart String, and will be stored as an TEXT Datatype

To prevent from opening a connection to the database again and again we can use this:

Step 6: Managing the data

Now we are going to show you how you can perform an operation on the SQLite database.

Query:

getAllPersons() will return all the person from the SQLite database if available.

Insert:

Delete:

If you see we have two methods, one deletes the row with particular id and other deletes all data present in the table, you can change all the query according to your need.

Update:

If these small code snippets still confuse you we have the complete code of the database class:

Step 7: Using the data

In order to use the database we need to create the instance of the database and use the method present in the database class

DatabaseProvider.db

This will help us to perform an operation on the database.

like if we want to get  the person in the database we will use the method that we have defined in our DatabaseProvider class

DatabaseProvider.db.getAllPersons()

And if I want to display it in the list then I’ll use FututeBuilder :

That it for SQLite in flutter.

Thanks for reading this article

If we got something wrong? Let me in the comments. we would love to improve.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on hourly or full-time basis as per your requirement! You can connect with us on Facebook and Twitter for any flutter related queries.

]]>
https://flutterdevs.com/uncategorized/data-persistence-with-sqlite-flutter/feed/ 3