close

How to save to local storage using Flutter?


How to use local storage to save data for offline fetching?

Is it accurate to say that you are a novice to shudder application advancement? furthermore, you have done investigating UI part of your application and now wishing to get to neighborhood stockpiling of your cell phone to store information?

At that point, this instructional exercise has contacted you at an ideal time!

Image for post
Courtesy of Dribbble — Data Storage

Why do we need to store data at mobile local storage?

At the point when we construct online applications, we simply incorporate our application with Firebase or other online information bases to deal with our information. It loads up the information into our application while dispatching it just when we have a web association empowered. Imagine a scenario where we need to assemble disconnected applications which should show up information in any event, when there is no web association accessible.

The best way is to write the data into a local file and read it when we launch it.

Image for post
Courtesy of Dribbble — Offline data

Hereafter say no to No internet connection error message and just continue to view your offline data! 😉

How to read and write data at the local disk using Flutter?

Presently, we will peruse and compose information of our Flutter application to a neighborhood record. This heaps the information from that record while dispatching the application.

Beginning!

Open your favored IDE for composing Dart code. I’m utilizing Visual Studio Code.

Add path_provider bundle:

Initially, we need to import the path_provider bundle, which permits us to get to ordinarily utilized areas on the gadget’s filesystem.

Update your pubspec.yaml record:

dependencies:
  flutter:
    sdk: flutter
  path_provider: #add this in yours

This module upholds admittance to two filesystem areas: 1. Transitory registry, 2. Reports registry.

— The brief index is the reserve and its substance might be deleted by the framework whenever. Thus, putting away information here isn’t beneficial for us to get it later.

— The records catalog is the one we to pick now, this is a registry for the application to store documents that no one but it can get to.

Locate the neighborhood way:

This present module’s getApplicationDocumentsDirectory() strategy is utilized to get that organizer way where the application puts its records and that can be erased simply by that application. On account of Android, its AppData organizer where our application related records will be put away. How about we compose a capacity for that getting it,

Future<String> get _localPath async {
  final directory = await getApplicationDocumentsDirectory();
  // For your reference print the AppDoc directory 
  print(directory.path);
 return directory.path;
}

Make a reference to the record area:

Subsequent to realizing where to put our record, how about we make a reference to the document area utilizing theFile class from the dart:io library. We are naming our record as data.txt.

Future<File> get _localFile async {
  final path = await _localPath;
  return File('$path/data.txt');
}

Compose information to that record:

Presently we have effectively made a record data.txt to work with. From now on we need to make capacities to peruse and compose the information into that document.To start with, we should make writeContent() work.

Future<File> writeContent() async {
  final file = await _localFile;
  // Write the file
  return file.writeAsString('Hello Folks');
}

Calling this capacity will just compose the string ‘Hi Folks’ into the document data.txt.

Peruse information from the record:

We will make a capacity for perusing the substance of the record and name it as readContent().

Future<String> readcontent() async {
  try {
    final file = await _localFile;
    // Read the file
    String contents = await file.readAsString();
    return contents;
  } catch (e) {
    // If there is an error reading, return a default String
    return 'Error';
  }
}

Calling this capacity will peruse the substance of the record data.txt and return this String esteem. If there should be an occurrence of any mistake in perusing the record, it will send ‘Blunder’.

As of now, we are finished with the rationale of perusing and composing information from and to the record at nearby capacity.

All together!

For our last demo,

— we call writeContent(), which we have just composed inside the initState() strategy for the Stateful gadget. initState() is a capacity that will be considered just a single time subsequent to dispatching the application. This will compose the String ‘Hi Folks’ into the document data.txt at neighborhood stockpiling.

— Then we read this String from the document and set the returned substance to a String variable information, which we will show in our App UI.

— Create a gadget and show the estimation of the variable information.

Complete code

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

void main() {
  runApp(
    MaterialApp(
      title: 'Reading and Writing Files',
      home: MyApp(),
    ),
  );
}

class MyApp extends StatefulWidget {
  @override
  _AppState createState() => _AppState();
}

class _AppState extends State<MyApp> {
  String data;

  Future<String> get _localPath async {
    final directory = await getApplicationDocumentsDirectory();
    print(directory.path);
    return directory.path;
  }

  Future<File> get _localFile async {
    final path = await _localPath;
    return File('$path/counter.txt');
  }

  Future<String> readContent() async {
    try {
      final file = await _localFile;
      // Read the file
      String contents = await file.readAsString();
      // Returning the contents of the file
      return contents;
    } catch (e) {
      // If encountering an error, return
      return 'Error!';
    }
  }

  Future<File> writeContent() async {
    final file = await _localFile;
    // Write the file
    return file.writeAsString('Hello Folk');
  }

  @override
  void initState() {
    super.initState();
    writeContent();
    readContent().then((String value) {
      setState(() {
        data = value;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Reading and Writing data')),
      body: Center(
        child: Text(
          'Data read from a file: \n $data',
        ),
      ),
    );
  }
}

Complete code

Simply reorder it in your manager and rush to perceive how it functions.

Image for post
Screenshot of the Output UI

This is simply to toss some light for seeing how to get to nearby capacity and perused/compose while working with a Flutter application, you can take this to a degree where you need to show the disconnected information in your application. Alter the code as per your need. ✌

In the event that you locate this instructional exercise helpful, remember to click/tap on the 👏 button as long as possible. :- ) Follow to get all the more intriguing instructional exercises on Flutter. See different instructional exercises,

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also Read

Leave a Comment