Home Blog Page 59

Now Develop Flutter App Online using FlutLab IDE

0
Flutlab online IDE for flutter application development
Flutlab online IDE for flutter application development

Hi Guys, Welcome to Proto Coders Point.

Recently, I found out an online IDE for Flutter development named FlutLab.

Whom this Flutter Online Editor (IDE) is best for

Flutlab Flutter IDE online is best for beginners in flutter, who wants to learn & build cross platform applicatiion using flutter online editor.

FlutLab is very useful online IDE, for flutter developer who don’t have good laptop/computer configuration, and Android Studio IDE or any other IDE runs very slow and can’t handle Flutter SDK because of low PC config.

This Flutter online IDE tool, is best to learn flutter application development online without installing any IDE.

What do you need to use flutlab.io

All you need is:-

  1. A Good Internet Connection.
  2. Laptop/Computer(No, need of high System Config)
  3. Any Browser( Google Chrome, Firebox…)

And that all you need…!!

Introduction to FlutLab.io

The Flutlab.io is basically a online IDE for developing flutter app online. It is a flutter bootstrapping project developed by CodeGemz S.R.O team.

By using which a flutter developers can develop complete cross-platform app without even installing any software on his PC( He just need a Browser to use Flut Lab).

This Flutlab UI is so smooth that you get experience like you are developing flutter app in your local computer.

Is flutlab free to use?

YES, is it FREE, with some limitation, If you want you can go with premium paid plan.

In Free Starter Plan

  • You can create max 2 flutter project.
  • Storage limit is 250 Mb.

In Flutlab Premium

What is a Premium account?

  • Access to high-performance dedicated IOS, Android, and Web builders.
  • Build priority before regular and anonymous users.
  • Unlimited project lifetime.
  • Up to 1 GB of Storage.
  • Up to 10 team members in one project.
  • Up to 10 projects in your profile.
  • Signing builds for app markets.
  • Private GitHub, Bitbucket, and GitLab repositories.
  • Private tech support.

What is the price of Premium?

  • It starts from $5 per month.

Video Introduction

Let’s Get Started

We will cover how to use and setup FlutLab in 4 Steps/Section:-

Step 1: Visit FlutLab.io for SignUp

Flut lab Welcome Page will look as below

flutlab welcome home page online IDE
  • if you want to try it out without signin, you can do it by just clicking on Get Started, but note that your project will not get saved for future updates.

Creating Account in flutlab

let’s create account, click on signup button

  • SignIn with Google Account, if you want flutlab project to get saved for future editing
  • Fill the signup form & complete account verification process
  • Visit gmail account to complete account verification

Now, After successful account verification, you can login & start creating flutter project using FlutLab.io

Note: With free acount you have limitation of 2 projects & 250 mb storage, whih is more then enough for learning purpose & basic mini flutter project


Step 2: Create First project in FlutLab.io

Now, Let’s create a project by clicking on project button.

  • Just, Select codebase from dropdown, Their are 8 codebase provided for you, select anyone.
  • Give name to project.
  • Give package name & create Project
  • Then, once project is created click on it open the project.

Step 3: Flutter Online IDE – FlutLab UI interfect

if you observe the UI interface of Flutlab, it similar to android Studio/ VSCode.

Step 4: Running Flutter project on Flutlab Emulator

  • You can simple make changes in code & run the project by clicking on play button on left side of interface.
  • As you hover on play button it gives you option on how you want to build flutter project, for now simply select web & run.
  • Once you click on play/run button, flutter lab IDE will compile your project & start working on it, it may take 1 min or more to build for first time.
  • After building process is completed, it will automatically load a Emulator for you, on which your app will run.

Hurrayy…!!, you have successfully run your first flutter project on FlutLab.io.


Feature provided by flutlab Flutter IDE

  • Hot Reload: Reload change made in app code in seconds.
  • VCS integration: connect to github/bitbucket and more…
  • Firebase: Connect to Firebase Console.
  • Emulator: Test app in flutLab Emulator.
  • FlutLab Installer: Flut lab provides you flutlab instraller android app that help you to test app on real devices.

Flutter get current location address from latitude & Longitude – geolocator

0
geo locator get latitude longitude to full address
geo locator get latitude longitude to full address

Hi Guys, Welcome to Proto Coders Point.

In this Flutter Tutorial Article, Will learn how to get current location coordinates (latitude & Longitude) in flutter & also get location address name from lat & long coordinates.

When you are working on service based app such as E-Commerce, Delivery then you need get user’s current location to provide your services to user location.
Therefore, you need to implement GeoLocation in your flutter project, so you are here looking for best tutorial for implementing GeoLocation into your flutter app.

Today, In this flutter Article, We’ll go through implementing geolocation to get latitude & longitude of a device current location & also get full address details based on current location lat & long in flutter.

Video Tutorial on Flutter GeoLocation – Example

Package used to get current location in flutter

To get current location in flutter we will make use of 2 flutter package.

  • GeoLocator: To get user’s device present location Latitude & Longitude in flutter.
  • GeoCoding: To get location address using lat & long coordinates (placemarkfromcoordinates) (lat long to address)

So let’s begin, without wasting more time.

Start by creating new flutter project or by opening existing project where you want to implement Locations Services.

1. Adding location package in flutter pubspec.yaml file

Open pubspec.yaml file in your flutter project & under dependencies section add this 2 packages (geolocator & geocoding).

dependencies:
  geolocator: #latest version
  geocoding:  #latest version

then hit pub get button or run command flutter put get


2. Location access permission in Android & iOS

Android

android > app > src > main > AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

iOS

ios > Runner > Info.plist

    <key>NSLocationAlwaysUsageDescription</key>
    <string>Needed to access location</string>
    <key>NSLocationWhenInUseUsageDescription</key>
    <string>Needed to access location</string>

3. Flutter method to get current user latitude & longitude location

The below method will return location position from which we can extract lat & long coordinates points.

Future<Position> _getGeoLocationPosition() async {
    bool serviceEnabled;
    LocationPermission permission;

    // Test if location services are enabled.
    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      // Location services are not enabled don't continue
      // accessing the position and request users of the
      // App to enable the location services.
      await Geolocator.openLocationSettings();
      return Future.error('Location services are disabled.');
    }

    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
      
        return Future.error('Location permissions are denied');
      }
    }

    if (permission == LocationPermission.deniedForever) {
      // Permissions are denied forever, handle appropriately.
      return Future.error(
          'Location permissions are permanently denied, we cannot request permissions.');
    }

    // When we reach here, permissions are granted and we can
    // continue accessing the position of the device.
    return await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
  }

And the above method can also handle turning on geolocation in device (if off) & also ask permission from user to ACCESS_FINE_LOCATION.


4. Method to get full address from latitude & longitude co-ordinates (lat long to address)

The below method will receive parameter i.e. location position by using which we can convert lat long to address.

Future<void> GetAddressFromLatLong(Position position)async {
    List<Placemark> placemarks = await placemarkFromCoordinates(position.latitude, position.longitude);
    print(placemarks);
    Placemark place = placemarks[0];
    Address = '${place.street}, ${place.subLocality}, ${place.locality}, ${place.postalCode}, ${place.country}';
    
  }


Complete Code – Flutter get latitude & longitude then convert lat long to address

main.dart

import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:geocoding/geocoding.dart';

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

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

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

class Homepage extends StatefulWidget {
  const Homepage({Key? key}) : super(key: key);

  @override
  _HomepageState createState() => _HomepageState();
}

class _HomepageState extends State<Homepage> {

  String location ='Null, Press Button';
  String Address = 'search';

  Future<Position> _getGeoLocationPosition() async {
    bool serviceEnabled;
    LocationPermission permission;

    // Test if location services are enabled.
    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      // Location services are not enabled don't continue
      // accessing the position and request users of the
      // App to enable the location services.
      await Geolocator.openLocationSettings();
      return Future.error('Location services are disabled.');
    }

    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        // Permissions are denied, next time you could try
        // requesting permissions again (this is also where
        // Android's shouldShowRequestPermissionRationale
        // returned true. According to Android guidelines
        // your App should show an explanatory UI now.
        return Future.error('Location permissions are denied');
      }
    }

    if (permission == LocationPermission.deniedForever) {
      // Permissions are denied forever, handle appropriately.
      return Future.error(
          'Location permissions are permanently denied, we cannot request permissions.');
    }

    // When we reach here, permissions are granted and we can
    // continue accessing the position of the device.
    return await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
  }

  Future<void> GetAddressFromLatLong(Position position)async {
    List<Placemark> placemarks = await placemarkFromCoordinates(position.latitude, position.longitude);
    print(placemarks);
    Placemark place = placemarks[0];
    Address = '${place.street}, ${place.subLocality}, ${place.locality}, ${place.postalCode}, ${place.country}';
    setState(()  {
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Coordinates Points',style: TextStyle(fontSize: 22,fontWeight: FontWeight.bold),),
            SizedBox(height: 10,),
            Text(location,style: TextStyle(color: Colors.black,fontSize: 16),),
            SizedBox(height: 10,),
            Text('ADDRESS',style: TextStyle(fontSize: 22,fontWeight: FontWeight.bold),),
            SizedBox(height: 10,),
            Text('${Address}'),
            ElevatedButton(onPressed: () async{
              Position position = await _getGeoLocationPosition();
              location ='Lat: ${position.latitude} , Long: ${position.longitude}';
              GetAddressFromLatLong(position);
            }, child: Text('Get Location'))
          ],
        ),
      ),
    );
  }
}

Output

Flutter Dart Stream Basic Example – Fetch Crypto Currency API Data

0
Flutter Streams

Hi Guys, Welcome to Proto Coders Point.

In this Flutter Tutorial, We will learn what is flutter dart streams, How to use it in flutter app, and When to use flutter stream in app.

In Dart, Asynchronous programming is been characterized by Future & Streams.

In this Flutter Article let’s learn about dart streams.

What is a Stream in flutter dart?

A Dart Stream uses Asynchronous Programming concept, A Stream in dart is a sequence of asynchronous event that is been served to user, when any update occurs in data flow through Stream sink.

means, Instead of getting the next data or event manually by asking for it, The dart stream will automatically update the UI about the event, when it’s ready to be served.

Let’s Understand Stream in easiest way.

A Stream in nothing but a continuous async flow of data or event.

Here is a Animation on How data flow through stream in dart flutter.

A Data keep on flowing in stream during the life cycle of a stream.

There are 2 point which are associated to a Stream.

  • Sink
  • Source

1. Sink: In Flutter Streams, a Sink is a point from where we can add data into the stream pipe.

2. Source: In Flutter Stream, a Source is a point from where we can keep listening to stream data or get the data that is been added into the stream.


How to Create our own Stream in flutter.

Most of the tme, you’re going to working with dart streams, being created for you in background, when you use any extrenal libraries such as State Management (GetX, Bloc, Provider… and so on). But you can make your own stream by using StreamController in dart.

Let’s Create StreamController & add data to it using sink.add() (put stream)

//Create Stream
StreamController _controller = StreamController();
int _counter = 60;

// add event/data to stream controller using sink
 _controller.sink.add(_counter);

Listening to stream using StreamBuilder Widget

Now, we are done with creating stream & adding data into it, now we need to listen to the data coming into stream & print the data on the screen, so for that we are going to make use of StreamBuilder widget to listen to asynchronous event.

StreamBuilder(
initialData: _counter,
stream: _controller.stream,
builder: (context,snapshot){
return Text('${snapshot.data}');
}
),

Stream Basic – Example 1

Count Down Value using Stream in flutter

Flutter Streams Basic – Count Down using StreamController & StreamBuilder

Example 1: In this Flutter StreamController Example, We will simply build an app that can count down a value from n to 0 using stream Controller sink & update the UI.

Video Tutorial

main.dart

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

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

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

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

class CounterApp extends StatefulWidget {
  const CounterApp({Key? key}) : super(key: key);

  @override
  _CounterAppState createState() => _CounterAppState();
}

class _CounterAppState extends State<CounterApp> {

  //create instance of streamcontroller class
  StreamController _controller = StreamController();
  int _counter = 60;

  void StartTimer() async{
    //Timer Method that runs every second
    Timer.periodic(Duration(seconds: 1), (timer) {
      _counter--;

      // add event/data to stream controller using sink
      _controller.sink.add(_counter);

      //will stop Count Down Timer when _counter value is 0
      if(_counter<=0){
        timer.cancel();
        _controller.close();
      }
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
     // Destroy the Stream Controller when use exit the app
    _controller.close();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            StreamBuilder(
              initialData: _counter,
              stream: _controller.stream,
                builder: (context,snapshot){
                return Text('${snapshot.data}');
                }
            ),
            SizedBox(
              height: 20,
            ),
            ElevatedButton(onPressed: (){
              //start the timer
              StartTimer();
            }, child: Text('Start Count Down'))
          ],
        ),
      ),
    );
  }
}


flutter Stream api – Example 2

Keep Fetching latest value of Crypto Currency using streams flutter

Dart Stream real time example – Fetch Crypto Currency price from API

Example 2: We will fetch data from Crypto Currency API & make use of flutter stream controller sink to add real time crypto currency data & update the UI using StreamBuilder widget.

As you know, Crypto Currency price/value keeps on changing very secondsm so crypto currency API is the best example to learn Flutter dart Stream.

Video Tutorial

API used:

https://api.nomics.com/v1/currencies/ticker?key=your_api_key&ids=BTC

The API gives us lot’s of JSON data of Crypto Currency, but we are using only 3 fields ‘name’, ‘logo_url’, ‘price’.

Note: flutter http package is need to added to make network call to API

DataModel.dart

As we are using only 3 field, Here is a datamodel with 3 field ‘name’, ‘image’, ‘price’. that help in storing data.

class DataModel{
  String name;
  String image;
  String price;

  DataModel.fromJson(Map<String,dynamic> json)
      : name = json['name'],
        image=json['logo_url'],
        price=json['price'];

  //a method that convert object to json
  Map<String, dynamic> toJson() => {
    'name': name,
    'logo_url': image,
    'price':price
  };

}

main.dart

import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:flutter_svg/flutter_svg.dart';
import 'package:stream_example/DataModel.dart';

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

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

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

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

  //create stream
  StreamController<DataModel> _streamController = StreamController();

  @override
  void dispose() {
    // stop streaming when app close
    _streamController.close();
  }
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    // A Timer method that run every 3 seconds

    Timer.periodic(Duration(seconds: 3), (timer) {
      getCryptoPrice();
    });

  }

  // a future method that fetch data from API
  Future<void> getCryptoPrice() async{

    var url = Uri.parse('https://api.nomics.com/v1/currencies/ticker?key=your_api_key&ids=DOGE');

    final response = await http.get(url);
    final databody = json.decode(response.body).first;

    DataModel dataModel = new DataModel.fromJson(databody);

    // add API response to stream controller sink
    _streamController.sink.add(dataModel);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: StreamBuilder<DataModel>(
          stream: _streamController.stream,
          builder: (context,snapdata){
             switch(snapdata.connectionState){
               case ConnectionState.waiting: return Center(child: CircularProgressIndicator(),);
               default: if(snapdata.hasError){
                 return Text('Please Wait....');
               }else{
                 return BuildCoinWidget(snapdata.data!);
               }
             }
          },
        ),
      ),
    );
  }

  Widget BuildCoinWidget(DataModel dataModel){
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text('${dataModel.name}',style: TextStyle(fontSize: 25),),
          SizedBox(height: 20,),
          SvgPicture.network('${dataModel.image}',width: 150,height: 150,),
          SizedBox(height: 20,),
          Text('\$${dataModel.price}',style: TextStyle(fontSize: 20,fontWeight: FontWeight.bold),)
        ],
      ),
    );
  }
}

output

Bitcoin price keep changing when API data get changed


How to Implement Read More / Read Less text in flutter

0

Hi Guys, Welcome to Proto Coders Point.

In this flutter tutorial, we will learn how to implement read more text button in flutter.

How to Create Read more Text / Show more text button in flutter

Read more text feature is implemented only when you have a huge length of text to be shown to the users, but you want to limit the maximum number of line to be displayed initially and then user can click on read more to show remaining text, and vice versa user can click on read less to shrink a text again to maxLine to be shown.

Video Tutorial

main.dart – Code implemented with read more button

Read the comment in below code to understand it ( else watch above youtube tutorial on the same)

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

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

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

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  // bool datatype to give toggle effect to button and 
  // depending on this bool value will show full text or 
  // limit the number of line to be viewed in text.
  bool isReadmore= false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Read More'),
        centerTitle: true,
      ),
      body: ListView(
        children: [
          Text('Read More Example',style: TextStyle(fontSize: 30),),
          //text widget to display long text
          buildText("It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like)."),
          ElevatedButton(onPressed: (){
            setState(() {
              // toggle the bool variable true or false
              isReadmore = !isReadmore;
            });
          }, child: Text((isReadmore?'Read Less' : 'Read More')))
        ],
      )
    );
  }

  Widget buildText(String text){
    
    // if read more is false then show only 3 lines from text
    // else show full text

    final lines = isReadmore ? null : 3;
    return Text(
      text,
      style: TextStyle(fontSize: 25),
      maxLines: lines,

      // overflow properties is used to show 3 dot in text widget
      // so that user can understand there are few more line to read.

      overflow: isReadmore ? TextOverflow.visible: TextOverflow.ellipsis,
    );
  }

}



Output

How to store/save class Data Model object data in SharedPreferences

0
how to save data model object data in sharedpreferences flutter

Hi Guys, Welcome to Proto Coders Point.

In this Flutter tutorial, We will learn how to store a data model object data in sharedPreferences in flutter.

Note: Firstly you need to serialize data to JSON String before saving it & the de-serialize it after reading.

Read this flutter article on JSON and serialization in flutter
https://flutter.dev/docs/development/data-and-backend/json to learn more in details.


Let’s Serialize JSON inside model class ‘User’

In ‘User’ data model class you will find 3 fields: name, email, phone & it also has a constructor & a method as below:

User.fromJson(): A constructor used for constructing a user instance from a Map structure.

toJson(): A method, used to convert user instance into a map.

User.dart

class User {
  final String name;
  final String email;
  final String phone;

  User(this.name, this.email,this.phone);

  //constructor that convert json to object instance
  User.fromJson(Map<String, dynamic> json) : name = json['name'],  email = json['email'],phone = json['phone'];

  //a method that convert object to json
  Map<String, dynamic> toJson() => {
    'name': name,
    'email': email,
    'phone':phone
  };
}

Saving object data in sharedPreferences

To save data model object, we must first convert it into a JsonString.

After converting model object data into JSON String, we can easily store it a String datatype.

then, we are storing jsonString into a shared_Preferences with key-value pairs.

 void storeUserData(){

    //store the user entered data in user object
    User user1 = new User(_name.text, _email.text);

    // encode / convert object into json string
    String user = jsonEncode(user1);

    print(user);

    //save the data into sharedPreferences using key-value pairs
    sharedPreferences.setString('userdata', user);
    
  }

Reading the data from shared_preferences

Now, you need to get the data stored in sharedPreferences, so fetch the data from sharedPreferences & convert the JsonString into Map Structure using jsonDecode() method & then convert it back to User Instance Object.

& finally use object to get data from data model datatype
Eg: user.name, user.email, user.phone.

void initialGetSaved() async{
    sharedPreferences = await SharedPreferences.getInstance();
      
   // Read the data, decode it and store it in map structure
    Map<String,dynamic> jsondatais = jsonDecode(sharedPreferences.getString('userdata')!);

    //convert it into User object
    var user = User.fromJson(jsondatais);

    if(jsondatais.isNotEmpty){
      print(user.name);
      print(user.email);
      //set the sharedPreferences saved data to TextField
      _name.value =  TextEditingValue(text: user.name);
      _email.value =  TextEditingValue(text: user.email);
      _phone.value =  TextEditingValue(text: user.phone);
    }
    
  }

How to convert User object data to json string and store in shared Preferences

Complete App implementation starts here

Let’s create a form in flutter, where a user can enter his name, email & phone(this is just for a example i have took 3 field).

Start with creating a new flutter project in your favorite IDE, I use android studio to build flutter apps( you can use any IDE).

1. Add Shared Preferences dependencies

As we need to save user entered data from TextField in flutter, we will make use of sharedpreferences to save the users data in app.

add sharedpreferences package into your flutter project.

In project > pubspec.yaml file.

In pubspec.yaml, under dependencies section add shared_preferences package.

dependencies:
  shared_preferences: #any version else keep empty it will take latest version

& then hit pub get or run flutter pub get commend in IDE Terminal.

2. Create a Data Model class ‘ User’

User.dart

class User {
  final String name;
  final String email;
  final String phone;

  User(this.name, this.email,this.phone);

  //constructor that convert json to object instance
  User.fromJson(Map<String, dynamic> json) : name = json['name'],  email = json['email'],phone = json['phone'];

  //a method that convert object to json
  Map<String, dynamic> toJson() => {
    'name': name,
    'email': email,
    'phone':phone
  };
}

3. UI – TextField Form Entered data will be saved until final submission

In main.dart page, we have 3 textfield, a Save Button & a submit button

3 TextField: user can enter name, email, phone.

Save Button: Saves the data entered in textfield for future, suppose if user leaves the app before final submission, After save button is press, the entered data in TextField will get saved and still exist even if user re-visit app in future.

Submit button: The submit will simply erase all the data from TextField & sharedpreferences will get cleared.

main.dart complete code

import 'dart:convert';

import 'package:datamodel_sharedpreferences/User.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.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> {


  late SharedPreferences sharedPreferences;
  
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    initialGetSaved();
  }

  void initialGetSaved() async{
    sharedPreferences = await SharedPreferences.getInstance();
    
    // Read the data, decode it and store it in map structure
    Map<String,dynamic> jsondatais = jsonDecode(sharedPreferences.getString('userdata')!);

    var user = User.fromJson(jsondatais);

    if(jsondatais.isNotEmpty){
      print(user.name);
      print(user.email);

      _name.value =  TextEditingValue(text: user.name);
      _email.value =  TextEditingValue(text: user.email);
      _phone.value =  TextEditingValue(text: user.phone);
    }

  }

  void storeUserData(){

    //store the user entered data in user object
    User user1 = new User(_name.text, _email.text,_phone.text);

    // encode / convert object into json string
    String user = jsonEncode(user1);

    print(user);

    //save the data into sharedPreferences using key-value pairs
    sharedPreferences.setString('userdata', user);

  }


  TextEditingController _name = new TextEditingController();
  TextEditingController _email = new TextEditingController();
  TextEditingController _phone = new TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Save DataModel Data JSON'),
      ),
      body: SingleChildScrollView(
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text('Full Form',style: TextStyle(fontSize: 32,fontWeight: FontWeight.bold),),
              Padding(
                padding: const EdgeInsets.all(16.0),
                child: Container(
                  height: 50,
                  child: TextField(
                    controller: _name,
                    decoration: InputDecoration(
                      border: OutlineInputBorder(),
                      labelText: 'Enter name'
                    ),
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(16.0),
                child: Container(
                  height: 50,
                  child: TextField(
                    controller: _email,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(),
                        labelText: 'Enter Email'
                    ),
                  ),
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(16.0),
                child: Container(
                  height: 50,
                  child: TextField(
                    controller: _phone,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(),
                        labelText: 'Enter Phone'
                    ),
                  ),
                ),
              ),
              ElevatedButton(onPressed: (){
                storeUserData();
              }, child: Text('SAVE')),
              ElevatedButton(onPressed: (){
                _name.value =  TextEditingValue(text: '');
                _email.value =  TextEditingValue(text: '');
                _phone.value =  TextEditingValue(text: '');
                sharedPreferences.remove('userdata');
              }, child: Text('SUBMIT'))
            ],
          ),
        ),
      ),
    );
  }
}

Shared Preferences alternative in flutter