I had a problem to read a data from a stream socket. After receiveing data in a websocket call, I want put all my content in a variable and start to using that wariable. Instead, I can print only the last string line in the body of the app. To socket connect I use socket.io-client dependency version ^1.0.1 and it works. The problem is the next step, how can get the data from the socket.
I can I print all the content of the StreamSocket?
import 'package:flutter/material.dart';
import 'package:vincenzakart/widget/navigationdrawerwidget.dart';
import 'package:socket_io_client/socket_io_client.dart' as IO;
import 'dart:async';
import 'dart:io';
class PilotiPage extends StatefulWidget {
const PilotiPage({Key? key}) : super(key: key);
@override
PilotiPageState createState() => PilotiPageState();
}
StreamSocket streamSocket = StreamSocket();
var datiDaServer;
class PilotiPageState extends State<PilotiPage> {
@override
void initState() {
super.initState();
initSocket();
}
@override
Widget build(BuildContext context) => Scaffold(
drawer: const NavigationDrawerWidget(),
appBar: AppBar(
title: const Text('Piloti'),
centerTitle: true,
backgroundColor: Colors.black12,
),
body: Container(
child: StreamBuilder(
stream: streamSocket.getResponse,
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
return Column(
children: [
Text(datiDaServer.toString()),
],
);
},
),
),
);
}
@override
void initSocket() {
connectAndListen();
}
// STEP1: Stream setup
class StreamSocket {
final _socketResponse = StreamController<String>();
void Function(String) get addResponse => _socketResponse.sink.add;
Stream<String> get getResponse => _socketResponse.stream;
void dispose() {
_socketResponse.close();
}
}
void connectAndListen() {
IO.Socket socket = IO.io('http://192.168.110.204:3999',
IO.OptionBuilder().setTransports(['websocket']).build());
socket.connect();
socket.onConnect((_) {
print('connect socket.io');
print(socket.id);
});
//When an event recieved from server, data is added to the stream
socket.on('message', (data) => streamSocket.addResponse);
socket.on('message', (data) {
print(data.toString());
print(data.toString().length);
datiDaServer = data;
});
socket.onDisconnect((_) => print('disconnect'));
}