feat:更新消息通知功能

This commit is contained in:
2026-06-20 16:11:57 +08:00
parent 5d12377606
commit 5e0864d3ac
16 changed files with 332 additions and 24 deletions

View File

@@ -13,6 +13,9 @@ android {
compileOptions {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
// 启用核心库脱糖
isCoreLibraryDesugaringEnabled = true
}
kotlinOptions {
@@ -39,6 +42,11 @@ android {
}
}
dependencies {
// 添加核心库脱糖依赖
coreLibraryDesugaring("com.android.tools:desugar_jdk_libs:2.1.4")
}
flutter {
source = "../.."
}

View File

@@ -39,7 +39,9 @@
In particular, this is used by the Flutter engine in io.flutter.plugin.text.ProcessTextPlugin. -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 通知权限 -->
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<queries>
<intent>
<action android:name="android.intent.action.PROCESS_TEXT"/>

View File

@@ -2,6 +2,14 @@ allprojects {
repositories {
google()
mavenCentral()
// 官方中国镜像:
maven { url = uri("https://storage.flutter-io.cn/download.flutter.io") }
// 阿里云镜像加速 google() / mavenCentral(),避免直连慢或被阻断
maven { url = uri("https://maven.aliyun.com/repository/google") }
maven { url = uri("https://maven.aliyun.com/repository/public") }
maven { url = uri("https://maven.aliyun.com/repository/gradle-plugin") }
}
}

View File

@@ -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';
}

View File

@@ -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 {

View File

@@ -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: '',

View File

@@ -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(

View File

@@ -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

View File

@@ -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(

View File

@@ -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

View File

@@ -0,0 +1,5 @@
import 'package:flutter/material.dart';
class AppProvider extends ChangeNotifier {
String routerName = '';
}

View 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);
}
}

View File

@@ -5,8 +5,10 @@
import FlutterMacOS
import Foundation
import flutter_local_notifications
import shared_preferences_foundation
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
FlutterLocalNotificationsPlugin.register(with: registry.registrar(forPlugin: "FlutterLocalNotificationsPlugin"))
SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin"))
}

View File

@@ -29,10 +29,10 @@ packages:
dependency: transitive
description:
name: async
sha256: d2872f9c19731c2e5f10444b14686eb7cc85c76274bd6c16e1816bff9a3bab63
sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.12.0"
version: "2.13.1"
azlistview:
dependency: "direct main"
description:
@@ -149,10 +149,10 @@ packages:
dependency: "direct main"
description:
name: cupertino_icons
sha256: ba631d1c7f7bef6b729a622b7b752645a2d076dba9976925b8f25725a30e1ee6
sha256: "41e005c33bd814be4d3096aff55b1908d419fde52ca656c8c47719ec745873cd"
url: "https://pub.flutter-io.cn"
source: hosted
version: "1.0.8"
version: "1.0.9"
dart_style:
dependency: transitive
description:
@@ -161,6 +161,14 @@ packages:
url: "https://pub.flutter-io.cn"
source: hosted
version: "3.1.7"
dbus:
dependency: transitive
description:
name: dbus
sha256: "0ce9b0a839e6dee59a37a623d2fc26a35bbbe6404213e419b0d6411023d62645"
url: "https://pub.flutter-io.cn"
source: hosted
version: "0.7.14"
dio:
dependency: "direct main"
description:
@@ -230,6 +238,38 @@ packages:
url: "https://pub.flutter-io.cn"
source: hosted
version: "5.0.0"
flutter_local_notifications:
dependency: "direct main"
description:
name: flutter_local_notifications
sha256: "2b50e938a275e1ad77352d6a25e25770f4130baa61eaf02de7a9a884680954ad"
url: "https://pub.flutter-io.cn"
source: hosted
version: "20.1.0"
flutter_local_notifications_linux:
dependency: transitive
description:
name: flutter_local_notifications_linux
sha256: dce0116868cedd2cdf768af0365fc37ff1cbef7c02c4f51d0587482e625868d0
url: "https://pub.flutter-io.cn"
source: hosted
version: "7.0.0"
flutter_local_notifications_platform_interface:
dependency: transitive
description:
name: flutter_local_notifications_platform_interface
sha256: "23de31678a48c084169d7ae95866df9de5c9d2a44be3e5915a2ff067aeeba899"
url: "https://pub.flutter-io.cn"
source: hosted
version: "10.0.0"
flutter_local_notifications_windows:
dependency: transitive
description:
name: flutter_local_notifications_windows
sha256: e97a1a3016512437d9c0b12fae7d1491c3c7b9aa7f03a69b974308840656b02a
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.0.1"
flutter_shaders:
dependency: transitive
description:
@@ -272,6 +312,14 @@ packages:
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.3.2"
http:
dependency: transitive
description:
name: http
sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412"
url: "https://pub.flutter-io.cn"
source: hosted
version: "1.6.0"
http_multi_server:
dependency: transitive
description:
@@ -356,10 +404,10 @@ packages:
dependency: "direct main"
description:
name: liquid_glass_widgets
sha256: "881b8d7c40d8ac23ac5b56ccf747250c45dc1bb9f3fa92bc0444fee1d2ff7187"
sha256: "776adcdb7d48af0b935642425936813074355830eb0a47ecca8b227549d5b057"
url: "https://pub.flutter-io.cn"
source: hosted
version: "0.16.1"
version: "0.16.3"
logging:
dependency: transitive
description:
@@ -408,6 +456,14 @@ packages:
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.0.0"
nested:
dependency: transitive
description:
name: nested
sha256: "03bac4c528c64c95c722ec99280375a6f2fc708eec17c7b3f07253b626cd2a20"
url: "https://pub.flutter-io.cn"
source: hosted
version: "1.0.0"
package_config:
dependency: transitive
description:
@@ -448,6 +504,14 @@ packages:
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.3.0"
petitparser:
dependency: transitive
description:
name: petitparser
sha256: "91bd59303e9f769f108f8df05e371341b15d59e995e6806aefab827b58336675"
url: "https://pub.flutter-io.cn"
source: hosted
version: "7.0.2"
platform:
dependency: transitive
description:
@@ -472,6 +536,14 @@ packages:
url: "https://pub.flutter-io.cn"
source: hosted
version: "1.5.2"
provider:
dependency: "direct main"
description:
name: provider
sha256: "4e82183fa20e5ca25703ead7e05de9e4cceed1fbd1eadc1ac3cb6f565a09f272"
url: "https://pub.flutter-io.cn"
source: hosted
version: "6.1.5+1"
pub_semver:
dependency: transitive
description:
@@ -593,10 +665,10 @@ packages:
dependency: transitive
description:
name: source_span
sha256: "254ee5351d6cb365c859e20ee823c3bb479bf4a293c22d17a9f1bf144ce86f7c"
sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab"
url: "https://pub.flutter-io.cn"
source: hosted
version: "1.10.1"
version: "1.10.2"
stack_trace:
dependency: transitive
description:
@@ -645,6 +717,14 @@ packages:
url: "https://pub.flutter-io.cn"
source: hosted
version: "0.7.7"
timezone:
dependency: transitive
description:
name: timezone
sha256: dd14a3b83cfd7cb19e7888f1cbc20f258b8d71b54c06f79ac585f14093a287d1
url: "https://pub.flutter-io.cn"
source: hosted
version: "0.10.1"
typed_data:
dependency: transitive
description:
@@ -665,10 +745,10 @@ packages:
dependency: transitive
description:
name: vm_service
sha256: "0968250880a6c5fe7edc067ed0a13d4bae1577fe2771dcf3010d52c4a9d3ca14"
sha256: "0016aef94fc66495ac78af5859181e3f3bf2026bd8eecc72b9565601e19ab360"
url: "https://pub.flutter-io.cn"
source: hosted
version: "14.3.1"
version: "15.2.0"
watcher:
dependency: transitive
description:
@@ -709,6 +789,14 @@ packages:
url: "https://pub.flutter-io.cn"
source: hosted
version: "1.1.0"
xml:
dependency: transitive
description:
name: xml
sha256: "971043b3a0d3da28727e40ed3e0b5d18b742fa5a68665cca88e74b7876d5e025"
url: "https://pub.flutter-io.cn"
source: hosted
version: "6.6.1"
yaml:
dependency: transitive
description:

View File

@@ -1 +1 @@
name: sweet_chat_app
name: sweet_chat_app

View File

@@ -6,6 +6,7 @@ list(APPEND FLUTTER_PLUGIN_LIST
)
list(APPEND FLUTTER_FFI_PLUGIN_LIST
flutter_local_notifications_windows
)
set(PLUGIN_BUNDLED_LIBRARIES)