Home Blog Page 72

How to get mac address of android phone programmatically

0
How to get mac address of android phone programmatically

Hi Guys, Welcome to Proto Coders Point, In this Android Tutorial we will check out How to get mac address of android phone programmatically – find mac address android devices.

So let’s begin

Find MAC Address of android Device Programmatically

Step 1 : Create a new Android Project

Step 2 : Add required Permission

Then, to get MAC Address of any android device you need to add some permission like ACCESS WIFI STATE, INTERNET, ACCESS NETWORK STATE.
To add them:

In your Android Manifest.xml file add below uses permission, just before <application> tag begin

<uses-permission>

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Step 3: Create a method GetMacAddress

Now, create a method that help you in getting mac address of your android mobile device.

public String getMacAddress(){
        try{
            List<NetworkInterface> networkInterfaceList = Collections.list(NetworkInterface.getNetworkInterfaces());

            String stringMac = "";

            for(NetworkInterface networkInterface : networkInterfaceList)
            {
                if(networkInterface.getName().equalsIgnoreCase("wlon0"));
                {
                    for(int i = 0 ;i <networkInterface.getHardwareAddress().length; i++){
                        String stringMacByte = Integer.toHexString(networkInterface.getHardwareAddress()[i]& 0xFF);

                        if(stringMacByte.length() == 1)
                        {
                            stringMacByte = "0" +stringMacByte;
                        }

                        stringMac = stringMac + stringMacByte.toUpperCase() + ":";
                    }
                    break;
                }

            }
            return stringMac;
        }catch (SocketException e)
        {
            e.printStackTrace();
        }

        return  "0";
    }

Step 4: Call the above method

By calling above getMacAddress() you will get mac address of android device.

String mobile_mac_addres = getMacAddress();  //call the method that return mac address 

Log.d("MyMacIS",mobile_mac_address);   // print the mac address on logcat screen

Here, we are calling getMacAddress() method and storing the MAC ADDRESS in a String Varaible.

How to get mac address of android phone programmatically – Complete Source Code

MainActivity.java

package com.example.getmacaddress;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    String mobile_mac_address;
    TextView macaddress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        macaddress = (TextView)findViewById(R.id.macaddress);

        mobile_mac_address = getMacAddress();

        Log.d("MyMacIS",mobile_mac_address);

        macaddress.setText(mobile_mac_address);

    }

    public String getMacAddress(){
        try{
            List<NetworkInterface> networkInterfaceList = Collections.list(NetworkInterface.getNetworkInterfaces());

            String stringMac = "";

            for(NetworkInterface networkInterface : networkInterfaceList)
            {
                if(networkInterface.getName().equalsIgnoreCase("wlon0"));
                {
                    for(int i = 0 ;i <networkInterface.getHardwareAddress().length; i++){
                        String stringMacByte = Integer.toHexString(networkInterface.getHardwareAddress()[i]& 0xFF);

                        if(stringMacByte.length() == 1)
                        {
                            stringMacByte = "0" +stringMacByte;
                        }

                        stringMac = stringMac + stringMacByte.toUpperCase() + ":";
                    }
                    break;
                }

            }
            return stringMac;
        }catch (SocketException e)
        {
            e.printStackTrace();
        }

        return  "0";
    }


}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">

    <TextView
        android:id="@+id/macaddress"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

Flutter Calender Widget Example – Table Calender Widget

0
Flutter calendar widget example
Flutter calendar widget example

Hi Guys Welcome to Proto Coders Point, In this article we will learn how to add calender in your flutter application.

Calender Widget in Flutter App

Using Calender you can organize the day, week and month, you can also check religious or any social event in flutter calender widget, It keeps a data of event or festival event that comes on a particular date or ant special event on calender.

In this tutorial article, we will check out how to use table_calender widget to display calender widget in flutter application.

So as you know that flutter team, keeps on work to build best UI widget so that developer work becames much easier, So our Flutter team has provided a best simple calender by name Table_Calender that makes easy to display a calender in our flutter app.

The table calender widget in flutter is a powerful widget which comes with many feature, customizable feature and even such a gesture and animation etc.

Feature of table calender widget

  • Easy to use API.
  • UI can be controlled using Custom Builder calender
  • Beautiful animation feature.
  • Gesture Detector
  • Has Multiple calender formats like year, month, week.
  • It has vertical auto sizing.

So, Let’s begin adding calender in flutter app

Step 1: Create a new Flutter Project

OffCourse, you need to open an existing flutter where you want to add calender or create a new flutter project,

Start your favorite IDE, In my case i make use of Android studio to build flutter apps.

New -> New Flutter Project -> Give a project title for example “Flutter Calender Example”.

Step 2 : Adding Dependencies

In your flutter project structure, you will file a file by name ‘pubspec.yaml’ open it, you need to add the dependencies ‘table_calender’ .

As shown in below screenshot

table calender widget

for the latest version of this package, kindly visit official site : https://pub.dev/packages/table_calendar/install

Step 3: Importing the calender dart file

Then now, once you have added the dependencies then you need to import the library/packge of calender where you want to use/display calender.

import 'package:table_calendar/table_calendar.dart';

Step 4: Code Process Explaination

1 : First we need to create a object for CalenderController that controls all the evven/action happening in calender & you need to initialize it in initState().

class _HomeCalendarPageState extends State<HomeCalendarPage> {
  CalendarController _controller;   //controller creation

  @override
  void initState() {
    super.initState();
    _controller = CalendarController();  //initializing it 
  }Flutt

 2 : Now you need to use calenderWidget i.e TableCalender as a child of Scafford Widget.

Scaffold(  
    body: SingleChildScrollView(  
      child: Column(  
        children: <Widget>[  
          TableCalendar()   // snippet code   // you need to customize it as per your UI // check below for full source code
        ],  
      ),  
    ),

above code is just a snipet code, you need to customize it as per you UI needs.

Flutter Calender Widget – Table Calender – Full Source Code

main.dart

Copy paste below code in main.dart file of your flutter project

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.green,
      ),
      home: HomeCalendarPage(),
    );
  }
}

class HomeCalendarPage extends StatefulWidget {
  @override
  _HomeCalendarPageState createState() => _HomeCalendarPageState();
}

class _HomeCalendarPageState extends State<HomeCalendarPage> {
  CalendarController _controller;

  @override
  void initState() {
    super.initState();
    _controller = CalendarController();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Calendar Example'),
      ),
      body: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            TableCalendar(
              initialCalendarFormat: CalendarFormat.month,
              calendarStyle: CalendarStyle(
                  todayColor: Colors.blue,
                  selectedColor: Theme.of(context).primaryColor,
                  todayStyle: TextStyle(
                      fontWeight: FontWeight.bold,
                      fontSize: 22.0,
                      color: Colors.white)
              ),
              headerStyle: HeaderStyle(
                centerHeaderTitle: true,
                formatButtonDecoration: BoxDecoration(
                  color: Colors.brown,
                  borderRadius: BorderRadius.circular(22.0),
                ),
                formatButtonTextStyle: TextStyle(color: Colors.white),
                formatButtonShowsNext: false,
              ),
              startingDayOfWeek: StartingDayOfWeek.monday,
              onDaySelected: (date, events,e) {
                print(date.toUtc());
              },

              builders: CalendarBuilders(
                selectedDayBuilder: (context, date, events) => Container(
                    margin: const EdgeInsets.all(5.0),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        color: Theme.of(context).primaryColor,
                        borderRadius: BorderRadius.circular(8.0)),
                    child: Text(
                      date.day.toString(),
                      style: TextStyle(color: Colors.white),
                    )),
                todayDayBuilder: (context, date, events) => Container(
                    margin: const EdgeInsets.all(5.0),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                        color: Colors.blue,
                        borderRadius: BorderRadius.circular(8.0)),
                    child: Text(
                      date.day.toString(),
                      style: TextStyle(color: Colors.white),
                    )),
              ),
              calendarController: _controller,
            )
          ],
        ),
      ),
    );
  }
}

Output

 

 

Flutter Dynamic theme change using getX | Dark & Light mode

0
change flutter theme dynamically using getx library
change flutter theme dynamically using getx library

Hi Guys, Welcome to Proto Coders Point, In this Flutter Tutorial we will create a app where user can select his desired theme either dark theme in flutter or light theme in flutter.

VIDEO TUTORIAL

Flutter Dynamic theme change using getX

Step 1 : Create a new Flutter project

Start your favorite IDE, In my case i am making user of ANDROID STUDIO to build Flutter project, you may use as per your choice.

Create a new Flutter project
IDE -> Files -> New > New Flutter Project -> give name -> give package name and finish

Step 2: Add GetX & Get Storage dependencies

Then, once your flutter project is been created, you need to add 2 required dependencies i.e. GetX  & Get Storage in pubspec.yaml

adding depencencies in flutter getx get storage
adding depencencies in flutter getx get storage

Step 3 : Adding images in Flutter project

create a package/folder in your flutter project structure, Right click on project -> New -> Directory (give name) and add image files in that folder.

After creating the directory you need to specify the path of the directory you have created in pubspec.yaml file so that your flutter project can access the images.

You can see in below screenshot, i have created folder by name images which has 2 images in it, and then in pubspec.yaml file i have gave the image path in flutter.

flutter image, assets path

Step 4: The Code

If you face problem in understand below code, learn basic of Getx and Get Storage (link is below)

void main() async{
  await GetStorage.init();  // before building the app  you need to initialize GetStorage  // so that we have access to use app data
  runApp(MyApp());
}

Then, Create a instance of GetStorage class

final appdata = GetStorage();  // instance of GetStorage

Now, using instance create a key-value pair

appdata.writeIfNull('darkmode', false);

as you see above, ‘darkmode’ is a key and false is value stored in it.

bool isDarkMode = appdata.read('darkmode');  //  get data from get storage and store in a boolean variable

This isDarkMode will store either true or false, If true then it means, user have previously turned on dark mode before closing the app.

and depending on isDarkMode, we will set the theme of the app either dark mode or light mode.

A Switch Widget to turn on/off dark mode dynamically in flutter

Switch(
                    value: isDarkMode ,
                    onChanged: (value) => appdata.write('darkmode', value),
      )

Complete Flutter code main.dart

This complete code will be posted on github repository, you may download it from there (link below)

import 'package:flutter/material.dart';
import 'package:get_storage/get_storage.dart';
import 'package:get/get.dart';

void main() async{
  await GetStorage.init();  // before building the app  you need to initialize GetStorage
  runApp(MyApp());
}

class MyApp extends StatelessWidget {

  final appdata = GetStorage();  // instance of GetStorage

  @override
  Widget build(BuildContext context) {

    appdata.writeIfNull('darkmode', false);
    return SimpleBuilder(
      builder: (_)
      {
        bool isDarkMode = appdata.read('darkmode');
        return GetMaterialApp(
          theme: isDarkMode ? ThemeData.dark() : ThemeData.light(),
          home: Scaffold(
            appBar: AppBar(title: Text("Getx Dynamic theme change"),),
            body: Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Image.asset(isDarkMode ? 'images/night.png' :'images/day.png' ,width: 100,height: 100,),
                  Switch(
                    value: isDarkMode ,
                    onChanged: (value) => appdata.write('darkmode', value),
                  )
                ],
              ),
            ),
          ),
        );
      },
    );
  }
}

To make it easy i am making user of Getx & Get Storage package https://pub.dev/packages/get_storage/

Watch this video to learn basic of Get Storage and Getx Basic : https://www.youtube.com/watch?v=L7Zs4yuStsw&t=1s

Keep user logged in into the app :

https://youtu.be/ViXfhl4dA3w

clone project on github https://github.com/RajatPalankar8/flutter_dynamic_theme_change.git

Comment below for any queries

😀 Follow and support me:

🐦 Twitter: https://twitter.com/rajatpalankar
💬 Facebook: https://www.facebook.com/protocoderspoint/
💸 Instagram: https://www.instagram.com/protocoderspoint/

Be sure to ask for help in the comments if you need any. Suggestions for future Flutter tutorials are also very welcome! 🙂 For mobile application development keep learning freely from proto coders point Visit: https://protocoderspoint.com/

Flutter map string dynamic example – Map in Flutter

0
Flutter map string dynamic example
Flutter map string dynamic example

Hi Guys, Welcome to Proto Coders Point, In this Article we will learn about map in dart programming language.

Dart Map

In Dart or any other programming language, A Map Object is a key-value pair to store string or any dynamic data.
Here, In dart map, A key & value can be of any datatype, It  means that we can store any data type because a map in dart language is a dynamic collection of data/information.

In Flutter Dart, A map can be declared in 2 ways : –

  • Using Map Literals.
  • Using Map Constructor.

Declaring a map using Map Literals

To declare a map in dart you need to enclose the key-value pair in a curly bracket “{}”

Syntax
var identifier = { ‘key1′:’value1’ , ‘key2′:’value2’ , ‘key3′:’value3’,  …….. };

Example

var usrMap = {"name": "Proto Coders Point ", 'Website': 'https://protocoderspoint.com/'}; 
   
print(usrMap);

output

map literal example

To get/print particular key value then you can do it like this print ( usrMap[‘name’] ) this will print the value = Proto Coders Point.

Declartion of Map using Map Construtor

Using map constructor, A Map can be declared in 2 steps:

  • Declare Map using it constructor
  • Initilalize the map

Syntax

var identifier = new Map();

then, to initialize to maps with some key-value

identifier[key] = value

Example

void main() { 
  
var logincred = new Map();
  
  logincred['username']='admin';
  logincred['password']='admin@12334#';
  
  print(logincred);

}

output

map constructor example

Properties of Map in dart

So, to us map you need to import dart.core package

  1. Keys : This will return all the key in map object.
  2. Values : Wiil return all the value in map object.
  3. length : Return the number of key-value pair length/size.
  4. isEmpty : Will return true if Map object is empty.
  5. IsNotEmpty : Will return true if map value is not empty.

Function of Map dart

There are some comman task performed with Map in dart:

  1. addAll() : Used to add all key-value of some other Map Object.
  2. clean() : Remove all data from pair.
  3. remove() : Remove Specific date of key.
  4. foreach : used to iterate and read alll map entires.

addAdd() :  Example

void main() { 
  
 var usrMap = {"name": "Proto Coders Point ", 'Website': 'https://protocoderspoint.com/'}; 
  
  
  var map2 = {'email': 'protocoders.come'};
  
  usrMap.addAll(map2);
  
  print(usrMap);


}

output

map add All

remove() : Example

Removes Specific data of key – values from map data, it accept a key which is  needed to be removed.

void main() { 
  
Map m  = { 'id': 01 ,'name': 'Rajat'};

  print("Before removing : ${m}");
  
  dynamic res = m.remove('name'); // here name is the key.
  
  print("removed data is : ${res}");
  
  
  print("After removing ${m}");

}

output

map remove function

foreach : Example

By using foreach function in Map you can easily iterate and read all the maps entries.

Syntax :  Map.forEach(void f(K key , V value));

void main() { 
  
var userdata = { 'name': 'Proto Coders Point', 'Website': 'https://protocoderspoint.com/'};
  
  userdata.forEach((k,v){
    print('  ${k} ${v}');
  });

}

output

Recommended Article

Dart data types – variable in dart

Flutter array array in flutter

Dropdown in flutter

List in dart – convert list to set or vice versa

Flutter Sharedpreferences Alternative | GetX Storage | keep user loggedIn?

1
flutter sharedpreferences alternative getx storage library
flutter sharedpreferences alternative getx storage library

Hi Guys, Welcome to Proto Coders Point, In this Flutter tutorial article, We will learn how to use GetX Storage package (an alternative of shared preferences) in Flutter Application Development to keep users logged In.

In this example we gonna make use of Get Storage library GetX, to keep logged in users data.

Video Tutorial

What is Get_Storage Package in flutter?

In Flutter get storage is a very fast, extra light weight & synchronous key-value pair package that will help you to store app data in memory such as, if user is signed in, if yes, then all the details about the user.

The GetX Storage is built completly built using dart programming language & we can easily integrate with GETX framework of flutter.

This Flutter package to store user data is fully tested & supported on most of the famous operating system like, Android, iOS, Web, Windows & much more OS.

Which kind of data get_storage can handle/store?

Using Getx Storage we can store data type such as StringintdoubleMap, and a list of values/arrays.

Installation and Basic of Get Storage Library

Check out this,

https://protocoderspoint.com/flutter-getx-storage-alternative-of-sharedpreferences/

 

Flutter Sharedpreferences Alternative GetX Storage | keep user loggedIn?

So let’s begin, with this small task in flutter app, to keep user signedIn using GetX Storage package (An Alternative of SharedPreferences)

OffCourse you need to create a new flutter project in your favourite IDE in my case i am using Android Studio as my IDE to develop flutter apps.

Create a new Flutter project and add the required 2 dependencies ( GetX & Get Storage ).

Then, to do this task you need 3 dart pages i.e

  • main.dart
  • LoginPage.dart
  • DashBoardPage.dart

main.dart : Here we will check if the user is logged in or no
If the user is not Logged In then we will Navigate user using GetX to LoginPage.
If user is been Logged In then we can navigate user to DashBoardPage.

LoginPage.dart: In this page/screen user can enter username & password to signIn to the app, SignedIn user data will be stored using Get Storage library in key, value pair. & from successfull signIN we will navigate the user to dashboard page.

Dashboardpage.dart: Here we can simple show a username of the signed/logged in user and there is a button so that user can logout from the app.

Creating dart files in project

As stated above we need 3 dart files, So for that in lib directory of your flutter project create them.

flutter project structure and it files
flutter project structure and it files

Codes – Login Form – Keep user logged in Using GetX Get Storage – Alternative of SharedPreferences

main.dart

In main page we are just checking if the user is been previously logged in or no

import 'package:flutter/material.dart';
import 'package:flutter_get/DashBoard.dart';
import 'package:flutter_get/LoginPage.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';


void main() async{
  await GetStorage.init();
  runApp(MyApp());
}

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

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

  final userdate = GetStorage();

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

    userdate.writeIfNull('isLogged', false);

    Future.delayed(Duration.zero,() async{
      checkiflogged();
    });

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Center(
          child:  CircularProgressIndicator()
        ),
      ),

    );
  }

  void checkiflogged() {
    userdate.read('isLogged') ? Get.offAll(DashBoard()) : Get.offAll(LoginPage());
  }
  
}




 

LoginPage.dart

UI Design

Login Page UI design Flutter

import 'package:flutter/material.dart';
import 'package:flutter_get/DashBoard.dart';
import 'package:get_storage/get_storage.dart';
import 'package:get/get.dart';


class LoginPage extends StatelessWidget {

  final username_controller = TextEditingController();
  final password_controller = TextEditingController();

  final userdata = GetStorage();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(" Shared Preferences"),
      ),
      body: Center(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              "Login Form",
              style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
            ),
            Text(
              "To show Example of Shared Preferences Alternative using GetX Storage",
              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');

                  userdata.write('isLogged', true);
                  userdata.write('username',username );

                  Get.offAll(DashBoard());

                }else{
                  Get.snackbar("Error", "Please Enter Username & Password",snackPosition: SnackPosition.BOTTOM);
                }
              },
              child: Text("Log-In"),
            )
          ],
        ),
      ),
    );
  }
}

 



DashBoard.dart

dashboard page flutter

import 'package:flutter/material.dart';
import 'package:flutter_get/LoginPage.dart';
import 'package:get_storage/get_storage.dart';
import 'package:get/get.dart';

class DashBoard extends StatelessWidget {

  final userdata = GetStorage();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(" Shared Preferences"),
      ),
      body: Center(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              "USER DATA",
              style: TextStyle(fontSize: 30, fontWeight:  FontWeight.bold),
            ),
            Text(
              "NAME : ${userdata.read('username')}",
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.w500),
            ),
            RaisedButton(
              onPressed: (){

                userdata.write('isLogged', false);
                userdata.remove('username');
                Get.offAll(LoginPage());

              },
              child: Text("LOGOUT"),
            )
          ],
        ),
      ),
    );
  }
}

 

Flutter GetX Storage – Alternative of SharedPreferences

0
flutter getx storage - alternative of shared preferences
flutter getx storage - alternative of shared preferences

Hi Guys, Welcome to Proto Coders Point, In this Flutter Article tutorial we will learn about GetX Get_Storage package

What is Get_Storage Package in flutter?

In Flutter get storage is a very fast, extra light weight & synchronous key-value pair package that will help you to store app data in memory such as, if user is signed in, if yes, then all the details about the user.

The GetX Storage is built completly built using dart programming language & we can easily integrate with GETX framework of flutter.

This Flutter package to store user data is fully tested & supported on most of the famous operating system like, Android, iOS, Web, Windows & much more OS.

Which kind of data get_storage can handle/store?

Using Getx Storage we can store data type such as String, int, double, Map, and a list of values/arrays.

How to install flutter package library – Get Storage library

Official site : https://pub.dev/packages/get_storage/install

  1. Add the dependencies in pubspec.yaml file:

    In your flutter project structure you will find a file by name “pubspec.yaml” file,
    Open it & under dependencies section add getx and get_storage package

    dependencies:
      get_storage: ^1.3.2
      get:
  2. Import them

After adding the required dependencies, you need to import it where you want to add getx storage feature.

import 'package:get_storage/get_storage.dart';

 

How to use getX Get Storage package?

  1. Initialization
    To Initialize storage, you must call GetStorage.init() method before loading the app / before calling runApp

    void main() async {
      await GetStorage.init();   //get storage initialization
      runApp(MyApp());
    }

    Here we need to make the main as “async” & to initialize GetStorage we must use “await”.
    So that if any data is been stored in device, it get loaded before the actual app

  2. Create a Instance of get Storage class

    final datacount = GetStorage();   // instance of getStorage class

     

  3. How to store/write data in getx storage
    To store/write data or information you must make use of “write“.
    Example:

    datacount.write("count", _count);

    get storage

    Here count is key  and _count is a value.

  4. How to read value from key
    To read values you need to use “read
    Example:

    datacount.read('count')

     

  5. To delete/remove the data
     you can delete/remove the data that is been stored by making use of “remove”
    Example:

    datacount.remove('count');

    So now we are down with basic of get storage package, Now let’s Check with a example

Example 1 : Counter App – Flutter sharedpreferences alternative

In this example, we will add  Get Storage  feature to default code if flutter i.e Increment valuable on button press.

Here will be store  the counter variable to get Storage instance class, so that when the app is removed in future it remember the last added counter value.

main.dart

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';


void main() async {
  await GetStorage.init();
  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: HomePage()
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

  int _count = 0;

  final datacount = GetStorage();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if(datacount.read('count')!= null)
      {
        _count = datacount.read('count');
      }
  }
  @override
  Widget build(BuildContext context) {

    datacount.writeIfNull("count", 0);
    return Scaffold(
      body: SafeArea(
        child: Center(
          child: Container(
            child: Text("${datacount.read('count')}"),
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: (){
         setState(() {
           _count++;

           datacount.write("count", _count);
         });
        },
        child: Icon(Icons.add),
      ),
    );
  }
}