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 “{}”
Keys : This will return all the key in map object.
Values : Wiil return all the value in map object.
length : Return the number of key-value pair length/size.
isEmpty : Will return true if Map object is empty.
IsNotEmpty : Will return true if map value is not empty.
Function of Map dart
There are some comman task performed with Map in dart:
addAll() : Used to add all key-value of some other Map Object.
clean() : Remove all data from pair.
remove() : Remove Specific date of key.
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
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
foreach : Example
By using foreach function in Map you can easily iterate and read all the maps entries.
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 String, int, double, Map, and a list of values/arrays.
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
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
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
In your flutter project structure you will find a file by name “pubspec.yaml” file,
Open it & under dependencies section add getxand get_storage package
dependencies:
get_storage: ^1.3.2
get:
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?
Initialization To Initialize storage, you must call GetStorage.init() method before loading the app / before calling runApp
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
Create a Instance of get Storage class
final datacount = GetStorage(); // instance of getStorage class
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);
Here count is key and _count is a value.
How to read value from key To read values you need to use “read”
Example:
datacount.read('count')
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
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.
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.
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{
}
}
}
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 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
}
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.