Skip to content

Commit

Permalink
optimize service coe
Browse files Browse the repository at this point in the history
  • Loading branch information
YeFei572 committed Sep 28, 2023
1 parent 7032d42 commit 4c4a339
Show file tree
Hide file tree
Showing 18 changed files with 327 additions and 77 deletions.
4 changes: 2 additions & 2 deletions android/build.gradle
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
buildscript {
ext.kotlin_version = '1.7.10'
repositories {
// google()
google()
mavenCentral()
}

Expand All @@ -13,7 +13,7 @@ buildscript {

allprojects {
repositories {
// google()
google()
mavenCentral()
}
}
Expand Down
10 changes: 5 additions & 5 deletions android/gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true

systemProp.http.proxyHost=localhost
systemProp.http.proxyPort=4781

systemProp.https.proxyHost=localhost
systemProp.https.proxyPort=4781
#systemProp.http.proxyHost=localhost
#systemProp.http.proxyPort=4780
#
#systemProp.https.proxyHost=localhost
#systemProp.https.proxyPort=4780
1 change: 1 addition & 0 deletions lib/constant/enums.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/// 消息类型
enum MsgType {
heartbeat(0, '心跳检测'),
loginMsg(1, '登录消息'),
txtMsg(2, '文本'),
picMsg(3, '图片'),
Expand Down
3 changes: 3 additions & 0 deletions lib/model/chat_record.dart
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ part 'chat_record.g.dart';
class ChatRecord {
int? id;

int? uid;

int? targetId;

String? targetName;
Expand All @@ -42,6 +44,7 @@ class ChatRecord {

ChatRecord({
this.id,
this.uid,
this.targetId,
this.targetName,
this.fromId,
Expand Down
2 changes: 2 additions & 0 deletions lib/model/chat_record.g.dart

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions lib/store/chat_store.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import 'package:flutter_cim_plus/constant/enums.dart';
import 'package:flutter_cim_plus/http/apiservice/api_service.dart';
import 'package:flutter_cim_plus/model/chat_record.dart';
import 'package:flutter_cim_plus/model/friend_info.dart';
import 'package:flutter_cim_plus/utils/database_helper.dart';
import 'package:get/get.dart';

Expand Down Expand Up @@ -48,6 +49,17 @@ class ChatStore extends GetxController {

/// 监听消息记录
Future<void> receiveMsg(ChatRecord record) async {
// 从库里面获取对应的对象用户信息
if (record.chatType == ChatType.p2p.code) {
List<FriendInfo> existFriend =
await DatabaseHelper().getFriendList(uid: record.uid);
if (existFriend.isNotEmpty) {
FriendInfo info = existFriend[0];
record.fromId = info.userId;
record.fromName = info.nickname;
record.fromAvatar = info.avatar;
}
}
await DatabaseHelper().insertRecord(record);
_chatList.clear();
loadChatList(page, size, LogicType.normal.code);
Expand Down
16 changes: 16 additions & 0 deletions lib/style/refresh_constants.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import 'package:easy_refresh/easy_refresh.dart';

class RefreshConstants {
static ClassicHeader buildZhHeaders() {
return const ClassicHeader(
dragText: '下拉开始刷新',
armedText: '松开开始刷新',
readyText: '准备开始刷新',
processedText: '刷新完成',
processingText: '拼命加载中...',
failedText: 'GG,刷新失败',
messageText: '上次更新时间%T',
noMoreText: '已经没有更多数据啦!',
);
}
}
18 changes: 18 additions & 0 deletions lib/style/txt_style.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import 'package:flutter/material.dart';

class TxtStyle {
static TextStyle? titleS({
double size = 17,
FontWeight fWeight = FontWeight.w600,
}) {
return TextStyle(fontSize: size, fontWeight: fWeight);
}

static TextStyle? contentS({
double size = 13,
FontWeight fWeight = FontWeight.w400,
Color? color,
}) {
return TextStyle(fontSize: size, fontWeight: fWeight, color: color);
}
}
62 changes: 54 additions & 8 deletions lib/utils/database_helper.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import 'package:sqflite/sqflite.dart';

import '../constant/enums.dart';
import '../model/chat_record.dart';
import '../model/friend_info.dart';

class DatabaseHelper {
static final DatabaseHelper _instance = DatabaseHelper._internal();
Expand All @@ -21,6 +22,7 @@ class DatabaseHelper {
}

/// id:消息记录id
/// uid:对话对象的id
/// targetId:对象id,可以是用户id,群id
/// targetName: 对象名称,可以是用户名称,群名称
/// avatar: 头像
Expand All @@ -35,9 +37,18 @@ class DatabaseHelper {
static Future<Database> initializeDatabase() async {
String path = join(await getDatabasesPath(), 'cim-plus.db');
return openDatabase(path, version: 1, onCreate: (db, version) async {
await db.execute("""
CREATE TABLE friends (
userId INTEGER PRIMARY KEY,
nickname TEXT NOT NULL,
remark TEXT,
avatar TEXT
);
""");
await db.execute("""
CREATE TABLE chat_records (
id INTEGER PRIMARY KEY AUTOINCREMENT,
uid INTEGER NOT NULL,
targetId INTEGER NOT NULL,
targetName TEXT NOT NULL,
avatar TEXT,
Expand Down Expand Up @@ -68,8 +79,8 @@ class DatabaseHelper {
record.logicType = LogicType.normal.code;
// 删除旧的逻辑数据并插入新的数据
await db.delete('chat_records',
where: 'targetId = ? and logicType = ?',
whereArgs: [record.targetId, record.logicType]);
where: 'uid = ? and logicType = ?',
whereArgs: [record.uid, record.logicType]);
await db.insert('chat_records', record.toJson());
}

Expand All @@ -93,14 +104,15 @@ class DatabaseHelper {

/// 获取指定用户的对话记录
Future<List<ChatRecord>> getConversionList(
int page, int size, int userId) async {
int page,
int size,
int userId, {
LogicType logicType = LogicType.friend,
}) async {
final db = await database;
final List<Map<String, dynamic>> maps = await db.query('chat_records',
where: 'logicType = 1 and (targetId = ? or fromId = ?)',
whereArgs: [
userId,
userId,
],
where: 'logicType = ? and uid = ?',
whereArgs: [logicType.code, userId],
orderBy: 'createTime DESC',
limit: size,
offset: (page - 1) * size);
Expand All @@ -122,4 +134,38 @@ class DatabaseHelper {
);
LogI("清除消息成功!清除消息条数:$num");
}

/// ------------------同步数据到本地数据库----------------------
/// 插入朋友信息列表到数据库
Future<void> insertFriendList(List<FriendInfo>? infos) async {
if (infos != null && infos.isNotEmpty) {
final db = await database;
// 先清空所有数据
db.delete('friends');
// 发起批量插入
Batch batch = db.batch();
for (FriendInfo info in infos) {
batch.insert('friends', info.toMap());
}
batch.commit(noResult: true);
}
}

/// 批量获取好友信息
Future<List<FriendInfo>> getFriendList({int? uid}) async {
final db = await database;
final List<Map<String, dynamic>> maps;
if (uid == null) {
maps = await db.query('friends', orderBy: 'nickname desc');
} else {
maps = await db.query(
'friends',
where: 'userId = ?',
whereArgs: [uid],
orderBy: 'nickname desc',
);
}
return List.generate(
maps.length, (index) => FriendInfo.fromJson(maps[index]));
}
}
18 changes: 18 additions & 0 deletions lib/utils/time_util.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
class TimeUtil {
static String formatTimeAgo(int timestamp) {
DateTime now = DateTime.now();
DateTime targetTime = DateTime.fromMillisecondsSinceEpoch(timestamp);

Duration difference = now.difference(targetTime);

if (difference.inDays > 0) {
return '${difference.inDays} 天前';
} else if (difference.inHours > 0) {
return '${difference.inHours} 小时前';
} else if (difference.inMinutes > 0) {
return '${difference.inMinutes} 分钟前';
} else {
return '刚刚';
}
}
}
50 changes: 42 additions & 8 deletions lib/view/chat/chat_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bounce/flutter_bounce.dart';
import 'package:flutter_cim_plus/model/chat_record.dart';
import 'package:flutter_cim_plus/style/refresh_constants.dart';
import 'package:flutter_cim_plus/style/txt_style.dart';
import 'package:flutter_cim_plus/utils/time_util.dart';
import 'package:flutter_cim_plus/view/chat/chat_controller.dart';
import 'package:flutter_cim_plus/widget/net_image_cached.dart';
import 'package:get/get.dart';
Expand All @@ -15,13 +18,11 @@ class ChatPage extends GetView<ChatController> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('聊天'),
centerTitle: true,
),
appBar: AppBar(title: const Text('聊天'), centerTitle: true),
body: GetX<ChatController>(
builder: (controller) => EasyRefresh(
controller: controller.refreshController,
header: RefreshConstants.buildZhHeaders(),
onRefresh: () => controller.initChatRecords(LogicType.normal.code),
child: _buildFriendItems(),
),
Expand All @@ -33,13 +34,46 @@ class ChatPage extends GetView<ChatController> {
return ListView.separated(
itemBuilder: (_, index) {
ChatRecord record = ChatStore.to.chatList[index];
bool isFrom = record.uid == record.fromId;
return Bounce(
duration: const Duration(milliseconds: 200),
onPressed: () => controller.toDetail(record),
child: ListTile(
leading: netImageCached(record.avatar ?? ''),
title: Text(record.targetName ?? ''),
subtitle: Text(record.content ?? ''),
child: Container(
decoration: const BoxDecoration(border: Border()),
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
child: Row(
children: [
netImageCached(
isFrom ? record.fromAvatar ?? '' : record.avatar ?? ''),
const SizedBox(width: 10),
Expanded(
child: SizedBox(
height: 50,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
isFrom
? record.fromName ?? ''
: record.targetName ?? '',
style: TxtStyle.titleS(),
),
Text(
record.content ?? '',
style: TxtStyle.contentS(),
maxLines: 1,
),
],
),
),
),
Text(
TimeUtil.formatTimeAgo(record.createTime!),
style: TxtStyle.contentS(color: Colors.white30),
)
],
),
),
);
},
Expand Down
1 change: 1 addition & 0 deletions lib/view/chat/detail/chat_view.dart
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ class _ChatViewState extends State<ChatView> {
LogI(editViewController.text);
ChatRecord record = ChatRecord(
avatar: widget.avatar,
uid: int.parse(widget.id),
targetId: int.parse(widget.id),
targetName: widget.title,
content: editViewController.text,
Expand Down
16 changes: 15 additions & 1 deletion lib/view/friend/friend_controller.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter_cim_plus/http/apiservice/api_service.dart';
import 'package:flutter_cim_plus/model/base_entity.dart';
import 'package:flutter_cim_plus/utils/database_helper.dart';
import 'package:flutter_cim_plus/utils/log_utils.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';

import '../../model/friend_info.dart';
Expand All @@ -21,10 +23,22 @@ class FriendController extends GetxController {
super.onInit();
}

Future<void> initFriendData() async {
Future<void> refreshFriends() async {
BaseEntity<List<FriendInfo>> res = await ApiService().getMyFriends();
if (res.code == 0 && res.data != null && res.data!.isNotEmpty) {
friendList.value = res.data!;
// 开始同步数据到本地数据库
DatabaseHelper().insertFriendList(res.data);
}
Fluttertoast.showToast(msg: '刷新成功!');
}

Future<void> initFriendData() async {
List<FriendInfo> friends = await DatabaseHelper().getFriendList();
if (friends.isNotEmpty) {
friendList.value = friends;
} else {
refreshFriends();
}
}

Expand Down
4 changes: 3 additions & 1 deletion lib/view/friend/friend_page.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bounce/flutter_bounce.dart';
import 'package:flutter_cim_plus/style/refresh_constants.dart';
import 'package:flutter_cim_plus/widget/net_image_cached.dart';
import 'package:get/get.dart';

Expand Down Expand Up @@ -33,7 +34,8 @@ class FriendPage extends GetView<FriendController> {
),
body: GetX<FriendController>(
builder: (controller) => EasyRefresh(
onRefresh: controller.initFriendData,
header: RefreshConstants.buildZhHeaders(),
onRefresh: controller.refreshFriends,
child: ListView.separated(
itemBuilder: (item, index) {
FriendInfo info = controller.friendList[index];
Expand Down
Loading

0 comments on commit 4c4a339

Please sign in to comment.