feat:更新消息通知功能
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
class AppConfig {
|
||||
static const String baseUrl = 'http://192.168.31.108:2836/api';
|
||||
static const String wsUrl = 'ws://192.168.31.108:5050';
|
||||
static const String baseUrl = 'http://192.168.31.109:2836/api';
|
||||
static const String wsUrl = 'ws://192.168.31.109:5050';
|
||||
}
|
||||
@@ -1,15 +1,32 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:liquid_glass_widgets/liquid_glass_widgets.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:sweet_chat_app/pages/login.dart';
|
||||
import 'package:sweet_chat_app/providers/app_provider.dart';
|
||||
import 'package:sweet_chat_app/services/notify_service.dart';
|
||||
import 'package:sweet_chat_app/utils/sp_utils.dart';
|
||||
|
||||
void main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
await SpUtil.init();
|
||||
|
||||
// 初始化提醒服务
|
||||
final notifyService = NotifyService();
|
||||
await notifyService.initialize();
|
||||
|
||||
// 预编译 shader,防止首帧白闪
|
||||
await LiquidGlassWidgets.initialize();
|
||||
// wrap() 安装无障碍桥接、全局主题、自适应质量
|
||||
runApp(LiquidGlassWidgets.wrap(child: const MyApp()));
|
||||
runApp(
|
||||
LiquidGlassWidgets.wrap(
|
||||
child: MultiProvider(
|
||||
providers: [
|
||||
ChangeNotifierProvider(create: (_) => AppProvider())
|
||||
],
|
||||
child: const MyApp(),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class MyApp extends StatelessWidget {
|
||||
|
||||
@@ -15,12 +15,14 @@ enum ImMessageType {
|
||||
|
||||
class ImMessage {
|
||||
final ImMessageType type;
|
||||
final String title;
|
||||
final String from;
|
||||
final String to;
|
||||
final String content;
|
||||
|
||||
ImMessage({
|
||||
required this.type,
|
||||
required this.title,
|
||||
required this.from,
|
||||
required this.to,
|
||||
required this.content,
|
||||
@@ -33,6 +35,7 @@ class ImMessage {
|
||||
factory ImMessage.fromJson(Map<String, dynamic> json) {
|
||||
return ImMessage(
|
||||
type: ImMessageType.values.firstWhere((e) => e.value == json['type']),
|
||||
title: json['title'],
|
||||
from: json['from'],
|
||||
to: json['to'],
|
||||
content: json['content'],
|
||||
@@ -41,6 +44,7 @@ class ImMessage {
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'type': type.value,
|
||||
'title': title,
|
||||
'from': from,
|
||||
'to': to,
|
||||
'content': content,
|
||||
@@ -53,6 +57,7 @@ class ImMessage {
|
||||
static ImMessage online(int userId) {
|
||||
return ImMessage(
|
||||
type: ImMessageType.online,
|
||||
title: '',
|
||||
from: userId.toString(),
|
||||
to: 'SYSTEM',
|
||||
content: '',
|
||||
|
||||
@@ -3,6 +3,7 @@ import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:liquid_glass_widgets/liquid_glass_widgets.dart';
|
||||
import 'package:sweet_chat_app/apis/message_api.dart';
|
||||
import 'package:sweet_chat_app/config/AppConfig.dart';
|
||||
import 'package:sweet_chat_app/models/chat_message.dart';
|
||||
import 'package:sweet_chat_app/models/contact_info.dart';
|
||||
import 'package:sweet_chat_app/models/im_message.dart';
|
||||
@@ -27,8 +28,10 @@ class _ChatPageState extends State<ChatPage> {
|
||||
late StreamSubscription<String> _msgSub;
|
||||
final TextEditingController _textController = TextEditingController();
|
||||
final ScrollController _scrollController = ScrollController();
|
||||
|
||||
final FocusNode _focusNode = FocusNode();
|
||||
|
||||
late int userId;
|
||||
late String nickname;
|
||||
late String avatarUrl;
|
||||
late List<ChatMessage> _messages;
|
||||
|
||||
@@ -37,16 +40,23 @@ class _ChatPageState extends State<ChatPage> {
|
||||
super.initState();
|
||||
|
||||
userId = SpUtil.getInt('userId') ?? 0;
|
||||
nickname = SpUtil.getString('nickname') ?? '';
|
||||
avatarUrl = SpUtil.getString('avatarUrl') ?? '';
|
||||
|
||||
_messages = [];
|
||||
_loadChatMessage();
|
||||
|
||||
_msgSub = WebSocketService().messages.listen((websocketMessage) {
|
||||
_handleMessage(websocketMessage);
|
||||
_textController.clear();
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
scrollToBottom();
|
||||
});
|
||||
|
||||
listenMessage();
|
||||
|
||||
_focusNode.addListener(() {
|
||||
if (_focusNode.hasFocus) {
|
||||
Future.delayed(const Duration(milliseconds: 350), scrollToBottom);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _loadChatMessage() async {
|
||||
@@ -58,10 +68,19 @@ class _ChatPageState extends State<ChatPage> {
|
||||
_messages = list;
|
||||
});
|
||||
}
|
||||
|
||||
void listenMessage() {
|
||||
WebSocketService().connect('${AppConfig.wsUrl}?userId=$userId');
|
||||
_msgSub = WebSocketService().messages.listen((websocketMessage) {
|
||||
_handleMessage(websocketMessage);
|
||||
scrollToBottom();
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_msgSub.cancel();
|
||||
_focusNode.dispose();
|
||||
_textController.dispose();
|
||||
_scrollController.dispose();
|
||||
super.dispose();
|
||||
@@ -73,11 +92,13 @@ class _ChatPageState extends State<ChatPage> {
|
||||
|
||||
final chat = ImMessage(
|
||||
type: ImMessageType.chatPrivate,
|
||||
title: nickname,
|
||||
from: userId.toString(),
|
||||
to: widget.contactInfo.id.toString(),
|
||||
content: text,
|
||||
);
|
||||
WebSocketService().send(chat.toJsonString());
|
||||
_textController.clear();
|
||||
}
|
||||
|
||||
bool checkIsMe(ChatMessage message) {
|
||||
@@ -94,7 +115,7 @@ class _ChatPageState extends State<ChatPage> {
|
||||
_messages.add(
|
||||
ChatMessage(
|
||||
msgId: DateTime.now().millisecondsSinceEpoch,
|
||||
senderId: userId,
|
||||
senderId: int.parse(imMsg.from),
|
||||
content: imMsg.content,
|
||||
msgType: 1,
|
||||
createTime: DateTime.now(),
|
||||
@@ -204,6 +225,7 @@ class _ChatPageState extends State<ChatPage> {
|
||||
Expanded(
|
||||
child: TextField(
|
||||
controller: _textController,
|
||||
focusNode: _focusNode,
|
||||
onSubmitted: (_) => _sendMessage(),
|
||||
style: const TextStyle(color: Colors.white),
|
||||
cursorColor: Colors.white,
|
||||
@@ -212,6 +234,9 @@ class _ChatPageState extends State<ChatPage> {
|
||||
hintStyle: TextStyle(color: Colors.white),
|
||||
border: InputBorder.none,
|
||||
),
|
||||
onTap: () {
|
||||
Future.delayed(const Duration(milliseconds: 350), scrollToBottom);
|
||||
},
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:liquid_glass_widgets/widgets/shared/glass_page.dart';
|
||||
import 'package:liquid_glass_widgets/widgets/surfaces/glass_bottom_bar.dart';
|
||||
import 'package:liquid_glass_widgets/widgets/surfaces/glass_scaffold.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:sweet_chat_app/config/AppConfig.dart';
|
||||
import 'package:sweet_chat_app/models/im_message.dart';
|
||||
import 'package:sweet_chat_app/pages/contact_page.dart';
|
||||
import 'package:sweet_chat_app/pages/explore_page.dart';
|
||||
import 'package:sweet_chat_app/pages/message_page.dart';
|
||||
import 'package:sweet_chat_app/providers/app_provider.dart';
|
||||
import 'package:sweet_chat_app/services/notify_service.dart';
|
||||
import 'package:sweet_chat_app/services/webSocket_service.dart';
|
||||
import 'package:sweet_chat_app/utils/sp_utils.dart';
|
||||
|
||||
@@ -19,8 +24,11 @@ class HomePage extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _HomePageState extends State<HomePage> {
|
||||
late StreamSubscription<String> _msgSub;
|
||||
final NotifyService notifyService = NotifyService();
|
||||
int _index = 0;
|
||||
|
||||
late int userId;
|
||||
|
||||
final _pages = [
|
||||
const MessagePage(),
|
||||
const ContactsPage(),
|
||||
@@ -36,13 +44,35 @@ class _HomePageState extends State<HomePage> {
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_msgSub.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void initWebsocket() {
|
||||
final userId = SpUtil.getInt('userId') ?? 0;
|
||||
userId = SpUtil.getInt('userId') ?? 0;
|
||||
WebSocketService().connect('${AppConfig.wsUrl}?userId=$userId');
|
||||
WebSocketService().send(ImMessage.online(userId).toJsonString());
|
||||
|
||||
_msgSub = WebSocketService().messages.listen((websocketMessage) {
|
||||
_handleMessage(websocketMessage);
|
||||
});
|
||||
}
|
||||
|
||||
void _handleMessage(String wsMsg) {
|
||||
if (!mounted) return;
|
||||
|
||||
final ImMessage imMsg = ImMessage.fromJsonString(wsMsg);
|
||||
|
||||
// 非自己的消息
|
||||
if (imMsg.from != userId.toString()) {
|
||||
final appProvider = Provider.of<AppProvider>(context, listen: false);
|
||||
// 如果已经在聊天中 则不用提醒
|
||||
if (appProvider.routerName == 'chat') {
|
||||
return;
|
||||
}
|
||||
|
||||
notifyService.showInstantNotification(title: imMsg.title, body: imMsg.content);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:liquid_glass_widgets/liquid_glass_widgets.dart';
|
||||
import 'package:sweet_chat_app/apis/auth_api.dart';
|
||||
import 'package:sweet_chat_app/services/notify_service.dart';
|
||||
import 'package:sweet_chat_app/utils/sp_utils.dart';
|
||||
import 'package:sweet_chat_app/utils/toast_utils.dart';
|
||||
import 'home_page.dart';
|
||||
@@ -15,14 +16,18 @@ class LoginPage extends StatefulWidget {
|
||||
class _LoginPageState extends State<LoginPage> {
|
||||
final _usernameController = TextEditingController();
|
||||
final _passwordController = TextEditingController();
|
||||
|
||||
// final NotifyService notifyService = NotifyService();
|
||||
|
||||
void _login() async {
|
||||
try {
|
||||
// notifyService.showInstantNotification(title: '你好', body: '测试消息');
|
||||
|
||||
final auth = await loginApi(
|
||||
_usernameController.text,
|
||||
_passwordController.text,
|
||||
);
|
||||
await SpUtil.setInt('userId', auth.user.id);
|
||||
await SpUtil.setString('nickname', auth.user.nickname);
|
||||
await SpUtil.setString('avatarUrl', auth.user.avatarUrl);
|
||||
|
||||
Navigator.of(
|
||||
|
||||
@@ -2,10 +2,13 @@ import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:liquid_glass_widgets/liquid_glass_widgets.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:sweet_chat_app/apis/message_api.dart';
|
||||
import 'package:sweet_chat_app/models/chat_session.dart';
|
||||
import 'package:sweet_chat_app/models/contact_info.dart';
|
||||
import 'package:sweet_chat_app/pages/chat_page.dart';
|
||||
import 'package:sweet_chat_app/providers/app_provider.dart';
|
||||
import 'package:sweet_chat_app/services/notify_service.dart';
|
||||
import 'package:sweet_chat_app/services/webSocket_service.dart';
|
||||
import 'package:sweet_chat_app/utils/date_utils.dart';
|
||||
import 'package:sweet_chat_app/utils/sp_utils.dart';
|
||||
@@ -20,13 +23,19 @@ class MessagePage extends StatefulWidget {
|
||||
class _MessagePageState extends State<MessagePage> {
|
||||
late StreamSubscription<String> _msgSub;
|
||||
late List<ChatSession> _chatSessionList;
|
||||
final NotifyService notifyService = NotifyService();
|
||||
|
||||
late int userId;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
userId = SpUtil.getInt('userId') ?? 0;
|
||||
_chatSessionList = [];
|
||||
_loadChatSession();
|
||||
_msgSub = WebSocketService().messages.listen((websocketMessage) {});
|
||||
_msgSub = WebSocketService().messages.listen((websocketMessage) {
|
||||
_loadChatSession();
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -58,11 +67,14 @@ class _MessagePageState extends State<MessagePage> {
|
||||
conversationId: chatSession.conversationId,
|
||||
);
|
||||
|
||||
final appProvider = Provider.of<AppProvider>(context, listen: false);
|
||||
Navigator.push(context, MaterialPageRoute(builder: (_) => chatPage)).then((
|
||||
_,
|
||||
) {
|
||||
appProvider.routerName = '';
|
||||
_loadChatSession();
|
||||
});
|
||||
appProvider.routerName = 'chat';
|
||||
}
|
||||
|
||||
@override
|
||||
|
||||
5
lib/providers/app_provider.dart
Normal file
5
lib/providers/app_provider.dart
Normal file
@@ -0,0 +1,5 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class AppProvider extends ChangeNotifier {
|
||||
String routerName = '';
|
||||
}
|
||||
100
lib/services/notify_service.dart
Normal file
100
lib/services/notify_service.dart
Normal file
@@ -0,0 +1,100 @@
|
||||
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
|
||||
|
||||
class NotifyService {
|
||||
static final NotifyService _instance = NotifyService._internal();
|
||||
|
||||
factory NotifyService() => _instance;
|
||||
|
||||
NotifyService._internal();
|
||||
|
||||
late FlutterLocalNotificationsPlugin _notifications;
|
||||
|
||||
// Android特殊模式,即使设备处于省电模式也能准时触发。
|
||||
final scheduleMode = AndroidScheduleMode.exactAllowWhileIdle;
|
||||
|
||||
// 初始化通知服务
|
||||
Future<void> initialize() async {
|
||||
_notifications = FlutterLocalNotificationsPlugin();
|
||||
|
||||
// 设置Android平台的初始化配置 使用应用图标作为通知图标
|
||||
const AndroidInitializationSettings androidSettings =
|
||||
AndroidInitializationSettings('@mipmap/ic_launcher');
|
||||
|
||||
// 设置iOS平台的初始化配置
|
||||
const DarwinInitializationSettings iosSettings =
|
||||
DarwinInitializationSettings(
|
||||
requestAlertPermission: true,
|
||||
requestBadgePermission: true,
|
||||
requestSoundPermission: true,
|
||||
);
|
||||
|
||||
// 初始化设置
|
||||
const InitializationSettings settings = InitializationSettings(
|
||||
android: androidSettings,
|
||||
iOS: iosSettings,
|
||||
);
|
||||
|
||||
await _notifications.initialize(settings: settings);
|
||||
}
|
||||
|
||||
// 创建Android通知详情
|
||||
AndroidNotificationDetails _androidNotificationDetails() {
|
||||
const channelId = 'com.cxx.sweet_chat_app';
|
||||
const channelName = '亲聊';
|
||||
const channelDescription = '亲聊通知';
|
||||
return const AndroidNotificationDetails(
|
||||
channelId,
|
||||
channelName,
|
||||
channelDescription: channelDescription,
|
||||
importance: Importance.high,
|
||||
priority: Priority.high,
|
||||
playSound: true,
|
||||
enableVibration: true,
|
||||
);
|
||||
}
|
||||
|
||||
// 创建iOS通知详情
|
||||
DarwinNotificationDetails _iosNotificationDetails() {
|
||||
return const DarwinNotificationDetails(
|
||||
presentAlert: true,
|
||||
presentBadge: true,
|
||||
presentSound: true,
|
||||
);
|
||||
}
|
||||
|
||||
NotificationDetails get _details {
|
||||
return NotificationDetails(
|
||||
android: _androidNotificationDetails(),
|
||||
iOS: _iosNotificationDetails(),
|
||||
);
|
||||
}
|
||||
|
||||
// 立即显示通知
|
||||
Future<void> showInstantNotification({
|
||||
required String title,
|
||||
required String body,
|
||||
int id = 0,
|
||||
}) async {
|
||||
await _notifications.show(id: id, title: title, body: body, notificationDetails: _details);
|
||||
}
|
||||
|
||||
// 检查通知权限
|
||||
Future<bool> checkPermission() async {
|
||||
final bool? result =
|
||||
await _notifications
|
||||
.resolvePlatformSpecificImplementation<
|
||||
AndroidFlutterLocalNotificationsPlugin
|
||||
>()
|
||||
?.areNotificationsEnabled();
|
||||
return result ?? false;
|
||||
}
|
||||
|
||||
// 请求权限
|
||||
Future<void> requestPermission() async {
|
||||
await _notifications
|
||||
.resolvePlatformSpecificImplementation<
|
||||
IOSFlutterLocalNotificationsPlugin
|
||||
>()
|
||||
?.requestPermissions(alert: true, badge: true, sound: true);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user