title: how to make chat in real time with flutter by firebase ( ios )
body: <p>i made chat module for my flutter app between user and vendor for each order but in real iphones i need to back then open chat screen to see new message not real time </p>
  
  <p>how can i convert it to be real time so the user or vendor no need to go back then re open chat page to see new messages </p>
  
  <p>this is my codes </p>
  
  <p>user chat screen </p>
  
  <pre><code>import 'dart:async';
  import 'dart:io';
  import 'dart:math';
  import 'dart:convert';
  import 'dart:async' show Future;
  import 'package:http/http.dart' as http;
  import 'package:flutter/material.dart';
  import 'package:firebase_database/firebase_database.dart';
  import 'package:intl/intl.dart';
  import 'package:firebase_messaging/firebase_messaging.dart';
  import 'chat_model.dart';
  import 'chatmessage.dart';
  import 'package:flutter_local_notifications/flutter_local_notifications.dart';
  import 'package:uuid/uuid.dart';
  import 'package:keyboard_actions/keyboard_actions.dart';
  
  class ChatPage extends StatefulWidget {
    final String _userName;
    final String _id;
    final String _userid;
    final String _orderNo;
    final String vendorId;
  
    //widget.vendorId
  
    ChatPage(
        this._userName, this._id, this._userid, this._orderNo, this.vendorId);
  
    StreamSubscription _subscriptionTodo;
  
    @override
    _ChatPageState createState() =&gt; new _ChatPageState();
  }
  
  class _ChatPageState extends State&lt;ChatPage&gt; {
    static var databaseReference = FirebaseDatabase.instance.reference();
    var v_id;
    var vendor_id;
    var user_id;
    var vendor_name, vendor_token;
    final TextEditingController _chatController = new TextEditingController();
    final List&lt;ChatMessage&gt; _messages = &lt;ChatMessage&gt;[];
    List&lt;ChatModel&gt; list_messages = List&lt;ChatModel&gt;();
  
    DateTime now = DateTime.now();
    FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
    FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
    var chat_id_fr;
  
    Future onSelectNotification(String payload) {
      debugPrint("payload : $payload");
      showDialog(
        context: context,
        builder: (_) =&gt; new AlertDialog(
              title: new Text('Notification'),
              content: new Text('$payload'),
            ),
      );
    }
  
    @override
    void initState() {
      vendor_id = widget.vendorId;
      user_id = widget._userid;
  
      print(vendor_id + "ssssss");
  
      getDetails();
      getchat();
  
      flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
      var android = new AndroidInitializationSettings('@mipmap/ic_launcher');
      var iOS = new IOSInitializationSettings();
      var initSetttings = new InitializationSettings(android, iOS);
      flutterLocalNotificationsPlugin.initialize(initSetttings,
          onSelectNotification: onSelectNotification);
  
      //_firebaseMessaging.setAutoInitEnabled(enabled)
      _firebaseMessaging.configure(
        onLaunch: (Map&lt;String, dynamic&gt; message) {
          print('onLaunch called');
          showNotification("", "");
        },
        onResume: (Map&lt;String, dynamic&gt; message) {
          print('onResume called');
          showNotification("", "");
        },
        onMessage: (Map&lt;String, dynamic&gt; message) {
          print('onMessage called' + message.toString());
  
          Map msg_ = message['notification'];
          String body = msg_['body'];
          String title = msg_['title'];
  
  
          setState(() {
            ChatMessage message = new ChatMessage(
              text: body.toString(),
              vendor: "vendor",
              vendor_name: "",
            );
            print("msg===" + body.toString());
            print("msg===" + body.toString());
            _messages.insert(0, message);
            showNotification(body, title);
          });
  
        },
      );
      _firebaseMessaging.subscribeToTopic('all');
      _firebaseMessaging.requestNotificationPermissions(IosNotificationSettings(
        sound: true,
        badge: true,
        alert: true,
      ));
      _firebaseMessaging.onIosSettingsRegistered
          .listen((IosNotificationSettings settings) {
        print('Hello');
      });
      _firebaseMessaging.getToken().then((token) {});
    }
  
    showNotification(String body, String title) async {
      var android = new AndroidNotificationDetails(
          'channel id', 'channel NAME', 'CHANNEL DESCRIPTION',
          priority: Priority.High, importance: Importance.Max);
      var iOS = new IOSNotificationDetails();
      var platform = new NotificationDetails(android, iOS);
      await flutterLocalNotificationsPlugin
          .show(0, 'New Message', '$body', platform, payload: '$body');
    }
  
    Future&lt;String&gt; getDetails() async {
      FirebaseDatabase.instance
          .reference()
          .child("vendor")
          .child(vendor_id)
          .once()
          .then((DataSnapshot snapshot) {
        Map value = snapshot.value;
        var vendor_id_fr = value['id'];
        vendor_name = value['name'];
        vendor_token = value['token'];
  
        //Map&lt;String, dynamic&gt; data = map['Data'];
        print("name " + vendor_name);
        print("id " + vendor_id);
        print("token " + vendor_token);
      });
  
      return vendor_id.toString();
    }
  
    Future&lt;String&gt; getchat() async {
      FirebaseDatabase.instance
          .reference()
          .child("chat")
          .child(widget._orderNo)
          .once()
          .then((DataSnapshot snapshot) {
        Map value_ = snapshot.value;
        value_.forEach((key, value) {
          Map value_1 = value;
          chat_id_fr = value_1['chat_id'];
          var vendor_msg_fr = value_1['msg'];
          var user_id_ = value_['user_id'];
          var vendor_id_ = value_['vendor_id'];
  
          ChatModel chatModel = new ChatModel.fromJson(value);
  
          list_messages.add(chatModel);
          list_messages.sort((x, y) =&gt; x.chat_id_fr.compareTo(y.chat_id_fr));
  
  
        });
  
        var list_data = list_messages.toString();
  
        print(list_data.toString());
        // list_messages=list_messages.reversed.toList();
  
        int dfd = list_messages.length;
  
        for (int i = 0; i &lt;= list_messages.length; i++) {
          dfd = dfd - 1;
  
        /*  var value = list_messages.reduce((curr, next) =&gt; curr.chat_id_fr &gt; next.chat_id_fr ? curr : next);
          var value1 = list_messages.reduce((curr, next) =&gt; curr.chat_id_fr &gt; next.chat_id_fr ? curr : next);
  */
  
  
          if (list_messages
              .elementAt(dfd)
              .for_value
              .toString()
              .contains("user")) {
            setState(() {
              ChatMessage message = new ChatMessage(
                  text: list_messages.elementAt(dfd).msg,
                  vendor: "user",
                  vendor_name: vendor_name);
              _messages.add(message);
            });
          } else {
            setState(() {
              ChatMessage message = new ChatMessage(
                text: list_messages.elementAt(dfd).msg.toString(),
                vendor: "vendor",
                vendor_name: vendor_name,
              );
              _messages.add(message);
              //list_messages.reversed.toList();
            });
          }
        }
      });
  
      return vendor_id.toString();
    }
  
    Future&lt;http.Response&gt; postRequest(String msg) async {
      var url = 'https://fcm.googleapis.com/fcm/send';
  
      Map&lt;String, dynamic&gt; jsonMap = {
        'notification': {'body': '$msg', 'title': 'New Massage'},
        'to':
            'fPgRVKZY56Q:APA91bHEMQy1EKHbPUraCn2tCp2th6Oah5Xx_N7b-6wLiHWjjYG7WCaRmjwstR8_YaNukwA_mwZHuCpQoYKuXL7nQBMGPH3kw58vHth7FkXuyn-keW0JnNUZhDzlgV2RA9HraeW2M4R0',
      };
      Map&lt;String, dynamic&gt; jsonMap1 = {
        'notification': {'body': '$msg', 'title': 'New Massage'},
        'to': '$vendor_token',
      };
  
      //encode Map to JSON
      var body = json.encode(jsonMap1);
      var response = await http.post(url,
          headers: {
            "Content-Type": "application/json",
            "Authorization":
                "key=AAAAt08dld0:APA91bEY6Dtrb1x1SlAprnEYeSEUdCT0D0oq9qzlkLJDIJdB0-hVIbdKL_L6CysecmOb46gjD3lyZMKl5aGH4rY1daFYA838VMnS7SzumelXie3Vps7s8MkILRgz7Kj0QQ65Dp0uZLI6"
          },
          body: body);
      print("${response.statusCode}" + "=response=");
      print("${response.body}" + "=response=");
      return response;
    }
  
    void _handleSubmit(String text) {
      _chatController.clear();
  
      String formattedDate = DateFormat('kk:mm:ss').format(now).toString();
  
      var uuid = new Uuid();
  
      var rondm_no;
      var rng = new Random();
  
      for (var i = 0; i &lt; 10; i++) {
        print(rng.nextInt(100));
        rondm_no = uuid.v1().toString() + 'user_id';
      }
  
     // chat_id_fr = 0;
  
      if (_messages.length == 0) {
        databaseReference
            .child("chat")
            .child(widget._orderNo)
            .child('$rondm_no')
            .update({
          'vendor_id': vendor_id.toString(),
          'user_id': user_id.toString(),
          'msg': text.toString(),
          'chat_id': 0,
          'for_value': 'user',
        });
  
        setState(() {
          ChatMessage message = new ChatMessage(
            text: text.toString(),
            vendor: "user",
            vendor_name: "",
          );
          postRequest(text.toString());
          print("msg===" + text.toString());
          print("msg===" + text.toString());
          _messages.insert(0, message);
        });
      } else {
        for (var i = 0; i &lt; _messages.length; i++) {
          int chat_id_fr = i + 1;
  
          databaseReference
              .child("chat")
              .child(widget._orderNo)
              .child('$rondm_no')
              .update({
            'vendor_id': vendor_id.toString(),
            'user_id': user_id.toString(),
            'msg': text.toString(),
            'chat_id': chat_id_fr,
            'for_value': 'user',
          });
        }
  
        setState(() {
          ChatMessage message = new ChatMessage(
            text: text.toString(),
            vendor: "user",
            vendor_name: "",
          );
          postRequest(text.toString());
          print("msg===" + text.toString());
          print("msg===" + text.toString());
          _messages.insert(0, message);
        });
      }
  
  
    }
  
    Widget _chatEnvironment() {
      return IconTheme(
        data: new IconThemeData(color: Color(0xFF7872c0)),
        child: new Container(
          margin: const EdgeInsets.symmetric(horizontal: 8.0),
          child: new Row(
            children: &lt;Widget&gt;[
              new Flexible(
                child: new TextField(
                  decoration: new InputDecoration.collapsed(
                      hintText: "Starts typing ..."),
                  controller: _chatController,
                  onSubmitted: _handleSubmit,
                ),
              ),
              new Container(
                margin: const EdgeInsets.symmetric(horizontal: 4.0),
                child: new IconButton(
                  icon: new Icon(Icons.send),
                  onPressed: () =&gt; _handleSubmit(_chatController.text),
                ),
              )
            ],
          ),
        ),
      );
    }
  
    @override
    Widget build(BuildContext context) {
      return new Scaffold(
          appBar: new AppBar(
            title: new Text("المحادثة"), //Conversation
            backgroundColor: Color(0xFF7872c0),
          ),
          body: new Column(
            children: &lt;Widget&gt;[
              new Flexible(
                child: ListView.builder(
                  padding: new EdgeInsets.all(8.0),
                  reverse: true,
                  itemBuilder: (_, int index) =&gt; _messages[index],
                  itemCount: _messages.length,
                ),
              ),
              new Divider(
                height: 1.0,
              ),
              new Container(
                decoration: new BoxDecoration(
                  color: Theme.of(context).cardColor,
                ),
                child: _chatEnvironment(),
              )
            ],
          ));
    }
  }
  
  </code></pre>
  
  <p>vendor chat screen </p>
  
  <pre><code>
  import 'dart:async';
  import 'dart:math';
  import 'dart:async';
  import 'dart:io';
  import 'dart:math';
  import 'dart:convert';
  import 'dart:async' show Future;
  import 'package:firebase_database/firebase_database.dart';
  import 'package:firebase_messaging/firebase_messaging.dart';
  import 'package:flutter/material.dart';
  import 'package:intl/intl.dart';
  import 'package:koni_app/Pages/UsersPages/MyOrders/Chat.dart';
  import 'package:koni_app/Pages/UsersPages/MyOrders/chat_model.dart';
  import 'package:koni_app/Pages/UsersPages/MyOrders/chatmessage.dart';
  import 'package:http/http.dart' as http;
  import 'MyOrders/Vendorchatmessage.dart';
  import 'package:flutter_local_notifications/flutter_local_notifications.dart';
  import 'package:uuid/uuid.dart';
  import 'package:keyboard_actions/keyboard_actions.dart';
  import 'MyOrders/vendorchat_model.dart';
  
  class VendorAdminChatPage extends StatefulWidget {
    final String _userName;
    final String _id;
    final String _userid;
    final String orderNo;
    final String vendorId;
    VendorAdminChatPage(this._userName, this._id, this._userid, this.orderNo,this.vendorId);
  
    StreamSubscription _subscriptionTodo;
  
  /*
    @override
    Widget build(BuildContext context) {
      return Scaffold(
        appBar: AppBar(
          backgroundColor: Color(0xFF7872c0),
          title: Text("تواصل مع الادارة "),
        ),
        body: Center(
          child: Text('here the UserAdminChat page it will be '),
        ),
      );
    }
  */
  
    @override
    State&lt;StatefulWidget&gt; createState() {
      // TODO: implement createState
      return _VendorChatPageState();
    }
  }
  
  class _VendorChatPageState extends State&lt;VendorAdminChatPage&gt; {
    static var databaseReference = FirebaseDatabase.instance.reference();
    var v_id;
    var vendor_id;
    var user_id;
    var user_name, user_token;
  
    final TextEditingController _chatController = new TextEditingController();
    final List&lt;Vendorchatmessage&gt; _messages = &lt;Vendorchatmessage&gt;[];
  
    FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
    List&lt;VendorChatModel&gt; list_messages = List&lt;VendorChatModel&gt;();
  
    DateTime now = DateTime.now();
    FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
  
    int chat_id_fr;
  
    Future onSelectNotification(String payload) {
      debugPrint("payload : $payload");
      showDialog(
        context: context,
        builder: (_) =&gt; new AlertDialog(
              title: new Text('Notification'),
              content: new Text('$payload'),
            ),
      );
    }
  
    @override
    void initState() {
      vendor_id = widget.vendorId;
      user_id = widget._userid;
      user_id = widget._userid;
      // var user_Id = widget._userid;
      print("sssss" + user_id);
  
      getDetails();
      getchat();
  
      flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
      var android = new AndroidInitializationSettings('@mipmap/ic_launcher');
      var iOS = new IOSInitializationSettings();
      var initSetttings = new InitializationSettings(android, iOS);
      flutterLocalNotificationsPlugin.initialize(initSetttings,
          onSelectNotification: onSelectNotification);
  
  
      _firebaseMessaging.configure(
        onLaunch: (Map&lt;String, dynamic&gt; message) {
          print('onLaunch called');
          showNotification("", "");
        },
        onResume: (Map&lt;String, dynamic&gt; message) {
          print('onResume called');
          showNotification("", "");
        },
        onMessage: (Map&lt;String, dynamic&gt; message) {
          print('onMessage called' + message.toString());
  
          Map msg_ = message['notification'];
          String body = msg_['body'];
          String title = msg_['title'];
  
  
  
          setState(() {
            showNotification(body, title);
            Vendorchatmessage message = new Vendorchatmessage(
              text: body.toString(),
              vendor: "user",
              vendor_name: "",
            );
            print("msg===" + body.toString());
            print("msg===" + body.toString());
            _messages.insert(0, message);
          });
  
        },
      );
      _firebaseMessaging.subscribeToTopic('all');
      _firebaseMessaging.requestNotificationPermissions(IosNotificationSettings(
        sound: true,
        badge: true,
        alert: true,
      ));
      _firebaseMessaging.onIosSettingsRegistered
          .listen((IosNotificationSettings settings) {
        print('Hello');
      });
      _firebaseMessaging.getToken().then((token) {});
    }
  
    showNotification(String body, String title) async {
      var android = new AndroidNotificationDetails(
          'channel id', 'channel NAME', 'CHANNEL DESCRIPTION',
          priority: Priority.High, importance: Importance.Max);
      var iOS = new IOSNotificationDetails();
      var platform = new NotificationDetails(android, iOS);
      await flutterLocalNotificationsPlugin
          .show(0, 'New Message', '$body', platform, payload: '$body');
    }
  
    Future&lt;String&gt; getDetails() async {
      FirebaseDatabase.instance
          .reference()
          .child("user")
          .child(user_id)
          .once()
          .then((DataSnapshot snapshot) {
        Map value = snapshot.value;
        var vendor_id_fr = value['id'];
        user_name = value['name'];
        user_token = value['token'];
  
        //Map&lt;String, dynamic&gt; data = map['Data'];
        print("name " + user_name);
        print("id " + vendor_id);
        print("token " + user_token);
      });
      return vendor_id.toString();
    }
  
    Future&lt;String&gt; getchat() async {
      FirebaseDatabase.instance
          .reference()
          .child("chat")
          .child(widget.orderNo)
          .once()
          .then((DataSnapshot snapshot) {
        Map value_ = snapshot.value;
  
        value_.forEach((key, value) {
          Map value_1 = value;
  
          chat_id_fr = value_1['chat_id'];
          var vendor_msg_fr = value_1['msg'];
          var user_id_ = value_['user_id'];
          var vendor_id_ = value_['vendor_id'];
  
          VendorChatModel chatModel = new VendorChatModel.fromJson(value);
          list_messages.add(chatModel);
          list_messages.sort((a, b) =&gt; a.chat_id_fr.compareTo(b.chat_id_fr));
  
        });
  
        var list_data = list_messages.toString();
        print(list_data.toString());
        int dfd = list_messages.length;
  
        for (int i = 0; i &lt;= list_messages.length; i++) {
  
        /*  String lower=list_messages.elementAt(0).chat_id_fr;
          String lower1=list_messages.elementAt(0).chat_id_fr;
  */
          dfd = dfd - 1;
  
  
         /* int ss=list_messages.length-1;
          String ss=ss.toString();*/
  
          if (list_messages.elementAt(dfd).for_value.toString().contains("user")) {
  
            setState(() {
              Vendorchatmessage message = new Vendorchatmessage(
                  text: list_messages.elementAt(dfd).msg,
                  vendor: "user",
                  vendor_name: user_name);
              _messages.add(message);
            });
  
          } else {
            setState(() {
              Vendorchatmessage message = new Vendorchatmessage(
                text: list_messages.elementAt(dfd).msg,
                vendor: "vendor",
                vendor_name: user_name,
              );
              _messages.add(message);
  
            });
          }
        }
      });
  
  
  
      return vendor_id.toString();
    }
  
    void _handleSubmit(String text) {
      _chatController.clear();
      // Vendorchatmessage message = new Vendorchatmessage(text: text);
      String formattedDate = DateFormat('kk:mm:ss').format(now).toString();
      var rondm_no;
      var uuid = new Uuid();
  
      var rng = new Random();
      for (var i = 0; i &lt; 10; i++) {
        print(rng.nextInt(100));
        rondm_no = uuid.v1().toString() + 'vendor_id';
      }
  
      chat_id_fr = 0;
  
      if (_messages.length == 0) {
        databaseReference
            .child("chat")
            .child(widget.orderNo)
            .child('$rondm_no')
            .update({
          'vendor_id': vendor_id.toString(),
          'user_id': user_id.toString(),
          'msg': text.toString(),
          'chat_id': 0,
          'for_value': 'vendor',
        });
      } else {
        for (var i = 0; i &lt; _messages.length; i++) {
          chat_id_fr = i + 1;
          databaseReference
              .child("chat")
              .child(widget.orderNo)
              .child('$rondm_no')
              .update({
            'vendor_id': vendor_id.toString(),
            'user_id': user_id.toString(),
            'msg': text.toString(),
            'chat_id': chat_id_fr,
            'for_value': 'vendor',
          });
        }
      }
  
      /*databaseReference.child("chat").child(widget.orderNo).update({
        'vendor_id': vendor_id.toString(),
        'user_id': user_id.toString(),
      });*/
  
      setState(() {
        Vendorchatmessage message = new Vendorchatmessage(
          text: text.toString(),
          vendor: "vendor",
          vendor_name: "",
        );
  
        print("msg===" + text.toString());
        print("msg===" + text.toString());
        _messages.insert(0, message);
  
        postRequest(text.toString());
      });
    }
  
    Future&lt;http.Response&gt; postRequest(String msg) async {
      var url = 'https://fcm.googleapis.com/fcm/send';
  
      Map&lt;String, dynamic&gt; jsonMap1 = {
        'notification': {'body': '$msg', 'title': 'New Massage'},
        'to': '$user_token',
      };
  
      //encode Map to JSON
      var body = json.encode(jsonMap1);
      var response = await http.post(url,
          headers: {
            "Content-Type": "application/json",
            "Authorization":
                "key=AAAAt08dld0:APA91bEY6Dtrb1x1SlAprnEYeSEUdCT0D0oq9qzlkLJDIJdB0-hVIbdKL_L6CysecmOb46gjD3lyZMKl5aGH4rY1daFYA838VMnS7SzumelXie3Vps7s8MkILRgz7Kj0QQ65Dp0uZLI6"
          },
          body: body);
      print("${response.statusCode}" + "=response=");
      print("${response.body}" + "=response=");
  
      return response;
    }
  
    Widget _chatEnvironment() {
      return IconTheme(
        data: new IconThemeData(color: Color(0xFF7872c0)),
        child: new Container(
          margin: const EdgeInsets.symmetric(horizontal: 8.0),
          child: new Row(
            children: &lt;Widget&gt;[
              new Flexible(
                child: new TextField(
                  decoration: new InputDecoration.collapsed(
                      hintText: "Starts typing ..."),
                  controller: _chatController,
                  onSubmitted: _handleSubmit,
                ),
              ),
              new Container(
                margin: const EdgeInsets.symmetric(horizontal: 4.0),
                child: new IconButton(
                  icon: new Icon(Icons.send),
                  onPressed: () =&gt; _handleSubmit(_chatController.text),
                ),
              )
            ],
          ),
        ),
      );
    }
  
    @override
    Widget build(BuildContext context) {
      return new Scaffold(
          appBar: new AppBar(
            title: new Text("المحادثة"), //Conversation
            backgroundColor: Color(0xFF7872c0),
          ),
          body: new Column(
            children: &lt;Widget&gt;[
              new Flexible(
                child: ListView.builder(
                  padding: new EdgeInsets.all(8.0),
                  reverse: true,
                  itemBuilder: (_, int index) =&gt; _messages[index],
                  itemCount: _messages.length,
                ),
              ),
              new Divider(
                height: 1.0,
              ),
              new Container(
                decoration: new BoxDecoration(
                  color: Theme.of(context).cardColor,
                ),
                child: _chatEnvironment(),
              )
            ],
          )
  
          /* Container(
            margin: const EdgeInsets.symmetric(horizontal: 8.0),
            child: Column(
              children: &lt;Widget&gt;[
                new Flexible(
                  child: new ListView.builder(
                    padding: new EdgeInsets.all(8.0),
                    reverse: true,
                    itemBuilder: (_, int index) {},
                    itemCount: 10,
                  ),
                ),
                new Divider(height: 1.0),
                Container(
                  margin: EdgeInsets.only(bottom: 20.0, right: 10.0, left: 10.0),
                  child: Row(
                    children: &lt;Widget&gt;[
                      new Flexible(
                        child: new TextField(
                          decoration: new InputDecoration.collapsed(
                              hintText: "ارسال الرسالة"), //"Send message"
                        ),
                      ),
                      new Container(
                        child: new IconButton(
                            icon: new Icon(
                              Icons.send,
                              color: Color(0xFF7872c0),
                            ),
                            onPressed: () {
  
                            }),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          )*/
  
          );
    }
  }
  
  </code></pre>
  
  <p>Updated Code </p>
  
  <pre><code>Future&lt;String&gt; getchat() async {
  
      FirebaseDatabase.instance
          .reference()
          .child("chat")
          .child(widget._orderNo)
          .onValue
          .listen((list_messages) {})
          .onData((Event event) {
          setState(() {
            if (event.snapshot != null) {
              Map&lt;dynamic, dynamic&gt; mapOfMaps = Map.from(event.snapshot.value);
  
              list_messages.clear();
  
              mapOfMaps.values.forEach((value) async {
                ChatModel vendor = ChatModel.fromJson(Map.from(value));
                  list_messages.add(vendor);
                  list_messages.sort((x, y) =&gt; x.chat_id_fr.compareTo(y.chat_id_fr));
            });
          }
  
        });
  
        var list_data = list_messages.toString();
  
        print(list_data.toString());
        // list_messages=list_messages.reversed.toList();
  
        int dfd = list_messages.length;
  
        for (int i = 0; i &lt;= list_messages.length; i++) {
          dfd = dfd - 1;
  
          /*  var value = list_messages.reduce((curr, next) =&gt; curr.chat_id_fr &gt; next.chat_id_fr ? curr : next);
          var value1 = list_messages.reduce((curr, next) =&gt; curr.chat_id_fr &gt; next.chat_id_fr ? curr : next);
  */
  
          if (list_messages
              .elementAt(dfd)
              .for_value
              .toString()
              .contains("user")) {
            setState(() {
              ChatMessage message = new ChatMessage(
                  text: list_messages.elementAt(dfd).msg,
                  vendor: "user",
                  vendor_name: vendor_name);
              _messages.add(message);
            });
          } else {
            setState(() {
              ChatMessage message = new ChatMessage(
                text: list_messages.elementAt(dfd).msg.toString(),
                vendor: "vendor",
                vendor_name: vendor_name,
              );
              _messages.add(message);
              //list_messages.reversed.toList();
            });
          }
        }
      });
  
      return vendor_id.toString();
    }
  
  </code></pre>