Krille/use stream builder

This commit is contained in:
Christian Pauly 2020-05-09 05:17:55 +00:00
parent 125c262420
commit ad757cb56d
3 changed files with 607 additions and 604 deletions

View File

@ -1,4 +1,3 @@
import 'dart:async';
import 'dart:io'; import 'dart:io';
import 'package:famedlysdk/famedlysdk.dart'; import 'package:famedlysdk/famedlysdk.dart';
@ -131,14 +130,6 @@ class _ChatDetailsState extends State<ChatDetails> {
if (participants != null) setState(() => members = participants); if (participants != null) setState(() => members = participants);
} }
StreamSubscription onUpdate;
@override
void dispose() {
onUpdate?.cancel();
super.dispose();
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
if (widget.room == null) { if (widget.room == null) {
@ -156,14 +147,15 @@ class _ChatDetailsState extends State<ChatDetails> {
final int actualMembersCount = final int actualMembersCount =
widget.room.mInvitedMemberCount + widget.room.mJoinedMemberCount; widget.room.mInvitedMemberCount + widget.room.mJoinedMemberCount;
final bool canRequestMoreMembers = members.length < actualMembersCount; final bool canRequestMoreMembers = members.length < actualMembersCount;
this.onUpdate ??= widget.room.onUpdate.stream
.listen((id) => setState(() => members = null));
return AdaptivePageLayout( return AdaptivePageLayout(
primaryPage: FocusPage.SECOND, primaryPage: FocusPage.SECOND,
firstScaffold: ChatList( firstScaffold: ChatList(
activeChat: widget.room.id, activeChat: widget.room.id,
), ),
secondScaffold: Scaffold( secondScaffold: StreamBuilder(
stream: widget.room.onUpdate.stream,
builder: (context, snapshot) {
return Scaffold(
body: NestedScrollView( body: NestedScrollView(
headerSliverBuilder: headerSliverBuilder:
(BuildContext context, bool innerBoxIsScrolled) => <Widget>[ (BuildContext context, bool innerBoxIsScrolled) => <Widget>[
@ -184,7 +176,8 @@ class _ChatDetailsState extends State<ChatDetails> {
), ),
ChatSettingsPopupMenu(widget.room, false) ChatSettingsPopupMenu(widget.room, false)
], ],
title: Text(widget.room.getLocalizedDisplayname(L10n.of(context)), title: Text(
widget.room.getLocalizedDisplayname(L10n.of(context)),
style: TextStyle( style: TextStyle(
color: Theme.of(context) color: Theme.of(context)
.appBarTheme .appBarTheme
@ -194,14 +187,16 @@ class _ChatDetailsState extends State<ChatDetails> {
backgroundColor: Theme.of(context).appBarTheme.color, backgroundColor: Theme.of(context).appBarTheme.color,
flexibleSpace: FlexibleSpaceBar( flexibleSpace: FlexibleSpaceBar(
background: ContentBanner(widget.room.avatar, background: ContentBanner(widget.room.avatar,
onEdit: widget.room.canSendEvent("m.room.avatar") && !kIsWeb onEdit: widget.room.canSendEvent("m.room.avatar") &&
!kIsWeb
? () => setAvatarAction(context) ? () => setAvatarAction(context)
: null), : null),
), ),
), ),
], ],
body: ListView.builder( body: ListView.builder(
itemCount: members.length + 1 + (canRequestMoreMembers ? 1 : 0), itemCount:
members.length + 1 + (canRequestMoreMembers ? 1 : 0),
itemBuilder: (BuildContext context, int i) => i == 0 itemBuilder: (BuildContext context, int i) => i == 0
? Column( ? Column(
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
@ -209,13 +204,14 @@ class _ChatDetailsState extends State<ChatDetails> {
ListTile( ListTile(
leading: widget.room.canSendEvent("m.room.topic") leading: widget.room.canSendEvent("m.room.topic")
? CircleAvatar( ? CircleAvatar(
backgroundColor: backgroundColor: Theme.of(context)
Theme.of(context).scaffoldBackgroundColor, .scaffoldBackgroundColor,
foregroundColor: Colors.grey, foregroundColor: Colors.grey,
child: Icon(Icons.edit), child: Icon(Icons.edit),
) )
: null, : null,
title: Text("${L10n.of(context).groupDescription}:", title: Text(
"${L10n.of(context).groupDescription}:",
style: TextStyle( style: TextStyle(
color: Theme.of(context).primaryColor, color: Theme.of(context).primaryColor,
fontWeight: FontWeight.bold)), fontWeight: FontWeight.bold)),
@ -226,7 +222,10 @@ class _ChatDetailsState extends State<ChatDetails> {
linkStyle: TextStyle(color: Colors.blueAccent), linkStyle: TextStyle(color: Colors.blueAccent),
textStyle: TextStyle( textStyle: TextStyle(
fontSize: 14, fontSize: 14,
color: Theme.of(context).textTheme.bodyText2.color, color: Theme.of(context)
.textTheme
.bodyText2
.color,
), ),
), ),
onTap: widget.room.canSendEvent("m.room.topic") onTap: widget.room.canSendEvent("m.room.topic")
@ -251,12 +250,14 @@ class _ChatDetailsState extends State<ChatDetails> {
foregroundColor: Colors.grey, foregroundColor: Colors.grey,
child: Icon(Icons.people), child: Icon(Icons.people),
), ),
title: Text(L10n.of(context).changeTheNameOfTheGroup), title: Text(
L10n.of(context).changeTheNameOfTheGroup),
subtitle: Text(widget.room subtitle: Text(widget.room
.getLocalizedDisplayname(L10n.of(context))), .getLocalizedDisplayname(L10n.of(context))),
onTap: () => setDisplaynameAction(context), onTap: () => setDisplaynameAction(context),
), ),
if (widget.room.canSendEvent("m.room.canonical_alias") && if (widget.room
.canSendEvent("m.room.canonical_alias") &&
widget.room.joinRules == JoinRules.public) widget.room.joinRules == JoinRules.public)
ListTile( ListTile(
leading: CircleAvatar( leading: CircleAvatar(
@ -268,26 +269,28 @@ class _ChatDetailsState extends State<ChatDetails> {
onTap: () => setCanonicalAliasAction(context), onTap: () => setCanonicalAliasAction(context),
title: Text(L10n.of(context).setInvitationLink), title: Text(L10n.of(context).setInvitationLink),
subtitle: Text( subtitle: Text(
(widget.room.canonicalAlias?.isNotEmpty ?? false) (widget.room.canonicalAlias?.isNotEmpty ??
false)
? widget.room.canonicalAlias ? widget.room.canonicalAlias
: L10n.of(context).none), : L10n.of(context).none),
), ),
PopupMenuButton( PopupMenuButton(
child: ListTile( child: ListTile(
leading: CircleAvatar( leading: CircleAvatar(
backgroundColor: backgroundColor: Theme.of(context)
Theme.of(context).scaffoldBackgroundColor, .scaffoldBackgroundColor,
foregroundColor: Colors.grey, foregroundColor: Colors.grey,
child: Icon(Icons.public)), child: Icon(Icons.public)),
title: Text( title: Text(L10n.of(context)
L10n.of(context).whoIsAllowedToJoinThisGroup), .whoIsAllowedToJoinThisGroup),
subtitle: Text( subtitle: Text(
widget.room.joinRules widget.room.joinRules
.getLocalizedString(L10n.of(context)), .getLocalizedString(L10n.of(context)),
), ),
), ),
onSelected: (JoinRules joinRule) => onSelected: (JoinRules joinRule) =>
SimpleDialogs(context).tryRequestWithLoadingDialog( SimpleDialogs(context)
.tryRequestWithLoadingDialog(
widget.room.setJoinRules(joinRule), widget.room.setJoinRules(joinRule),
), ),
itemBuilder: (BuildContext context) => itemBuilder: (BuildContext context) =>
@ -314,16 +317,19 @@ class _ChatDetailsState extends State<ChatDetails> {
foregroundColor: Colors.grey, foregroundColor: Colors.grey,
child: Icon(Icons.visibility), child: Icon(Icons.visibility),
), ),
title: title: Text(L10n.of(context)
Text(L10n.of(context).visibilityOfTheChatHistory), .visibilityOfTheChatHistory),
subtitle: Text( subtitle: Text(
widget.room.historyVisibility widget.room.historyVisibility
.getLocalizedString(L10n.of(context)), .getLocalizedString(L10n.of(context)),
), ),
), ),
onSelected: (HistoryVisibility historyVisibility) => onSelected:
SimpleDialogs(context).tryRequestWithLoadingDialog( (HistoryVisibility historyVisibility) =>
widget.room.setHistoryVisibility(historyVisibility), SimpleDialogs(context)
.tryRequestWithLoadingDialog(
widget.room
.setHistoryVisibility(historyVisibility),
), ),
itemBuilder: (BuildContext context) => itemBuilder: (BuildContext context) =>
<PopupMenuEntry<HistoryVisibility>>[ <PopupMenuEntry<HistoryVisibility>>[
@ -357,13 +363,13 @@ class _ChatDetailsState extends State<ChatDetails> {
PopupMenuButton( PopupMenuButton(
child: ListTile( child: ListTile(
leading: CircleAvatar( leading: CircleAvatar(
backgroundColor: backgroundColor: Theme.of(context)
Theme.of(context).scaffoldBackgroundColor, .scaffoldBackgroundColor,
foregroundColor: Colors.grey, foregroundColor: Colors.grey,
child: Icon(Icons.info_outline), child: Icon(Icons.info_outline),
), ),
title: title: Text(
Text(L10n.of(context).areGuestsAllowedToJoin), L10n.of(context).areGuestsAllowedToJoin),
subtitle: Text( subtitle: Text(
widget.room.guestAccess widget.room.guestAccess
.getLocalizedString(L10n.of(context)), .getLocalizedString(L10n.of(context)),
@ -380,8 +386,8 @@ class _ChatDetailsState extends State<ChatDetails> {
PopupMenuItem<GuestAccess>( PopupMenuItem<GuestAccess>(
value: GuestAccess.can_join, value: GuestAccess.can_join,
child: Text( child: Text(
GuestAccess.can_join GuestAccess.can_join.getLocalizedString(
.getLocalizedString(L10n.of(context)), L10n.of(context)),
), ),
), ),
if (widget.room.canChangeGuestAccess) if (widget.room.canChangeGuestAccess)
@ -389,7 +395,8 @@ class _ChatDetailsState extends State<ChatDetails> {
value: GuestAccess.forbidden, value: GuestAccess.forbidden,
child: Text( child: Text(
GuestAccess.forbidden GuestAccess.forbidden
.getLocalizedString(L10n.of(context)), .getLocalizedString(
L10n.of(context)),
), ),
), ),
], ],
@ -412,7 +419,8 @@ class _ChatDetailsState extends State<ChatDetails> {
title: Text(L10n.of(context).inviteContact), title: Text(L10n.of(context).inviteContact),
leading: CircleAvatar( leading: CircleAvatar(
child: Icon(Icons.add), child: Icon(Icons.add),
backgroundColor: Theme.of(context).primaryColor, backgroundColor:
Theme.of(context).primaryColor,
foregroundColor: Colors.white, foregroundColor: Colors.white,
), ),
onTap: () => Navigator.of(context).push( onTap: () => Navigator.of(context).push(
@ -428,8 +436,10 @@ class _ChatDetailsState extends State<ChatDetails> {
: i < members.length + 1 : i < members.length + 1
? ParticipantListItem(members[i - 1]) ? ParticipantListItem(members[i - 1])
: ListTile( : ListTile(
title: Text(L10n.of(context).loadCountMoreParticipants( title: Text(L10n.of(context)
(actualMembersCount - members.length).toString())), .loadCountMoreParticipants(
(actualMembersCount - members.length)
.toString())),
leading: CircleAvatar( leading: CircleAvatar(
backgroundColor: backgroundColor:
Theme.of(context).scaffoldBackgroundColor, Theme.of(context).scaffoldBackgroundColor,
@ -442,7 +452,8 @@ class _ChatDetailsState extends State<ChatDetails> {
), ),
), ),
), ),
), );
}),
); );
} }
} }

View File

@ -1,5 +1,3 @@
import 'dart:async';
import 'package:famedlysdk/famedlysdk.dart'; import 'package:famedlysdk/famedlysdk.dart';
import 'package:fluffychat/components/adaptive_page_layout.dart'; import 'package:fluffychat/components/adaptive_page_layout.dart';
import 'package:fluffychat/components/avatar.dart'; import 'package:fluffychat/components/avatar.dart';
@ -35,28 +33,18 @@ class ChatEncryptionSettings extends StatefulWidget {
} }
class _ChatEncryptionSettingsState extends State<ChatEncryptionSettings> { class _ChatEncryptionSettingsState extends State<ChatEncryptionSettings> {
Room room;
StreamSubscription roomUpdate;
@override
void dispose() {
roomUpdate?.cancel();
super.dispose();
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
room ??= Matrix.of(context).client.getRoomById(widget.id); final room = Matrix.of(context).client.getRoomById(widget.id);
roomUpdate ??= room.onUpdate.stream.listen((s) => setState(() => null));
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
title: Text(L10n.of(context).participatingUserDevices), title: Text(L10n.of(context).participatingUserDevices),
), ),
body: Column( body: StreamBuilder(
children: <Widget>[ stream: room.onUpdate.stream,
FutureBuilder<List<DeviceKeys>>( builder: (context, snapshot) {
return FutureBuilder<List<DeviceKeys>>(
future: room.getUserDeviceKeys(), future: room.getUserDeviceKeys(),
builder: (BuildContext context, snapshot) { builder: (BuildContext context, snapshot) {
if (snapshot.hasError) { if (snapshot.hasError) {
@ -112,15 +100,17 @@ class _ChatEncryptionSettingsState extends State<ChatEncryptionSettings> {
.keys["ed25519:${deviceKeys[i].deviceId}"] .keys["ed25519:${deviceKeys[i].deviceId}"]
.beautified, .beautified,
style: TextStyle( style: TextStyle(
color: color: Theme.of(context)
Theme.of(context).textTheme.bodyText2.color), .textTheme
.bodyText2
.color),
), ),
value: deviceKeys[i].verified, value: deviceKeys[i].verified,
onChanged: (bool newVal) { onChanged: (bool newVal) {
if (newVal == true) { if (newVal == true) {
if (deviceKeys[i].blocked) { if (deviceKeys[i].blocked) {
deviceKeys[i] deviceKeys[i].setBlocked(
.setBlocked(false, Matrix.of(context).client); false, Matrix.of(context).client);
} }
deviceKeys[i] deviceKeys[i]
.setVerified(true, Matrix.of(context).client); .setVerified(true, Matrix.of(context).client);
@ -140,15 +130,8 @@ class _ChatEncryptionSettingsState extends State<ChatEncryptionSettings> {
), ),
); );
}, },
), );
Divider(thickness: 1, height: 1), }),
ListTile(
title: Text("Outbound MegOlm session ID:"),
subtitle: Text(
room.outboundGroupSession?.session_id()?.beautified ?? "None"),
),
],
),
); );
} }
} }

View File

@ -52,21 +52,17 @@ class ChatList extends StatefulWidget {
class _ChatListState extends State<ChatList> { class _ChatListState extends State<ChatList> {
bool get searchMode => searchController.text?.isNotEmpty ?? false; bool get searchMode => searchController.text?.isNotEmpty ?? false;
StreamSubscription sub;
final TextEditingController searchController = TextEditingController(); final TextEditingController searchController = TextEditingController();
SelectMode selectMode = SelectMode.normal;
Timer coolDown; Timer coolDown;
PublicRoomsResponse publicRoomsResponse; PublicRoomsResponse publicRoomsResponse;
bool loadingPublicRooms = false; bool loadingPublicRooms = false;
String searchServer; String searchServer;
Future<bool> waitForFirstSync(BuildContext context) async { Future<void> waitForFirstSync(BuildContext context) async {
Client client = Matrix.of(context).client; Client client = Matrix.of(context).client;
if (client.prevBatch?.isEmpty ?? true) { if (client.prevBatch?.isEmpty ?? true) {
await client.onFirstSync.stream.first; await client.onFirstSync.stream.first;
} }
sub ??= client.onSync.stream
.listen((s) => mounted ? setState(() => null) : null);
return true; return true;
} }
@ -205,29 +201,22 @@ class _ChatListState extends State<ChatList> {
@override @override
void dispose() { void dispose() {
sub?.cancel();
searchController.removeListener( searchController.removeListener(
() => setState(() => null), () => setState(() => null),
); );
_intentDataStreamSubscription?.cancel(); _intentDataStreamSubscription?.cancel();
_intentFileStreamSubscription?.cancel(); _intentFileStreamSubscription?.cancel();
_onShareContentChangedSub?.cancel();
super.dispose(); super.dispose();
} }
StreamSubscription _onShareContentChangedSub;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
_onShareContentChangedSub ??= Matrix.of(context) return StreamBuilder(
.onShareContentChanged stream: Matrix.of(context).onShareContentChanged.stream,
.stream builder: (context, snapshot) {
.listen((c) => setState(() => null)); final selectMode = Matrix.of(context).shareContent == null
if (Matrix.of(context).shareContent != null) { ? SelectMode.normal
selectMode = SelectMode.share; : SelectMode.share;
} else if (selectMode == SelectMode.share) {
setState(() => selectMode = SelectMode.normal);
}
return Scaffold( return Scaffold(
drawer: selectMode == SelectMode.share drawer: selectMode == SelectMode.share
? null ? null
@ -335,7 +324,8 @@ class _ChatListState extends State<ChatList> {
foregroundColor: Colors.white, foregroundColor: Colors.white,
backgroundColor: Colors.blue, backgroundColor: Colors.blue,
label: L10n.of(context).createNewGroup, label: L10n.of(context).createNewGroup,
labelStyle: TextStyle(fontSize: 18.0, color: Colors.black), labelStyle:
TextStyle(fontSize: 18.0, color: Colors.black),
onTap: () => Navigator.of(context).pushAndRemoveUntil( onTap: () => Navigator.of(context).pushAndRemoveUntil(
AppRoute.defaultRoute(context, NewGroupView()), AppRoute.defaultRoute(context, NewGroupView()),
(r) => r.isFirst), (r) => r.isFirst),
@ -345,30 +335,38 @@ class _ChatListState extends State<ChatList> {
foregroundColor: Colors.white, foregroundColor: Colors.white,
backgroundColor: Colors.green, backgroundColor: Colors.green,
label: L10n.of(context).newPrivateChat, label: L10n.of(context).newPrivateChat,
labelStyle: TextStyle(fontSize: 18.0, color: Colors.black), labelStyle:
TextStyle(fontSize: 18.0, color: Colors.black),
onTap: () => Navigator.of(context).pushAndRemoveUntil( onTap: () => Navigator.of(context).pushAndRemoveUntil(
AppRoute.defaultRoute(context, NewPrivateChatView()), AppRoute.defaultRoute(
context, NewPrivateChatView()),
(r) => r.isFirst), (r) => r.isFirst),
), ),
], ],
), ),
body: FutureBuilder<bool>( body: StreamBuilder(
stream: Matrix.of(context).client.onSync.stream,
builder: (context, snapshot) {
return FutureBuilder<void>(
future: waitForFirstSync(context), future: waitForFirstSync(context),
builder: (BuildContext context, snapshot) { builder: (BuildContext context, snapshot) {
if (snapshot.hasData) { if (snapshot.hasData) {
List<Room> rooms = List<Room>.from(Matrix.of(context).client.rooms); List<Room> rooms =
List<Room>.from(Matrix.of(context).client.rooms);
rooms.removeWhere((Room room) => rooms.removeWhere((Room room) =>
searchMode && searchMode &&
!room.displayname !room.displayname.toLowerCase().contains(
.toLowerCase() searchController.text.toLowerCase() ?? ""));
.contains(searchController.text.toLowerCase() ?? "")); if (rooms.isEmpty &&
if (rooms.isEmpty && (!searchMode || publicRoomsResponse == null)) { (!searchMode || publicRoomsResponse == null)) {
return Center( return Center(
child: Column( child: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: <Widget>[ children: <Widget>[
Icon( Icon(
searchMode ? Icons.search : Icons.chat_bubble_outline, searchMode
? Icons.search
: Icons.chat_bubble_outline,
size: 80, size: 80,
color: Colors.grey, color: Colors.grey,
), ),
@ -388,14 +386,18 @@ class _ChatListState extends State<ChatList> {
? Material( ? Material(
elevation: 2, elevation: 2,
child: ListTile( child: ListTile(
title: Text(L10n.of(context).publicRooms), title: Text(
L10n.of(context).publicRooms),
), ),
) )
: Container(), : Container(),
itemCount: totalCount + 1, itemCount: totalCount + 1,
itemBuilder: (BuildContext context, int i) { itemBuilder: (BuildContext context, int i) {
if (i == 0) { if (i == 0) {
return Matrix.of(context).client.statusList.isEmpty return Matrix.of(context)
.client
.statusList
.isEmpty
? Container() ? Container()
: PreferredSize( : PreferredSize(
preferredSize: Size.fromHeight(89), preferredSize: Size.fromHeight(89),
@ -403,10 +405,14 @@ class _ChatListState extends State<ChatList> {
height: 81, height: 81,
child: ListView.builder( child: ListView.builder(
scrollDirection: Axis.horizontal, scrollDirection: Axis.horizontal,
itemCount: itemCount: Matrix.of(context)
Matrix.of(context).client.statusList.length, .client
itemBuilder: (BuildContext context, int i) => .statusList
PresenceListItem(Matrix.of(context) .length,
itemBuilder:
(BuildContext context, int i) =>
PresenceListItem(
Matrix.of(context)
.client .client
.statusList[i]), .statusList[i]),
), ),
@ -417,10 +423,11 @@ class _ChatListState extends State<ChatList> {
return i < rooms.length return i < rooms.length
? ChatListItem( ? ChatListItem(
rooms[i], rooms[i],
activeChat: widget.activeChat == rooms[i].id, activeChat:
widget.activeChat == rooms[i].id,
) )
: PublicRoomListItem( : PublicRoomListItem(publicRoomsResponse
publicRoomsResponse.publicRooms[i - rooms.length]); .publicRooms[i - rooms.length]);
}); });
} else { } else {
return Center( return Center(
@ -428,7 +435,9 @@ class _ChatListState extends State<ChatList> {
); );
} }
}, },
),
); );
}),
);
});
} }
} }