gpt4 book ai didi

firebase - 如何使用 firebase 的 flutter 进行实时聊天(ios)

转载 作者:IT王子 更新时间:2023-10-29 07:02:06 26 4
gpt4 key购买 nike

我为每个订单的用户和供应商之间的 flutter 应用程序制作了聊天模块,但在真实的 iPhone 中,我需要返回然后打开聊天屏幕才能看到新消息,而不是实时的

我怎样才能将它转换成实时的,这样用户或供应商就不需要返回然后重新打开聊天页面来查看新消息

这是我的代码

用户聊天界面

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() => new _ChatPageState();
}

class _ChatPageState extends State<ChatPage> {
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<ChatMessage> _messages = <ChatMessage>[];
List<ChatModel> list_messages = List<ChatModel>();

DateTime now = DateTime.now();
FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
var chat_id_fr;

Future onSelectNotification(String payload) {
debugPrint("payload : $payload");
showDialog(
context: context,
builder: (_) => 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<String, dynamic> message) {
print('onLaunch called');
showNotification("", "");
},
onResume: (Map<String, dynamic> message) {
print('onResume called');
showNotification("", "");
},
onMessage: (Map<String, dynamic> 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<String> 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<String, dynamic> data = map['Data'];
print("name " + vendor_name);
print("id " + vendor_id);
print("token " + vendor_token);
});

return vendor_id.toString();
}

Future<String> 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) => 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 <= list_messages.length; i++) {
dfd = dfd - 1;

/* var value = list_messages.reduce((curr, next) => curr.chat_id_fr > next.chat_id_fr ? curr : next);
var value1 = list_messages.reduce((curr, next) => curr.chat_id_fr > 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<http.Response> postRequest(String msg) async {
var url = 'https://fcm.googleapis.com/fcm/send';

Map<String, dynamic> jsonMap = {
'notification': {'body': '$msg', 'title': 'New Massage'},
'to':
'fPgRVKZY56Q:APA91bHEMQy1EKHbPUraCn2tCp2th6Oah5Xx_N7b-6wLiHWjjYG7WCaRmjwstR8_YaNukwA_mwZHuCpQoYKuXL7nQBMGPH3kw58vHth7FkXuyn-keW0JnNUZhDzlgV2RA9HraeW2M4R0',
};
Map<String, dynamic> 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 < 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 < _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: <Widget>[
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: () => _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: <Widget>[
new Flexible(
child: ListView.builder(
padding: new EdgeInsets.all(8.0),
reverse: true,
itemBuilder: (_, int index) => _messages[index],
itemCount: _messages.length,
),
),
new Divider(
height: 1.0,
),
new Container(
decoration: new BoxDecoration(
color: Theme.of(context).cardColor,
),
child: _chatEnvironment(),
)
],
));
}
}

供应商聊天屏幕


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<StatefulWidget> createState() {
// TODO: implement createState
return _VendorChatPageState();
}
}

class _VendorChatPageState extends State<VendorAdminChatPage> {
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<Vendorchatmessage> _messages = <Vendorchatmessage>[];

FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
List<VendorChatModel> list_messages = List<VendorChatModel>();

DateTime now = DateTime.now();
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;

int chat_id_fr;

Future onSelectNotification(String payload) {
debugPrint("payload : $payload");
showDialog(
context: context,
builder: (_) => 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<String, dynamic> message) {
print('onLaunch called');
showNotification("", "");
},
onResume: (Map<String, dynamic> message) {
print('onResume called');
showNotification("", "");
},
onMessage: (Map<String, dynamic> 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<String> 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<String, dynamic> data = map['Data'];
print("name " + user_name);
print("id " + vendor_id);
print("token " + user_token);
});
return vendor_id.toString();
}

Future<String> 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) => 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 <= 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 < 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 < _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<http.Response> postRequest(String msg) async {
var url = 'https://fcm.googleapis.com/fcm/send';

Map<String, dynamic> 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: <Widget>[
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: () => _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: <Widget>[
new Flexible(
child: ListView.builder(
padding: new EdgeInsets.all(8.0),
reverse: true,
itemBuilder: (_, int index) => _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: <Widget>[
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: <Widget>[
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: () {

}),
),
],
),
),
],
),
)*/

);
}
}

更新代码

Future<String> getchat() async {

FirebaseDatabase.instance
.reference()
.child("chat")
.child(widget._orderNo)
.onValue
.listen((list_messages) {})
.onData((Event event) {
setState(() {
if (event.snapshot != null) {
Map<dynamic, dynamic> 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) => 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 <= list_messages.length; i++) {
dfd = dfd - 1;

/* var value = list_messages.reduce((curr, next) => curr.chat_id_fr > next.chat_id_fr ? curr : next);
var value1 = list_messages.reduce((curr, next) => curr.chat_id_fr > 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();
}

最佳答案

你需要做这个改变

使用 value 而不是 once

使用它从 firebase 获取数据

  FirebaseDatabase.instance
.reference()
.child("vendor")
.child(vendor_id)
.onValue
.listen(() {})
.onData((Event event) {
setState(() {
if (event.snapshot != null) {
print("data= " + event.snapshot.value.toString());

Map<dynamic, dynamic> mapOfMaps = Map.from(event.snapshot.value);

arrCategories.clear();

mapOfMaps.values.forEach((value) async {
Category category = Category.fromJson(Map.from(value));

arrCategories.add(category);
});
}
});
});

关于firebase - 如何使用 firebase 的 flutter 进行实时聊天(ios),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57439288/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com