'Flutter Deserialize a JSON and save it locally
On the following code, is how i am fetching and saving the Json localy. On the console i can see the Json as follows. {"cyclus":29,"range":50,"force":-15.25071}
I can decode the data, and check for the key if it exists or not. But right now i do not know how to call the values of the key´s and display the values
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:web_socket_channel/io.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:async';
import 'dart:io';
const String fileName = 'myJsonPotyFile.json';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: WebSocketPOTY(),
);
}
}
//apply this class on home: attribute at MaterialApp()
class WebSocketPOTY extends StatefulWidget {
const WebSocketPOTY({Key? key}) : super(key: key);
@override
State<StatefulWidget> createState() {
return _WebSocketDHT();
}
}
class _WebSocketDHT extends State<WebSocketPOTY> {
late String potenty1;
late String potenty2;
late IOWebSocketChannel channel;
late bool connected; //boolean value to track if WebSocket is connected
late File _filePath;
Future<String> get _localPath async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
Future<File> get _localFile async {
final path = await _localPath;
return File('$path/$fileName');
}
void _readJson() async {
_filePath = await _localFile;
}
@override
void initState() {
_readJson();
connected = false; //initially connection status is "NO" so its FALSE
potenty1 = "0";
potenty2 = "0";
Future.delayed(Duration.zero, () async {
channelconnect();
});
super.initState();
}
channelconnect() {
try {
channel = IOWebSocketChannel.connect("ws://192.168.0.254:80");
channel.stream.listen(
(message) {
print(message);
Map<String, dynamic> jsondat = json.decode(message);
String data = json.encode(jsondat);
_filePath.writeAsString(data);
setState(() {
if (jsondat.containsKey('cyclus')) {
connected = true;
} else if (jsondat.containsKey('range')) {
setState(() {
potenty1 = jsondat['force'];
potenty2 = jsondat['range'];
//_filePath.writeAsString(message);
});
}
});
},
onDone: () {
//if WebSocket is disconnected
print("Web socket is closed");
setState(() {
connected = false;
});
},
onError: (error) {
print(error.toString());
},
);
} catch (_) {
print("error on connecting to websocket.");
}
}
Future<void> sendcmd(String cmd) async {
if (connected == true) {
channel.sink.add(cmd); //sending Command to NodeMCU
//send command to NodeMCU
} else {
channelconnect();
print("Websocket is not connected.");
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Poty"),
backgroundColor: const Color.fromARGB(255, 30, 89, 106)),
body: Container(
alignment: Alignment.topCenter, //inner widget alignment to center
padding: const EdgeInsets.all(20),
child: Column(
children: [
Container(
//showing if websocket is connected or disconnected
child: connected
? const Text(
"WEBSOCKET: CONNECTED",
style: TextStyle(fontSize: 18),
)
: const Text(
"DISCONNECTED",
style: TextStyle(fontSize: 18),
)),
const SizedBox(
height: 50,
),
Text(
"Poty1 Value $potenty1 Milimeter",
style: const TextStyle(fontSize: 18),
),
const SizedBox(
height: 20,
),
Text(
"Poty2 Value $potenty2 Newton",
style: const TextStyle(fontSize: 18),
),
],
)),
);
}
}
Solution 1:[1]
You can convert jsonData of type Map<String, dynamic> to a String using:
String data = json.encode(jsondata);
Now, you can store this data string locally. You can use Shared Preferences or Get Storage for local storage.
https://pub.dev/packages/shared_preferences
https://pub.dev/packages/get_storage
For getting data, again you can use
json.decode(data);
data is the string that you will read from local storage.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Waqar Ali Siyal |
