Flutter allows you to easily implement local storage. Below is the sample code for local storage in flutter.
The sample code below we used the path_provider package to access the device’s file system. We also use the file class to manipulate files. Also, use the jsonEncode() method to convert the data to json format. I also use a textfield widget to let the user enter data and re-render when the state changes.
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
void main() {
runapp(myapp());
}
class myapp extends statefulwidget {
@override
_myappstate createstate() => _myappstate();
}
class _myappstate extends state<myapp> {
string _text = '';
@override
void initstate() {
super.initstate();
_loaddata();
}
void _loaddata() async {
final directory = await getapplicationdocumentsdirectory();
final file = file('${directory.path}/data.txt');
if (await file.exists()) {
final data = jsondecode(await file.readasstring());
setstate(() {
_text = data['text'];
});
} else {
setstate(() {
_text = 'no data';
});
}
}
void _savedata() async {
final directory = await getapplicationdocumentsdirectory();
final file = file('${directory.path}/data.txt');
await file.writeasstring(jsonencode({'text': _text}));
}
@override
widget build(buildcontext context) {
return materialapp(
title: 'flutter local storage',
theme: themedata(
primaryswatch: colors.blue,
visualdensity: visualdensity.adaptiveplatformdensity,
),
home: scaffold(
appbar: appbar(
title: text('flutter local storage'),
),
body: center(
child: textfield(
decoration: inputdecoration(hinttext: 'enter text'),
onchanged: (text) {
setstate(() {
_text = text;
});
},
),
),
floatingactionbutton: floatingactionbutton(
child: icon(icons.save),
onpressed: _savedata,
),
),
);
}
}