Reputation: 109
I recive data from datareciver listener and added to my object list but I cant upload listview from another class. So is there a listener for listview to update when data recive.
I put all my class and code
ContentModel.dart -which is my Model
class ContentModel{
String dialogID;
DialogModel(this.dialogID);
}
Global.dart --Global class to store list
class Globals {
static List<ContentModel> dialogList =new List<ContentModel>();
}
main.dart --main view to display my list when its recive
List<ContentModel> _contentModel = Globals.dialogList;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child:ListView.builder(
padding: EdgeInsets.symmetric(horizontal: 12.0),
itemCount:_contentModel.length,
reverse: false,
controller: _scrollController,
itemBuilder: (BuildContext context, index) =>
buildChat(_contentModel[index]))
));
}
DataReciver.dart --Data reciver can recive any time and save it on global list
class QuickBloxListenerManager{
onMassageRecive(Function fun) async
{
try {
await QB.chat.subscribeChatEvent(QBChatEvents.RECEIVED_NEW_MESSAGE,
(data) {
print( "New Message Arrive...");
Map<String, Object> map = new Map<String, dynamic>.from(data);
Map<String, Object> payload =
new Map<String, dynamic>.from(map["payload"]);
ContentModel newMsg = new ContentModel();
newMsg.dialogID=payload['id'];
Globals.messageList.messages.add(newMsg);
}, onErrorMethod: (error) {
});
} on PlatformException catch (e) {
}
}
}
Upvotes: 0
Views: 4270
Reputation: 3326
You can look into the StreamBuilder, which is a widget very common in Flutter apps to update the UI based on data change. In this case, you can implement the flow of your app like this:
import 'dart:async';
class QuickBloxListenerManager{
final _controller = StreamController<List<ContentModel>>();
Stream<List<ContentModel>> contentModelStream => _controller.stream;
// ... other lines
}
onMassageRecive() async {
try {
// ... other lines
newMsg.dialogID=payload['id'];
// Here I'm seeing you're quoting the dialogList, so I will use that list in the code
Globals.dialogList.add(newMsg);
_controller.add(Globals.dialogList);
// ... other lines
}
class SomeScreen extends StatefulWidget {
// ... other lines
// Initiate your QuickBloxListenerManager class
final QuickBloxListenerManager _manager = QuickBloxListenerManager();
// Get your data in the initState()
@override
initState() {
super.initState();
_manager.onMassageRecive();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
child: StreamBuilder<List<ContentModel>>(
stream: _manager.contentModelStream,
builder: (context, snapshot) {
if (!snapshot.hasData) return Container();
List<ContentModel> _contentModel = snapshot.data;
return ListView.builder(
padding: EdgeInsets.symmetric(horizontal: 12.0),
itemCount:_contentModel.length,
reverse: false,
controller: _scrollController,
itemBuilder: (BuildContext context, index) =>
buildChat(_contentModel[index]))
)
);
}
);
}
}
Upvotes: 4