Home Blog Page 72

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),
      ),
    );
  }
}


 

 

Flutter Encryption and Decryption using flutter string encryption

0
how to encrypt password in flutter
how to encrypt password in flutter

Hi Guys Welcome to Proto Coders Point, In this Flutter tutorial we will check how to encrypt password in flutter using flutter string encryption.

Video Tutorial

Flutter string encryption Package Plugin

This package is very useful for string encryption, it’s a Cross platform string encryption which uses commonly best Encrytion methods like (AES/CBC/PKCS5/RandomIVs/HMAC-SHA256 Integrity Check).

Installation of Flutter Encryption package

1. Adding Dependencies in pubspec.yaml file

open your flutter project that you have created in your IDE(android-studio).

In your project structure you may see a file by name pubspec.yaml name open, in this file under dependencies add the package

dependencies:
  flutter_string_encryption: ^0.3.1   // add this line // package version may change kindly check update version on offical site

2. Importing the package

Then after you have added the required flutter encryption package now you need to import the package where you will be using it in your code to encrypt or decrypt the string or the password the user enter.

import 'package:flutter_string_encryption/flutter_string_encryption.dart';

So now the flutter encryption and decryption package is been successfully added into your flutter project, now you can use it.

So now let’s check how to encrypt a string using flutter string encryption

Usage of the library

// create a PlatformStringCryptor

In Below Snippet code we have creating an object of PlatformStringCryptor that will help use in creatng salt and to generate key.

final cryptor = new PlatformStringCryptor();

// generate a Salt string using Cryptor

final String salt = await cryptor.generateSalt();

//generate a key from password

Here password is the text that user enter in textfield

final String key = await cryptor.generateKeyFromPassword(password, salt);

Encrypt A String

final String encrypted = await cryptor.encrypt("Password that you want to encrypt", key);

Decrypt A String

try {
  final String decrypted = await cryptor.decrypt(encrypted, key);
  print(decrypted); // - A string to encrypt.
} on MacMismatchException {
  // unable to decrypt (wrong key or forged data)
}

IMPORTANT NOTE

Then key that is used to Encrypt a string should be same while you want to decrypt the encrypted string.

Implementing Flutter Encryption decryption in Flutter Project

main.dart

import 'dart:math';

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


void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(

        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

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

class _MyHomePageState extends State<MyHomePage> {

  TextEditingController pass = TextEditingController();

  var key = "null";
  String encryptedS,decryptedS;

  var password = "null";

  PlatformStringCryptor cryptor;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Password Encrypt"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Padding(
              padding: const EdgeInsets.fromLTRB(30, 0, 30, 0),
              child: TextField(
                controller: pass,
                decoration: InputDecoration(
                  hintText: 'Password',
                  hintStyle: TextStyle(color: Colors.black),
                  enabledBorder: OutlineInputBorder(
                    borderRadius: new BorderRadius.circular(10.0),
                    borderSide: BorderSide(
                        color: Colors.red
                    ),
                  ),
                  focusedBorder: OutlineInputBorder(
                      borderRadius: new BorderRadius.circular(10.0),
                      borderSide: BorderSide(
                          color: Colors.blue[400]
                      )
                  ),
                  isDense: true,                      // Added this
                  contentPadding: EdgeInsets.fromLTRB(10, 20, 10, 10),
                ),
                cursorColor: Colors.white,
              ),
            ),
            RaisedButton(
              onPressed: (){
                Encrypt();
              },
              child: Text("Encrypt"),
            ),
            RaisedButton(
              onPressed: (){
                Decrypt();
              },
              child: Text("Decrypt"),
            ),
          ],
        ),
      ),
    );
  }

// method to Encrypt String Password
  void Encrypt() async{

    cryptor = PlatformStringCryptor();
    final salt = await cryptor.generateSalt();

    password = pass.text;

    key = await cryptor.generateKeyFromPassword(password, salt);

  // here pass the password entered by user and the key
    encryptedS = await cryptor.encrypt(password, key);

    print(encryptedS);
  }


// method to decrypt String Password
  void Decrypt() async{

    try{
      //here pass encrypted string and the key to decrypt it 
      decryptedS = await cryptor.decrypt(encryptedS, key);

      print(decryptedS);
    }on MacMismatchException{

    }
  }

}


Output

Flutter encrypted decrypted example
Flutter encrypted decrypted example

 

Arrays in Dart – How to create & print array in flutter / dart?

0
How to print array in flutter
How to print array in flutter

Hi Guys, Welcome to Proto Coders Point, In this tutorial we will learn about arrays in dart flutter with an example

What is array in dart?

Same as other programming language, In dart also the defination of array is same.

An array in an object that can be used to store a list of collections of elements. In array list the collection can be of any datatype: numbers, String, etc.

In Flutter dart, array can be used to store multiple values in one datatype variable.

To access the value/element in the array list then you can do it through it index id.
The value stored in an array are called as elements.

array in dart flutter
array structure in dart flutter

Initializing arrays in Dart

Using literal constructor

Using Literal constructor [] an new array can be created: as shown in below example:

import 'dart:convert';
void main() { 
   var arr = ['a','b','c','d','e'];  // array literal constructor

   print(arr);    //print the array on the screen 
}

How to print array in flutter?

To print array list on the screen or on console log then

you can make use of print cmd to print on console

else if you want to display array in your flutter app then you can make use of Text widget to show the array list

 new keyword and List 

import 'dart:convert';
void main() { 
   var arr = new List(5);// creates an empty array of length 5
   // assigning values to all the indices


   //adding data to array list 
   arr[0] = 'a'; 
   arr[1] = 'b'; 
   arr[2] = 'c'; 
   arr[3] = 'd'; 
   arr[4] = 'e';  


   print(arr); 
}

How to access particular array element? Method to read array list

first() Return first element of the array.
last()  last element of the array.
isEmpty() It returns true if the list is empty; otherwise, it returns false.
length() It returns the length of the array. eg : 5

Example

import 'dart:convert';
void main() { 
   var arr = ['a','b','c','d','e']; 
   print(arr.first);// first element of array
   print(arr.last);// last element of array
   print(arr.isEmpty);// to check whether the array is empty or not
   print(arr.length);// the lenght of the array
   
}

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

Why flutter hot reload is  faster then gradle build android instant run?

1
why flutter hot reload is fast
why flutter hot reload is fast

Hi Guys, Welcome to Proto Coders Point.

In this article we will discuss on why flutter hot reload is faster then android instant run.

Very little difference you may see in flutter hot reload and android Instant run/gradle build

Flutter Hot Reload

The Flutter Framework automatically rebuilds the widget tree, this framework allow you to rapidly boost and reload the changes that your have made in your source code.

When you change flutter dart code and save and send your dart code to get rebuild in your mobile phone where it takes only few seconds or sometime instantly get run.

Hot reload in flutter is so fast because Flutter engine make user of JIT model (just-in_time) for compilation while you run in debug mode, which means that less time is spent in compilation.

But at some point of time, you have to reload/restart your flutter dart code with re-initializes the app’s state

In development mode, Flutter is compiled just-in-time. That is why we can do hot-reload/restart so fast. In release mode (when you go to publish your app), your code is compiled ahead-of-time, to native code. It is for better performace, minimum size and remove other stuff that are useful in dev mode.

What is different between hot reload, hot restart and full restart?

Hot reload: Here it only re build the widget tree where changes has occurred, keeping the app state as it was before hot reload, this does not re run the main() or the initState() of the dart code.

Hot Restart: This will restarts the flutter dart code and it also forget and rebuild the app state, all the previous app state will get lost when hot restart is preformed.

Full restart: In flutter full restart it recompile full project source code for ios, Android, Web that why it may take some longer time because it need to compile the java/Kotlin/objC and swift code etc.

Android Instant run

In android studio instant run same a flutter reload but instant run will always compiles the class fully.

Instant run the VM will checks if a new class change is been made.

Android Studio  instant run will try it’s best to change as little as possible, if it can change some part of classes then it will, but it often needs to replace the entire activity and sometimes the entire app will get rebuilt.

Recommended Flutter Articles

Pros of Flutter. Why flutter app development is best?

Future of Flutter app development

Why is Flutter trending in 2021