'Updated Post. Fetching a Json with Websocket and display on the screen the values
On the console i can see the Json arriving as follows if i print it out {"cyclus":9,"range":1.681231022,"force":20.81800461}
Now i am not re-declaring the jsondat and used your approach. If i print out the values i can see them on the console like this.
flutter: 20.84395218 flutter: 1.609025955
If i comment //range = jsondat["force"]; and comment //force = jsondat["force"]; ....connected becomes true and on the console i see both values.
If i uncomment range = jsondat["force"]; and force = jsondat["force"]; i get on the console stuff like that.
#38 _CustomZone.runUnary (dart:async/zone.dart:1335:19) #39 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1244:7) #40 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11) #41 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7) #42 _SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:774:19)
setState(() {
if (jsondat.isNotEmpty){
connected = true;
print(jsondat["range"]);
print(jsondat["force"]);
//range = jsondat["force"];
//force = jsondat["force"];
}
});
Follows the code. Thanks in advance for some help
// ignore_for_file: avoid_print
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 = 'myJsonFile.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> {
String range = "0";
String force = "0";
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;
Future.delayed(Duration.zero, () async {
channelconnect();
});
super.initState();
}
channelconnect() {
try {
channel = IOWebSocketChannel.connect("ws://192.168.1.100:80");
channel.stream.listen(
(message) {
//print(message);
Map<String, dynamic> jsondat = jsonDecode(message);
//String data = jsonEncode(jsondat);
_filePath.writeAsString(message);
setState(() {
if (jsondat.isNotEmpty){
connected = true;
print(jsondat["range"]);
print(jsondat["force"]);
//range = (jsondat["force"]);
//force = jsondat["force"];
}
});
},
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(
"$range Milimeter",
style: const TextStyle(fontSize: 18),
),
const SizedBox(
height: 20,
),
Text(
" $force Newton",
style: const TextStyle(fontSize: 18),
),
],
)),
);
}
}
Solution 1:[1]
Firstly, why are you re-declaring jsondat?
Secondly, your json data {"cyclus":29,"range":50,"force":15.25071} contains cyclus which means your else if will never execute.
channel.stream.listen(
(message) {
print(message);
Map<String, dynamic> jsondat = jsonDecode(message); // Here
String data = jsonEncode(jsondat);
_filePath.writeAsString(data);
setState(() {
if (jsondat.containsKey('cyclus')) {
connected = true;
} else if (jsondat.containsKey('range')) {
Map<String, dynamic> jsondat = json.decode(message); // and Here
setState(() {
range = jsondat['range'];
force = jsondat['force'];
//_filePath.writeAsString(message);
});
}
});
},
Refactor it to be
channel = IOWebSocketChannel.connect("ws://192.168.0.254:80");
channel.stream.listen(
(message) {
print(message);
Map<String, dynamic> jsondat = jsonDecode(message);
String data = jsonEncode(jsondat);
_filePath.writeAsString(data);
setState(() {
if (jsondat.isNotEmpty) { // Or whatever method/technique you choose
connected = true;
range = jsondat['range'];
force = jsondat['force'];
//_filePath.writeAsString(message);
}
});
},
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 | Frank nike |
