I need some suggestions or help please. I am trying to do a small real time chat application, most tutorials that I have been looking basically use firebase, but I have been using MySQL already for other parts of my small projects, I am not sure if I understood Stream
correctly, but as far as I know I think that the data does keep fetching, I tried it but it didn't update the new data, and besides StreamBuilder
being a little hard to use, I went for the easiest method using a regular http and displaying it by using a function which will be run at the initiation of page like this:
void initState() {
super.initState();
_getChat();
}
_getChat() {
Pulling.getChatsContents().then((value) {
setState(() {
_chatContent = value;
_chatLength = "${value.length}";
});
});
}
Storing them here:
List<Chats> _chatContent;
String _chatLength = '0';
where the List<Chats>
is the following:
class Chats {
final String senderid;
final String msgcontent;
Chats(
{this.senderid,
this.msgcontent});
factory Chats.fromJson(Map<String, dynamic> json) {
return Chats(
senderid: json['sender_id'] as String,
msgcontent: json['msg_content'] as String,
);
}
}
and the Pulling
is:
class Pulling {
static const ROOT = 'https://example.com/chatsContent.php';
static StreamController streamChat = StreamController();
static Future<List<Chats>> getChatsContents() async {
try {
var myUser = '2';
var map = Map<String, dynamic>();
map['user'] = myUser;
final response = await http.post(ROOT, body: map);
if (200 == response.statusCode) {
final chatsParsed =
json.decode(response.body).cast<Map<String, dynamic>>();
List<Chats> listChat =
chatsParsed.map<Chats>((json) => Chats.fromJson(json)).toList();
return listChat;
} else {
return List<Chats>();
}
} catch (e) {
return List<Chats>();
}
}
}
So basically with all these I am getting the data and displaying, but when new data is added, I do not get the update, there may be a way to do it with Stream
, but I am actually quite confused combining it with http
, so I was thinking if it is possible and if it is efficient for the app if I added this to the void initState:
_timer = Timer.periodic(Duration(seconds: 1), (timer) => _getChat());
also calling _timer
at the beginning:
Timer _timer;
Thank you guys for reading all this and helping me!
UPDATE
The way that I display the fetched data is as follows:
return Column(
children: [
for (var i = 0; i < int.parse(_chatLength); i++)
Container(
child: Text(_chatContent[i].msgcontent),
),
]);