Browse Source

im 修改

wr_202303
zsw 4 months ago
parent
commit
0da7957230
  1. 6
      android/app/build.gradle
  2. 4
      android/build.gradle
  3. 4
      android/gradle.properties
  4. 29
      lib/im/SocketClient.dart
  5. 179
      lib/im/chat_details_page.dart
  6. 125
      lib/im/database/hx_database.dart
  7. 290
      lib/im/database/hx_database.g.dart
  8. 24
      lib/im/database/message.dart
  9. 34
      lib/im/database/message_dao.dart
  10. 41
      lib/im/database/migration.dart
  11. 31
      lib/im/im_view/im_page.dart
  12. 16
      lib/im/out/auth.pb.dart
  13. 8
      lib/im/out/auth.pbjson.dart
  14. 16
      lib/im/out/message.pb.dart
  15. 6
      lib/im/out/message.pbjson.dart
  16. 5
      lib/main.dart
  17. 1
      lib/mine/edit_signature.dart
  18. 42
      pubspec.lock
  19. 3
      pubspec.yaml

6
android/app/build.gradle

@ -27,7 +27,7 @@ apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
apply plugin: 'com.mob.sdk'
apply plugin: 'com.huawei.agconnect'
//apply plugin: 'com.huawei.agconnect'
MobSDK {
appKey "m33ee7650da86a"
@ -203,7 +203,7 @@ dependencies {
implementation 'com.tencent.tpns:xiaomi:1.2.7.1-release'
implementation 'com.tencent.tpns:huawei:1.2.6.0-release'
// implementation 'com.tencent.tpns:huawei:1.2.6.0-release'
// HMS Core Push
implementation 'com.huawei.hms:push:5.3.0.304'
// implementation 'com.huawei.hms:push:5.3.0.304'
}

4
android/build.gradle

@ -1,5 +1,5 @@
buildscript {
ext.kotlin_version = '1.7.10'
ext.kotlin_version = '1.8.10'
repositories {
maven { url "https://www.jitpack.io" }
maven {url 'https://developer.huawei.com/repo/'}
@ -24,7 +24,7 @@ buildscript {
dependencies {
classpath 'com.android.tools.build:gradle:7.4.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.huawei.agconnect:agcp:1.4.1.300'
// classpath 'com.huawei.agconnect:agcp:1.4.1.300'
classpath 'com.mob.sdk:MobSDK:+'
classpath fileTree(include:['*.jar'], dir:'libs')
classpath 'com.umeng.umsdk:common:9.4.7'

4
android/gradle.properties

@ -1,5 +1,5 @@
org.gradle.jvmargs=-Xmx1536M
#org.gradle.jvmargs=-Xmx4096m
#org.gradle.jvmargs=-Xmx1536M
org.gradle.jvmargs=-Xmx4096m
android.useAndroidX=true
android.enableJetifier=true
MobSDK.mobEnv=x

29
lib/im/SocketClient.dart

@ -27,11 +27,10 @@ class SocketClient {
print(data);
print("socket-listen");
Proto proto = Proto.fromBytes(data);
print("socket-listen: $proto");
MsgData data1 = MsgData.fromBuffer(proto.body);
print('收到来自:${data1.from},消息内容: ${utf8.decode(data1.data)} ');
hxDatabase.messageDao.insertMessage(createMessage(mobile, utf8.decode(data1.data), userId: data1.from));
hxDatabase.insert(createMessage(userId, utf8.decode(data1.data), msgType: data1.type.value, userId: data1.from));
callbacks.forEach((callback) {
callback.call(data1);
@ -67,7 +66,7 @@ class SocketClient {
return;
}
final authReq = AuthReq()
..uid = mobile
..uid = userId
..token = token;
final authReqBytes = authReq.writeToBuffer();
final proto = Proto(1, 1, authReqBytes); // operation seqId 1
@ -75,18 +74,26 @@ class SocketClient {
_socket.add(protoBytes);
}
sendMessage(int toId, String content) {
Future<Message> sendMessage(String toId, String content) async {
Map message = createMessage(toId, content, userId: userId);
int id = await hxDatabase.insert(message).catchError((error) {
debugPrint("insertMessage: $error");
});
if (!checkSocket()) {
return;
hxDatabase.update({"id": id, "state": 3}).catchError((error) {
debugPrint("insertMessage: $error");
});
message["id"] = id;
message["state"] = 3;
return Message.fromJson(message);
}
message["id"] = id;
Uint8List data = utf8.encode(content);
MsgData msgData = MsgData(to: toId, from: mobile, type: MsgType.SINGLE_TEXT,data: data);
MsgData msgData = MsgData(to: toId, from: userId, type: MsgType.SINGLE_TEXT, data: data);
final proto2 = Proto(5, 1, msgData.writeToBuffer());
_socket.add(proto2.toBytes());
hxDatabase.messageDao.insertMessage(createMessage(toId, content, userId: mobile)).catchError((error) {
debugPrint("insertMessage: $error");
});
debugPrint("insertMessage: end");
debugPrint("sendMessage: ${message["id"]}");
return Message.fromJson(message);
}
checkSocket() {
@ -97,7 +104,7 @@ class SocketClient {
return true;
}
get mobile => 123456;
get userId => shared.getString("userId");
}

179
lib/im/chat_details_page.dart

@ -7,11 +7,13 @@ import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:huixiang/im/database/message.dart';
import 'package:huixiang/main.dart';
import 'package:huixiang/retrofit/retrofit_api.dart';
import 'package:huixiang/view_widget/my_appbar.dart';
import 'package:flutter/cupertino.dart';
import 'package:image_pickers/image_pickers.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../../community/release_dynamic.dart';
import '../../generated/l10n.dart';
import '../../utils/font_weight.dart';
@ -58,6 +60,19 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
// SmartDialog.showToast("聊天 $txt", alignment: Alignment.center);
}
List<Message> messages = [];
loadMessageList() async {
selfUserId = (await SharedPreferences.getInstance()).getString("userId");
toUserId = widget.arguments["toId"];
messages = await hxDatabase.queryUList(toUserId);
if (mounted) setState(() {});
}
String selfUserId = "";
String toUserId = "";
@override
void initState() {
super.initState();
@ -65,20 +80,21 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
WidgetsBinding.instance.addObserver(this);
commentFocus.addListener(_focusNodeListener);
loadMessageList();
Future.delayed(Duration.zero, () {
jumpToBottom();
});
}
void jumpToBottom() {
scrollController.position
.jumpTo(scrollController.position.maxScrollExtent);
scrollController.position.jumpTo(scrollController.position.maxScrollExtent);
}
void didChangeMetrics() {
WidgetsBinding.instance.addPostFrameCallback((_) {
isKeyBoardShow = MediaQuery.of(context).viewInsets.bottom > 0;
if (!mounted) return;
isKeyBoardShow = MediaQuery.of(context).viewInsets.bottom > 0;
if (MediaQuery.of(context).viewInsets.bottom == 0) {
if (isKeyBoardShow) {
FocusScope.of(context).requestFocus(FocusNode());
@ -241,7 +257,8 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
color: Colors.black,
size: 30,
),
)),
),
),
),
body: Container(
child: Column(
@ -263,7 +280,8 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
FocusScope.of(context).requestFocus(FocusNode());
});
},
child: chatDetailsList()),
child: chatDetailsList(),
),
],
),
),
@ -281,8 +299,9 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
return Container(
margin: EdgeInsets.only(bottom: 48.h),
child: ListView.builder(
itemCount: 10,
itemCount: messages.length,
shrinkWrap: true,
reverse: true,
physics: NeverScrollableScrollPhysics(),
itemBuilder: (context, position) {
return GestureDetector(
@ -292,15 +311,20 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
copyIndex = 0;
});
},
child: chatDetailsItem(),
child: chatDetailsItem(messages[position]),
);
}),
},
),
);
}
Widget chatDetailsItem() {
Widget chatDetailsItem(Message message) {
bool isSelf = message.fromId == selfUserId;
bool isText = message.msgType == 0;
return Container(
padding: EdgeInsets.only(top: 32.h,),
padding: EdgeInsets.only(
top: 32.h,
),
child: Column(
children: [
Text(
@ -312,6 +336,7 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
fontWeight: MyFontWeight.regular,
),
),
if (messages.indexOf(message) == (messages.length - 1))
Padding(
padding: EdgeInsets.only(top: 10.h, bottom: 24.h),
child: Text(
@ -324,6 +349,7 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
),
),
),
if (messages.indexOf(message) == (messages.length - 1))
SizedBox(
height: 16.h,
),
@ -339,7 +365,9 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
color: Color(0xFF2A2A2A),
borderRadius: BorderRadius.circular(6),
),
padding: EdgeInsets.symmetric(horizontal: 32.w,vertical: 7.5.h),
padding: EdgeInsets.symmetric(
horizontal: 32.w, vertical: 7.5.h,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
@ -358,7 +386,9 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
height: 16,
width: 16,
),
SizedBox(height: 2.h,),
SizedBox(
height: 2.h,
),
Text(
"复制",
textAlign: TextAlign.center,
@ -380,7 +410,9 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
height: 16,
width: 16,
),
SizedBox(height: 2.h,),
SizedBox(
height: 2.h,
),
Text(
S.of(context).shanchu,
textAlign: TextAlign.center,
@ -404,7 +436,11 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
),
],
),
Padding(padding:EdgeInsets.only(left: 17.w,right: 39.w),
/// not self
if (!isSelf && isText)
Padding(
padding: EdgeInsets.only(left: 17.w, right: 39.w),
child: Row(
children: [
// MImage(
@ -438,16 +474,16 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
)
],
),
padding: EdgeInsets.symmetric(vertical: 8.h, horizontal: 12.w),
padding: EdgeInsets.symmetric(
vertical: 8.h, horizontal: 12.w),
child: GestureDetector(
onLongPress: () {
setState(() {
copyIndex = 1;
});
},
child:
Text(
tex = "上次你在我这里买的水果钱是不是忘记付了?一共18块钱做点生意也是真的不容易啊。",
child: Text(
tex = message.content,
textAlign: TextAlign.left,
style: TextStyle(
height: 1.2.h,
@ -456,11 +492,14 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
fontWeight: MyFontWeight.medium,
),
),
)
)),
))),
],
),),
SizedBox(height: 40.h,),
),
),
if (!isSelf && isText)
SizedBox(
height: 40.h,
),
if (copyIndex == 1)
Stack(
alignment: Alignment.bottomCenter,
@ -473,7 +512,8 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
color: Color(0xFF2A2A2A),
borderRadius: BorderRadius.circular(6),
),
padding: EdgeInsets.symmetric(horizontal: 32.w,vertical: 7.5.h),
padding:
EdgeInsets.symmetric(horizontal: 32.w, vertical: 7.5.h),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
@ -492,7 +532,9 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
height: 16,
width: 16,
),
SizedBox(height: 2.h,),
SizedBox(
height: 2.h,
),
Text(
"复制",
textAlign: TextAlign.center,
@ -514,7 +556,9 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
height: 16,
width: 16,
),
SizedBox(height: 2.h,),
SizedBox(
height: 2.h,
),
Text(
S.of(context).shanchu,
textAlign: TextAlign.center,
@ -538,9 +582,14 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
),
],
),
Padding(padding:EdgeInsets.only(left:36.w,right: 16.w),
/// self
if (isSelf && isText)
Padding(
padding: EdgeInsets.only(left: 36.w, right: 16.w),
child: Row(
children: [
if (message.state == 3)
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(100),
@ -559,25 +608,28 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
),
),
),
if (message.state == 3)
SizedBox(
width: 12.w,
),
Expanded(
child: Container(
alignment: Alignment.centerRight,
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(6),
color: Color(0xFF32A060),
),
padding: EdgeInsets.symmetric(vertical: 8.h, horizontal: 12.w),
padding:
EdgeInsets.symmetric(vertical: 8.h, horizontal: 12.w),
child: GestureDetector(
onLongPress: () {
setState(() {
copyIndex = 1;
});
},
child:
Text(
tex = "凭本事买的为啥要给你钱啊伙计",
child: Text(
tex = message.content,
textAlign: TextAlign.left,
style: TextStyle(
height: 1.2.h,
@ -587,7 +639,9 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
),
),
),
)),
),
),
),
SizedBox(
width: 12.w,
),
@ -606,8 +660,13 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
width: 44,
),
],
)),
Padding(padding:EdgeInsets.only(left: 17.w,right: 39.w,top: 20.h),
),
),
/// not self image
if (!isSelf && !isText)
Padding(
padding: EdgeInsets.only(left: 17.w, right: 39.w, top: 20.h),
child: Row(
children: [
// MImage(
@ -644,8 +703,7 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
),
child: GestureDetector(
onLongPress: () {
setState((){
});
setState(() {});
},
child: Image.asset(
"assets/image/icon_guide_4.webp",
@ -653,11 +711,17 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
height: 200.h,
fit: BoxFit.fill,
),
))),
Expanded(
flex: 1,
child: Container(),
)
)),
Expanded(flex:1,child: Container(),)
],
),),
),
),
/// no reply long time
if (messages.indexOf(message) == 0)
Padding(
padding: EdgeInsets.only(left: 17.w, right: 17.w, top: 24.h),
child: Text(
@ -709,6 +773,13 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
if (commentText.trim() == "") {
return;
}
socketClient.sendMessage(toUserId, commentText).then((value) {
Message message = value;
messages.insert(0, message);
chatController.clear();
if (mounted)
setState(() {});
});
// widget.queryMemberComment(commentText);
},
maxLines: 8,
@ -850,13 +921,17 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
width: 24,
),
),
Padding(padding:EdgeInsets.only(top: 8.h),
Padding(
padding: EdgeInsets.only(top: 8.h),
child: Text(
"拍照",
style: TextStyle(
fontSize:12.sp, color: Color(0xFFA29E9E),
fontWeight: MyFontWeight.regular,),
),),
fontSize: 12.sp,
color: Color(0xFFA29E9E),
fontWeight: MyFontWeight.regular,
),
),
),
],
),
),
@ -887,16 +962,19 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
width: 24,
),
),
Padding(padding:EdgeInsets.only(top: 8.h),
Padding(
padding: EdgeInsets.only(top: 8.h),
child: Text(
"相册",
style: TextStyle(
fontSize:12.sp, color: Color(0xFFA29E9E),
fontWeight: MyFontWeight.regular,),
),),
],
)
fontSize: 12.sp,
color: Color(0xFFA29E9E),
fontWeight: MyFontWeight.regular,
),
),
),
],
)),
],
)
],
@ -915,7 +993,10 @@ class _ChatDetailsPage extends State<ChatDetailsPage>
return new AlertDialog(
backgroundColor: Color(0xFF2A2A2A),
elevation: 0,
contentPadding:EdgeInsets.only(top: 8.h,bottom: 5.h,),
contentPadding: EdgeInsets.only(
top: 8.h,
bottom: 5.h,
),
content: Container(
height: 40.h,
// width:20.w,

125
lib/im/database/hx_database.dart

@ -1,18 +1,123 @@
import 'dart:async';
import 'package:floor/floor.dart';
import 'package:flutter/cupertino.dart';
import 'package:huixiang/im/database/message_dao.dart';
import 'package:huixiang/im/database/message.dart';
import 'package:sqflite/sqflite.dart' as sqflite;
import 'package:huixiang/im/database/migration.dart';
import 'package:sqflite/sqflite.dart';
class HxDatabase {
Database db;
void open() async {
// _migrations.add(Migration(1, 2, (Database database) async {
// database.execute('ALTER TABLE `Message` ADD COLUMN `replyId` VARCHAR(20) DEFAULT NULL AFTER `toId`');
// }));
await openDatabase(
'hx.db',
version: 2,
onCreate: (Database db, int version) async {
db.execute('CREATE TABLE IF NOT EXISTS `Message` (`id` INTEGER, `fromId` VARCHAR(20), `toId` VARCHAR(20), `replyId` VARCHAR(20), `content` TEXT, `attach` TEXT, `msgType` INTEGER, `time` VARCHAR(20), `state` INTEGER, `isDelete` INTEGER, PRIMARY KEY (`id`))');
},
onConfigure: (database) async {
await database.execute('PRAGMA foreign_keys = ON');
},
onUpgrade: (database, startVersion, endVersion) async {
await runMigrations(database, startVersion, endVersion, _migrations);
},
onOpen: (Database db) {
this.db = db;
}
);
}
part 'hx_database.g.dart';
void close() {
db.close();
}
@Database(version: 1, entities: [Message])
abstract class HxDatabase extends FloorDatabase {
Future<List<Message>> queryList(userId) {
if (db == null) {
return Future.value(<Message>[]);
}
String sql = 'SELECT * FROM Message WHERE toId = ? OR fromId = ? GROUP BY toId,fromId ORDER BY time DESC';
return db.rawQuery(sql, [userId, userId]).then((value) {
return value.map((e) {
debugPrint("Message: ${e}");
return Message.fromJson(e);
}).toList();
}, onError: (error) {
debugPrint("Messageerror: $error");
});
}
MessageDao get messageDao;
Future<List<Message>> queryUList(userId) {
if (db == null) {
return Future.value(<Message>[]);
}
String sql = 'SELECT * FROM Message WHERE toId = ? OR fromId = ? ORDER BY time DESC';
return db.rawQuery(sql, [userId, userId]).then((value) {
return value.map((e) => Message.fromJson(e)).toList();
}, onError: (error) {
debugPrint("Messageerror: $error");
});
}
Future<List<Map>> queryListAll() {
if (db == null) {
return Future.value();
}
String sql = 'SELECT * FROM Message ORDER BY time DESC';
return db.rawQuery(sql);
}
Future<int> deleteAll() async {
return db.delete("Message");
}
update(Map<dynamic, dynamic> message) {
}
Future<int> insert(Map message) async {
if (db == null) {
return Future.value(0);
}
debugPrint("Messageinsert: ${message}");
return db.insert("Message", message);
}
final List<Migration> _migrations = [];
addMigrations(List<Migration> migrations) {
_migrations.addAll(migrations);
return this;
}
Future<void> runMigrations(
final Database migrationDatabase,
final int startVersion,
final int endVersion,
final List<Migration> migrations,
) async {
final relevantMigrations = migrations
.where((migration) => migration.startVersion >= startVersion)
.toList()
..sort(
(first, second) => first.startVersion.compareTo(second.startVersion));
if (relevantMigrations.isEmpty ||
relevantMigrations.last.endVersion != endVersion) {
throw StateError(
'There is no migration supplied to update the database to the current version.'
' Aborting the migration.',
);
}
for (final migration in relevantMigrations) {
await migration.migrate(migrationDatabase);
}
}
}

290
lib/im/database/hx_database.g.dart

@ -1,144 +1,146 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'hx_database.dart';
// **************************************************************************
// FloorGenerator
// **************************************************************************
// ignore: avoid_classes_with_only_static_members
class $FloorHxDatabase {
/// Creates a database builder for a persistent database.
/// Once a database is built, you should keep a reference to it and re-use it.
static _$HxDatabaseBuilder databaseBuilder(String name) =>
_$HxDatabaseBuilder(name);
/// Creates a database builder for an in memory database.
/// Information stored in an in memory database disappears when the process is killed.
/// Once a database is built, you should keep a reference to it and re-use it.
static _$HxDatabaseBuilder inMemoryDatabaseBuilder() =>
_$HxDatabaseBuilder(null);
}
class _$HxDatabaseBuilder {
_$HxDatabaseBuilder(this.name);
final String name;
final List<Migration> _migrations = [];
Callback _callback;
/// Adds migrations to the builder.
_$HxDatabaseBuilder addMigrations(List<Migration> migrations) {
_migrations.addAll(migrations);
return this;
}
/// Adds a database [Callback] to the builder.
_$HxDatabaseBuilder addCallback(Callback callback) {
_callback = callback;
return this;
}
/// Creates the database and initializes it.
Future<HxDatabase> build() async {
final path = name != null
? await sqfliteDatabaseFactory.getDatabasePath(name)
: ':memory:';
final database = _$HxDatabase();
database.database = await database.open(
path,
_migrations,
_callback,
);
return database;
}
}
class _$HxDatabase extends HxDatabase {
_$HxDatabase([StreamController<String> listener]) {
changeListener = listener ?? StreamController<String>.broadcast();
}
MessageDao _messageDaoInstance;
Future<sqflite.Database> open(
String path,
List<Migration> migrations, [
Callback callback,
]) async {
final databaseOptions = sqflite.OpenDatabaseOptions(
version: 1,
onConfigure: (database) async {
await database.execute('PRAGMA foreign_keys = ON');
await callback?.onConfigure?.call(database);
},
onOpen: (database) async {
await callback?.onOpen?.call(database);
},
onUpgrade: (database, startVersion, endVersion) async {
await MigrationAdapter.runMigrations(
database, startVersion, endVersion, migrations);
await callback?.onUpgrade?.call(database, startVersion, endVersion);
},
onCreate: (database, version) async {
await database.execute(
'CREATE TABLE IF NOT EXISTS `Message` (`id` INTEGER, `fromId` INTEGER, `toId` INTEGER, `content` TEXT, `attach` TEXT, `msgType` INTEGER, `time` INTEGER, `state` INTEGER, `isDelete` INTEGER, PRIMARY KEY (`id`))');
await callback?.onCreate?.call(database, version);
},
);
return sqfliteDatabaseFactory.openDatabase(path, options: databaseOptions);
}
@override
MessageDao get messageDao {
return _messageDaoInstance ??= _$MessageDao(database, changeListener);
}
}
class _$MessageDao extends MessageDao {
_$MessageDao(
this.database,
this.changeListener,
) : _queryAdapter = QueryAdapter(database, changeListener),
_messageInsertionAdapter = InsertionAdapter(
database,
'Message',
(Message item) => item.toJson(),
changeListener);
final sqflite.DatabaseExecutor database;
final StreamController<String> changeListener;
final QueryAdapter _queryAdapter;
final InsertionAdapter<Message> _messageInsertionAdapter;
@override
Stream<List<Message>> findMessageByToId(int toId) {
return _queryAdapter.queryListStream(
'SELECT * FROM Message WHERE toId = ?1',
mapper: (Map<String, Object> row) => Message.fromJson(row),
arguments: [toId],
queryableName: 'Message',
isView: false);
}
@override
Future<List<Message>> findMessageByGroup(int userId) {
debugPrint("findMessageByGroup: $userId");
return _queryAdapter.queryList(
'SELECT * FROM Message WHERE toId = ?1 OR fromId = ?2 GROUP BY toId,fromId ORDER BY time DESC',
mapper: (Map<String, Object> row) => Message.fromJson(row),
arguments: [userId, userId]);
}
@override
Future<void> insertMessage(Message message) async {
await _messageInsertionAdapter.insert(message, OnConflictStrategy.abort);
}
}
// // GENERATED CODE - DO NOT MODIFY BY HAND
//
// part of 'hx_database.dart';
//
// // **************************************************************************
// // FloorGenerator
// // **************************************************************************
//
// // ignore: avoid_classes_with_only_static_members
// import 'package:floor/floor.dart';
//
// class $FloorHxDatabase {
// /// Creates a database builder for a persistent database.
// /// Once a database is built, you should keep a reference to it and re-use it.
// static _$HxDatabaseBuilder databaseBuilder(String name) =>
// _$HxDatabaseBuilder(name);
//
// /// Creates a database builder for an in memory database.
// /// Information stored in an in memory database disappears when the process is killed.
// /// Once a database is built, you should keep a reference to it and re-use it.
// static _$HxDatabaseBuilder inMemoryDatabaseBuilder() =>
// _$HxDatabaseBuilder(null);
// }
//
// class _$HxDatabaseBuilder {
// _$HxDatabaseBuilder(this.name);
//
// final String name;
//
// final List<Migration> _migrations = [];
//
// Callback _callback;
//
// /// Adds migrations to the builder.
// _$HxDatabaseBuilder addMigrations(List<Migration> migrations) {
// _migrations.addAll(migrations);
// return this;
// }
//
// /// Adds a database [Callback] to the builder.
// _$HxDatabaseBuilder addCallback(Callback callback) {
// _callback = callback;
// return this;
// }
//
// /// Creates the database and initializes it.
// Future<HxDatabase> build() async {
// final path = name != null
// ? await sqfliteDatabaseFactory.getDatabasePath(name)
// : ':memory:';
// final database = _$HxDatabase();
// database.database = await database.open(
// path,
// _migrations,
// _callback,
// );
// return database;
// }
// }
//
// class _$HxDatabase extends HxDatabase {
// _$HxDatabase([StreamController<String> listener]) {
// changeListener = listener ?? StreamController<String>.broadcast();
// }
//
// MessageDao _messageDaoInstance;
//
// Future<sqflite.Database> open(
// String path,
// List<Migration> migrations, [
// Callback callback,
// ]) async {
// final databaseOptions = sqflite.OpenDatabaseOptions(
// version: 1,
// onConfigure: (database) async {
// await database.execute('PRAGMA foreign_keys = ON');
// await callback?.onConfigure?.call(database);
// },
// onOpen: (database) async {
// await callback?.onOpen?.call(database);
// },
// onUpgrade: (database, startVersion, endVersion) async {
// await MigrationAdapter.runMigrations(
// database, startVersion, endVersion, migrations);
//
// await callback?.onUpgrade?.call(database, startVersion, endVersion);
// },
// onCreate: (database, version) async {
// await database.execute(
// 'CREATE TABLE IF NOT EXISTS `Message` (`id` INTEGER, `fromId` INTEGER, `toId` INTEGER, `content` TEXT, `attach` TEXT, `msgType` INTEGER, `time` INTEGER, `state` INTEGER, `isDelete` INTEGER, PRIMARY KEY (`id`))');
//
// await callback?.onCreate?.call(database, version);
// },
// );
// return sqfliteDatabaseFactory.openDatabase(path, options: databaseOptions);
// }
//
// @override
// MessageDao get messageDao {
// return _messageDaoInstance ??= _$MessageDao(database, changeListener);
// }
// }
//
// class _$MessageDao extends MessageDao {
// _$MessageDao(
// this.database,
// this.changeListener,
// ) : _queryAdapter = QueryAdapter(database, changeListener),
// _messageInsertionAdapter = InsertionAdapter(
// database,
// 'Message',
// (Message item) => item.toJson(),
// changeListener);
//
// final sqflite.DatabaseExecutor database;
//
// final StreamController<String> changeListener;
//
// final QueryAdapter _queryAdapter;
//
// final InsertionAdapter<Message> _messageInsertionAdapter;
//
// @override
// Stream<List<Message>> findMessageByToId(int toId) {
// return _queryAdapter.queryListStream(
// 'SELECT * FROM Message WHERE toId = ?1',
// mapper: (Map<String, Object> row) => Message.fromJson(row),
// arguments: [toId],
// queryableName: 'Message',
// isView: false);
// }
//
// @override
// Future<List<Message>> findMessageByGroup(int userId) {
// debugPrint("findMessageByGroup: $userId");
// return _queryAdapter.queryList(
// 'SELECT * FROM Message WHERE toId = ?1 OR fromId = ?2 GROUP BY toId,fromId ORDER BY time DESC',
// mapper: (Map<String, Object> row) => Message.fromJson(row),
// arguments: [userId, userId]);
// }
//
// @override
// Future<void> insertMessage(Message message) async {
// await _messageInsertionAdapter.insert(message, OnConflictStrategy.abort);
// }
// }

24
lib/im/database/message.dart

@ -1,13 +1,12 @@
import 'package:floor/floor.dart';
@entity
class Message {
@primaryKey
int id;
int fromId;
String fromId;
int toId;
String toId;
String replyId;
String content;
@ -15,18 +14,19 @@ class Message {
int msgType;
int time;
String time;
int state;
int isDelete;
Message(id, fromId, toId, content, attach, msgType, time, state, isDelete);
Message(this.id, this.fromId, this.toId, this.replyId, this.content, this.attach, this.msgType, this.time, this.state, this.isDelete);
factory Message.fromJson(Map<String, dynamic> json) => Message(
json["id"],
json["fromId"],
json["toId"],
json["replyId"],
json["content"],
json["attach"],
json["msgType"],
@ -38,6 +38,7 @@ class Message {
"id": id,
"fromId": fromId,
"toId": toId,
"replyId": replyId,
"content": content,
"attach": attach,
"msgType": msgType,
@ -47,15 +48,16 @@ class Message {
};
}
createMessage(var toId, String content, {String attach, int msgType, userId}) {
return Message.fromJson(<String, dynamic>{
createMessage(var toId, String content, {String attach, int msgType, userId, replyId}) {
return <String, dynamic>{
"fromId": userId,
"toId": toId,
"replyId": replyId,
"content": content,
"attach": attach,
"msgType": msgType ?? 0,
"time": DateTime.now().millisecondsSinceEpoch,
"time": "${DateTime.now().millisecondsSinceEpoch}",
"state": 0,
"isDelete": 0
});
};
}

34
lib/im/database/message_dao.dart

@ -1,17 +1,17 @@
import 'package:floor/floor.dart';
import 'package:huixiang/im/database/message.dart';
@dao
abstract class MessageDao {
@Query('SELECT * FROM Message WHERE toId = :toId')
Stream<List<Message>> findMessageByToId(int toId);
@insert
Future<void> insertMessage(Message message);
@Query('SELECT * FROM Message WHERE toId = :userId OR fromId = :userId GROUP BY toId,fromId ORDER BY time DESC')
Future<List<Message>> findMessageByGroup(int userId);
}
// import 'package:floor/floor.dart';
// import 'package:huixiang/im/database/message.dart';
//
//
// @dao
// abstract class MessageDao {
//
// @Query('SELECT * FROM Message WHERE toId = :toId')
// Stream<List<Message>> findMessageByToId(int toId);
//
// @insert
// Future<void> insertMessage(Message message);
//
// @Query('SELECT * FROM Message WHERE toId = :userId OR fromId = :userId GROUP BY toId,fromId ORDER BY time DESC')
// Future<List<Message>> findMessageByGroup(int userId);
//
// }

41
lib/im/database/migration.dart

@ -0,0 +1,41 @@
import 'package:sqflite/sqflite.dart' as sqflite;
/// Base class for a database migration.
///
/// Each migration can move between 2 versions that are defined by
/// [startVersion] and [endVersion].
class Migration {
/// The start version of the database.
final int startVersion;
/// The start version of the database.
final int endVersion;
/// Function that performs the migration.
final Future<void> Function(sqflite.Database database) migrate;
/// Creates a new migration between [startVersion] and [endVersion].
/// [migrate] will be called by the database and performs the actual
/// migration.
Migration(this.startVersion, this.endVersion, this.migrate)
: assert(startVersion > 0),
assert(startVersion < endVersion);
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is Migration &&
runtimeType == other.runtimeType &&
startVersion == other.startVersion &&
endVersion == other.endVersion &&
migrate == other.migrate;
@override
int get hashCode =>
startVersion.hashCode ^ endVersion.hashCode ^ migrate.hashCode;
@override
String toString() {
return 'Migration{startVersion: $startVersion, endVersion: $endVersion, migrate: $migrate}';
}
}

31
lib/im/im_view/im_page.dart

@ -74,29 +74,20 @@ class _IMPage extends State<IMPage> implements OnChatMessage {
queryMsgStats();
}
List<int> userIds = [];
List<String> userIds = [];
Stream streamSubscription ;
loadMessageList() async {
int userId = 123456;
hxDatabase.changeListener.stream.listen((event) {
debugPrint("messages: 1111");
}, onError: (Object error, stackTrace) {
debugPrint("messages: 3333");
});
hxDatabase.changeListener.onListen = () {
debugPrint("messages: 2222");
};
messages = await hxDatabase.messageDao.findMessageByGroup(userId);
SharedPreferences shared = await SharedPreferences.getInstance();
String userId = shared.getString("userId");
messages = await hxDatabase.queryList(userId);
messages.forEach((element) {
debugPrint("messages: $element");
debugPrint("messages: ${element.toJson()}");
});
userIds = messages
.map((e) => e.toId != userId ? e.toId : e.fromId)
.toSet()
.toSet().where((element) => element != userId)
.toList();
if (mounted) {
setState(() {});
@ -289,7 +280,6 @@ class _IMPage extends State<IMPage> implements OnChatMessage {
child: TextField(
textInputAction: TextInputAction.search,
onEditingComplete: () {
socketClient.sendMessage(654321, "hello~");
FocusScope.of(context).requestFocus(FocusNode());
},
controller: imEditingController,
@ -331,7 +321,12 @@ class _IMPage extends State<IMPage> implements OnChatMessage {
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () {
Navigator.of(context).pushNamed('/router/chat_details_page');
Navigator.of(context).pushNamed(
'/router/chat_details_page',
arguments: {
"toId": userIds[position],
},
);
},
child: chatItem(userIds[position]),
);
@ -371,7 +366,7 @@ class _IMPage extends State<IMPage> implements OnChatMessage {
Expanded(
child: Text(
"喽哈 $userId",
overflow: TextOverflow.ellipsis,
overflow: TextOverflow.fade,
maxLines: 1,
style: TextStyle(
fontSize: 16.sp,

16
lib/im/out/auth.pb.dart

@ -15,7 +15,7 @@ import 'package:protobuf/protobuf.dart' as $pb;
class AuthReq extends $pb.GeneratedMessage {
factory AuthReq({
$core.int? uid,
$core.String? uid,
$core.String? token,
}) {
final $result = create();
@ -32,7 +32,7 @@ class AuthReq extends $pb.GeneratedMessage {
factory AuthReq.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r);
static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'AuthReq', createEmptyInstance: create)
..a<$core.int>(1, _omitFieldNames ? '' : 'uid', $pb.PbFieldType.OU3)
..aOS(1, _omitFieldNames ? '' : 'uid')
..aOS(2, _omitFieldNames ? '' : 'token')
..hasRequiredFields = false
;
@ -59,9 +59,9 @@ class AuthReq extends $pb.GeneratedMessage {
static AuthReq? _defaultInstance;
@$pb.TagNumber(1)
$core.int get uid => $_getIZ(0);
$core.String get uid => $_getSZ(0);
@$pb.TagNumber(1)
set uid($core.int v) { $_setUnsignedInt32(0, v); }
set uid($core.String v) { $_setString(0, v); }
@$pb.TagNumber(1)
$core.bool hasUid() => $_has(0);
@$pb.TagNumber(1)
@ -79,7 +79,7 @@ class AuthReq extends $pb.GeneratedMessage {
class AuthResp extends $pb.GeneratedMessage {
factory AuthResp({
$core.int? uid,
$core.String? uid,
$core.int? code,
$core.String? message,
}) {
@ -100,7 +100,7 @@ class AuthResp extends $pb.GeneratedMessage {
factory AuthResp.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r);
static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'AuthResp', createEmptyInstance: create)
..a<$core.int>(1, _omitFieldNames ? '' : 'uid', $pb.PbFieldType.OU3)
..aOS(1, _omitFieldNames ? '' : 'uid')
..a<$core.int>(2, _omitFieldNames ? '' : 'code', $pb.PbFieldType.OU3)
..aOS(3, _omitFieldNames ? '' : 'message')
..hasRequiredFields = false
@ -128,9 +128,9 @@ class AuthResp extends $pb.GeneratedMessage {
static AuthResp? _defaultInstance;
@$pb.TagNumber(1)
$core.int get uid => $_getIZ(0);
$core.String get uid => $_getSZ(0);
@$pb.TagNumber(1)
set uid($core.int v) { $_setUnsignedInt32(0, v); }
set uid($core.String v) { $_setString(0, v); }
@$pb.TagNumber(1)
$core.bool hasUid() => $_has(0);
@$pb.TagNumber(1)

8
lib/im/out/auth.pbjson.dart

@ -17,20 +17,20 @@ import 'dart:typed_data' as $typed_data;
const AuthReq$json = {
'1': 'AuthReq',
'2': [
{'1': 'uid', '3': 1, '4': 1, '5': 13, '10': 'uid'},
{'1': 'uid', '3': 1, '4': 1, '5': 9, '10': 'uid'},
{'1': 'token', '3': 2, '4': 1, '5': 9, '10': 'token'},
],
};
/// Descriptor for `AuthReq`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List authReqDescriptor = $convert.base64Decode(
'CgdBdXRoUmVxEhAKA3VpZBgBIAEoDVIDdWlkEhQKBXRva2VuGAIgASgJUgV0b2tlbg==');
'CgdBdXRoUmVxEhAKA3VpZBgBIAEoCVIDdWlkEhQKBXRva2VuGAIgASgJUgV0b2tlbg==');
@$core.Deprecated('Use authRespDescriptor instead')
const AuthResp$json = {
'1': 'AuthResp',
'2': [
{'1': 'uid', '3': 1, '4': 1, '5': 13, '10': 'uid'},
{'1': 'uid', '3': 1, '4': 1, '5': 9, '10': 'uid'},
{'1': 'code', '3': 2, '4': 1, '5': 13, '10': 'code'},
{'1': 'message', '3': 3, '4': 1, '5': 9, '10': 'message'},
],
@ -38,6 +38,6 @@ const AuthResp$json = {
/// Descriptor for `AuthResp`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List authRespDescriptor = $convert.base64Decode(
'CghBdXRoUmVzcBIQCgN1aWQYASABKA1SA3VpZBISCgRjb2RlGAIgASgNUgRjb2RlEhgKB21lc3'
'CghBdXRoUmVzcBIQCgN1aWQYASABKAlSA3VpZBISCgRjb2RlGAIgASgNUgRjb2RlEhgKB21lc3'
'NhZ2UYAyABKAlSB21lc3NhZ2U=');

16
lib/im/out/message.pb.dart

@ -19,8 +19,8 @@ export 'message.pbenum.dart';
class MsgData extends $pb.GeneratedMessage {
factory MsgData({
$core.int? to,
$core.int? from,
$core.String? to,
$core.String? from,
$core.int? ctime,
MsgType? type,
$core.List<$core.int>? data,
@ -48,8 +48,8 @@ class MsgData extends $pb.GeneratedMessage {
factory MsgData.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r);
static final $pb.BuilderInfo _i = $pb.BuilderInfo(_omitMessageNames ? '' : 'MsgData', createEmptyInstance: create)
..a<$core.int>(1, _omitFieldNames ? '' : 'to', $pb.PbFieldType.OU3)
..a<$core.int>(2, _omitFieldNames ? '' : 'from', $pb.PbFieldType.OU3)
..aOS(1, _omitFieldNames ? '' : 'to')
..aOS(2, _omitFieldNames ? '' : 'from')
..a<$core.int>(3, _omitFieldNames ? '' : 'ctime', $pb.PbFieldType.OU3)
..e<MsgType>(4, _omitFieldNames ? '' : 'type', $pb.PbFieldType.OE, defaultOrMaker: MsgType.SINGLE_TEXT, valueOf: MsgType.valueOf, enumValues: MsgType.values)
..a<$core.List<$core.int>>(5, _omitFieldNames ? '' : 'data', $pb.PbFieldType.OY)
@ -78,18 +78,18 @@ class MsgData extends $pb.GeneratedMessage {
static MsgData? _defaultInstance;
@$pb.TagNumber(1)
$core.int get to => $_getIZ(0);
$core.String get to => $_getSZ(0);
@$pb.TagNumber(1)
set to($core.int v) { $_setUnsignedInt32(0, v); }
set to($core.String v) { $_setString(0, v); }
@$pb.TagNumber(1)
$core.bool hasTo() => $_has(0);
@$pb.TagNumber(1)
void clearTo() => clearField(1);
@$pb.TagNumber(2)
$core.int get from => $_getIZ(1);
$core.String get from => $_getSZ(1);
@$pb.TagNumber(2)
set from($core.int v) { $_setUnsignedInt32(1, v); }
set from($core.String v) { $_setString(1, v); }
@$pb.TagNumber(2)
$core.bool hasFrom() => $_has(1);
@$pb.TagNumber(2)

6
lib/im/out/message.pbjson.dart

@ -33,8 +33,8 @@ final $typed_data.Uint8List msgTypeDescriptor = $convert.base64Decode(
const MsgData$json = {
'1': 'MsgData',
'2': [
{'1': 'to', '3': 1, '4': 1, '5': 13, '10': 'to'},
{'1': 'from', '3': 2, '4': 1, '5': 13, '10': 'from'},
{'1': 'to', '3': 1, '4': 1, '5': 9, '10': 'to'},
{'1': 'from', '3': 2, '4': 1, '5': 9, '10': 'from'},
{'1': 'ctime', '3': 3, '4': 1, '5': 13, '10': 'ctime'},
{'1': 'type', '3': 4, '4': 1, '5': 14, '6': '.MsgType', '10': 'type'},
{'1': 'data', '3': 5, '4': 1, '5': 12, '10': 'data'},
@ -43,7 +43,7 @@ const MsgData$json = {
/// Descriptor for `MsgData`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List msgDataDescriptor = $convert.base64Decode(
'CgdNc2dEYXRhEg4KAnRvGAEgASgNUgJ0bxISCgRmcm9tGAIgASgNUgRmcm9tEhQKBWN0aW1lGA'
'CgdNc2dEYXRhEg4KAnRvGAEgASgJUgJ0bxISCgRmcm9tGAIgASgJUgRmcm9tEhQKBWN0aW1lGA'
'MgASgNUgVjdGltZRIcCgR0eXBlGAQgASgOMgguTXNnVHlwZVIEdHlwZRISCgRkYXRhGAUgASgM'
'UgRkYXRh');

5
lib/main.dart

@ -221,7 +221,8 @@ void main() async {
HxDatabase hxDatabase;
initDatabase() async {
hxDatabase = await $FloorHxDatabase.databaseBuilder('huixiang_database.db').build();
hxDatabase = HxDatabase();
await hxDatabase.open();
}
final SocketClient socketClient = new SocketClient();
@ -505,7 +506,7 @@ Map<String, WidgetBuilder> routers = <String, WidgetBuilder>{
'/router/contacts_share': (context, {arguments}) =>
ContactsShare(arguments:arguments),
'/router/chat_details_page': (context, {arguments}) =>
ChatDetailsPage(),
ChatDetailsPage(arguments: arguments),
'/router/chat_setting': (context, {arguments}) =>
ChatSetting(),
'/router/chat_friend_group': (context, {arguments}) =>

1
lib/mine/edit_signature.dart

@ -2,7 +2,6 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:huixiang/generated/l10n.dart';
import 'package:huixiang/utils/font_weight.dart';
import 'package:huixiang/view_widget/my_appbar.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

42
pubspec.lock

@ -265,22 +265,6 @@ packages:
url: "https://pub.flutter-io.cn"
source: hosted
version: "3.0.2"
floor:
dependency: "direct main"
description:
name: floor
sha256: "52a8eac2c8d274e7c0c54251226f59786bb5b749365a2d8537d8095aa5132d92"
url: "https://pub.flutter-io.cn"
source: hosted
version: "1.4.2"
floor_annotation:
dependency: transitive
description:
name: floor_annotation
sha256: fa3fa4f198cdd1d922a69ceb06e54663fe59256bf1cb3c036eff206b445a6960
url: "https://pub.flutter-io.cn"
source: hosted
version: "1.4.2"
flutter:
dependency: "direct main"
description: flutter
@ -955,7 +939,7 @@ packages:
source: hosted
version: "1.9.1"
sqflite:
dependency: transitive
dependency: "direct main"
description:
name: sqflite
sha256: b4d6710e1200e96845747e37338ea8a819a12b51689a3bcf31eff0003b37a0b9
@ -970,30 +954,6 @@ packages:
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.4.5+1"
sqflite_common_ffi:
dependency: transitive
description:
name: sqflite_common_ffi
sha256: f86de82d37403af491b21920a696b19f01465b596f545d1acd4d29a0a72418ad
url: "https://pub.flutter-io.cn"
source: hosted
version: "2.2.5"
sqlite3:
dependency: transitive
description:
name: sqlite3
sha256: "281b672749af2edf259fc801f0fcba092257425bcd32a0ce1c8237130bc934c7"
url: "https://pub.flutter-io.cn"
source: hosted
version: "1.11.2"
sqlparser:
dependency: transitive
description:
name: sqlparser
sha256: "91f47610aa54d8abf9d795a7b4e49b2a788f65d7493d5a68fbf180c3cbcc6f38"
url: "https://pub.flutter-io.cn"
source: hosted
version: "0.27.0"
stack_trace:
dependency: transitive
description:

3
pubspec.yaml

@ -123,7 +123,8 @@ dependencies:
flutter_datetime_picker: ^1.5.1
widgetpicker: ^0.1.1
floor: ^1.4.2
# floor: ^1.4.2
sqflite: ^2.2.2
syncfusion_flutter_datepicker: ^19.4.38
protobuf: ^3.1.0

Loading…
Cancel
Save