fix: client state migrated to null

This commit is contained in:
Deven Joshi
2021-04-16 17:52:08 +05:30
parent 1aea44e568
commit e1ab168d33
3 changed files with 47 additions and 47 deletions
+21 -21
View File
@@ -58,12 +58,12 @@ class Channel {
/// Returns true if the channel is muted /// Returns true if the channel is muted
bool get isMuted => bool get isMuted =>
_client.state!.user?.channelMutes _client.state.user?.channelMutes
.any((element) => element.channel!.cid == cid) == .any((element) => element.channel!.cid == cid) ==
true; true;
/// Returns true if the channel is muted as a stream /// Returns true if the channel is muted as a stream
Stream<bool>? get isMutedStream => _client.state!.userStream.map((event) => Stream<bool>? get isMutedStream => _client.state.userStream.map((event) =>
event!.channelMutes.any((element) => element.channel!.cid == cid) == event!.channelMutes.any((element) => element.channel!.cid == cid) ==
true); true);
@@ -310,7 +310,7 @@ class Channel {
// ignore: parameter_assignments // ignore: parameter_assignments
message = message.copyWith( message = message.copyWith(
createdAt: message.createdAt, createdAt: message.createdAt,
user: _client.state!.user, user: _client.state.user,
quotedMessage: quotedMessage, quotedMessage: quotedMessage,
status: MessageSendingStatus.sending, status: MessageSendingStatus.sending,
attachments: message.attachments?.map( attachments: message.attachments?.map(
@@ -564,7 +564,7 @@ class Channel {
}) async { }) async {
final messageId = message.id; final messageId = message.id;
final now = DateTime.now(); final now = DateTime.now();
final user = _client.state!.user; final user = _client.state.user;
final latestReactions = [...message.latestReactions ?? <Reaction>[]]; final latestReactions = [...message.latestReactions ?? <Reaction>[]];
if (enforceUnique) { if (enforceUnique) {
@@ -629,7 +629,7 @@ class Channel {
Future<EmptyResponse?> deleteReaction( Future<EmptyResponse?> deleteReaction(
Message message, Reaction reaction) async { Message message, Reaction reaction) async {
final type = reaction.type; final type = reaction.type;
final user = _client.state!.user; final user = _client.state.user;
final reactionCounts = {...message.reactionCounts ?? <String, int>{}}; final reactionCounts = {...message.reactionCounts ?? <String, int>{}};
if (reactionCounts.containsKey(type)) { if (reactionCounts.containsKey(type)) {
@@ -805,8 +805,8 @@ class Channel {
/// Mark all channel messages as read /// Mark all channel messages as read
Future<EmptyResponse?> markRead() async { Future<EmptyResponse?> markRead() async {
_checkInitialized(); _checkInitialized();
client.state!.totalUnreadCount = max( client.state.totalUnreadCount = max(
0, (client.state!.totalUnreadCount ?? 0) - (state!.unreadCount ?? 0)); 0, (client.state.totalUnreadCount ?? 0) - (state!.unreadCount ?? 0));
state!._unreadCountController.add(0); state!._unreadCountController.add(0);
final response = await _client.post('$_channelURL/read', data: {}); final response = await _client.post('$_channelURL/read', data: {});
return _client.decode(response.data, EmptyResponse.fromJson); return _client.decode(response.data, EmptyResponse.fromJson);
@@ -841,7 +841,7 @@ class Channel {
void _initState(ChannelState channelState) { void _initState(ChannelState channelState) {
state = ChannelClientState(this, channelState); state = ChannelClientState(this, channelState);
client.state!.channels![cid] = this; client.state.channels![cid] = this;
if (!_initializedCompleter.isCompleted) { if (!_initializedCompleter.isCompleted) {
_initializedCompleter.complete(true); _initializedCompleter.complete(true);
} }
@@ -1274,7 +1274,7 @@ class ChannelClientState {
void _computeInitialUnread() { void _computeInitialUnread() {
final userRead = channelState?.read.firstWhereOrNull( final userRead = channelState?.read.firstWhereOrNull(
(r) => r.user.id == _channel._client.state?.user?.id, (r) => r.user.id == _channel._client.state.user?.id,
); );
if (userRead != null) { if (userRead != null) {
_unreadCountController.add(userRead.unreadMessages); _unreadCountController.add(userRead.unreadMessages);
@@ -1391,7 +1391,7 @@ class ChannelClientState {
void _listenReactionDeleted() { void _listenReactionDeleted() {
_subscriptions.add(_channel.on(EventType.reactionDeleted).listen((event) { _subscriptions.add(_channel.on(EventType.reactionDeleted).listen((event) {
final userId = _channel.client.state!.user!.id; final userId = _channel.client.state.user!.id;
final message = event.message!.copyWith( final message = event.message!.copyWith(
ownReactions: [...event.message!.latestReactions!] ownReactions: [...event.message!.latestReactions!]
..removeWhere((it) => it.userId != userId), ..removeWhere((it) => it.userId != userId),
@@ -1402,7 +1402,7 @@ class ChannelClientState {
void _listenReactions() { void _listenReactions() {
_subscriptions.add(_channel.on(EventType.reactionNew).listen((event) { _subscriptions.add(_channel.on(EventType.reactionNew).listen((event) {
final userId = _channel.client.state!.user!.id; final userId = _channel.client.state.user!.id;
final message = event.message!.copyWith( final message = event.message!.copyWith(
ownReactions: [...event.message!.latestReactions!] ownReactions: [...event.message!.latestReactions!]
..removeWhere((it) => it.userId != userId), ..removeWhere((it) => it.userId != userId),
@@ -1418,7 +1418,7 @@ class ChannelClientState {
EventType.reactionUpdated, EventType.reactionUpdated,
) )
.listen((event) { .listen((event) {
final userId = _channel.client.state!.user!.id; final userId = _channel.client.state.user!.id;
final message = event.message!.copyWith( final message = event.message!.copyWith(
ownReactions: [...event.message!.latestReactions!] ownReactions: [...event.message!.latestReactions!]
..removeWhere((it) => it.userId != userId), ..removeWhere((it) => it.userId != userId),
@@ -1512,7 +1512,7 @@ class ChannelClientState {
if (userReadIndex != null && userReadIndex != -1) { if (userReadIndex != null && userReadIndex != -1) {
final userRead = readList.removeAt(userReadIndex); final userRead = readList.removeAt(userReadIndex);
if (userRead.user.id == _channel._client.state!.user!.id) { if (userRead.user.id == _channel._client.state.user!.id) {
_unreadCountController.add(0); _unreadCountController.add(0);
} }
readList.add(Read( readList.add(Read(
@@ -1552,14 +1552,14 @@ class ChannelClientState {
/// Channel members list /// Channel members list
List<Member> get members => _channelState!.members List<Member> get members => _channelState!.members
.map((e) => e.copyWith(user: _channel.client.state!.users[e.user!.id])) .map((e) => e.copyWith(user: _channel.client.state.users[e.user!.id]))
.toList(); .toList();
/// Channel members list as a stream /// Channel members list as a stream
Stream<List<Member>> get membersStream => CombineLatestStream.combine2< Stream<List<Member>> get membersStream => CombineLatestStream.combine2<
List<Member?>?, Map<String?, User?>, List<Member>>( List<Member?>?, Map<String?, User?>, List<Member>>(
channelStateStream.map((cs) => cs!.members), channelStateStream.map((cs) => cs!.members),
_channel.client.state!.usersStream, _channel.client.state.usersStream,
(members, users) => (members, users) =>
members!.map((e) => e!.copyWith(user: users[e.user!.id])).toList(), members!.map((e) => e!.copyWith(user: users[e.user!.id])).toList(),
); );
@@ -1573,14 +1573,14 @@ class ChannelClientState {
/// Channel watchers list /// Channel watchers list
List<User> get watchers => _channelState!.watchers List<User> get watchers => _channelState!.watchers
.map((e) => _channel.client.state!.users[e.id] ?? e) .map((e) => _channel.client.state.users[e.id] ?? e)
.toList(); .toList();
/// Channel watchers list as a stream /// Channel watchers list as a stream
Stream<List<User>> get watchersStream => CombineLatestStream.combine2< Stream<List<User>> get watchersStream => CombineLatestStream.combine2<
List<User>?, Map<String?, User?>, List<User>>( List<User>?, Map<String?, User?>, List<User>>(
channelStateStream.map((cs) => cs!.watchers), channelStateStream.map((cs) => cs!.watchers),
_channel.client.state!.usersStream, _channel.client.state.usersStream,
(watchers, users) => watchers!.map((e) => users[e.id] ?? e).toList(), (watchers, users) => watchers!.map((e) => users[e.id] ?? e).toList(),
); );
@@ -1600,8 +1600,8 @@ class ChannelClientState {
int? get unreadCount => _unreadCountController.value; int? get unreadCount => _unreadCountController.value;
bool _countMessageAsUnread(Message message) { bool _countMessageAsUnread(Message message) {
final userId = _channel.client.state?.user?.id; final userId = _channel.client.state.user?.id;
final userIsMuted = _channel.client.state?.user?.mutes.firstWhereOrNull( final userIsMuted = _channel.client.state.user?.mutes.firstWhereOrNull(
(m) => m.user?.id == message.user!.id, (m) => m.user?.id == message.user!.id,
) != ) !=
null; null;
@@ -1763,7 +1763,7 @@ class ChannelClientState {
..add( ..add(
_channel.on(EventType.typingStart).listen( _channel.on(EventType.typingStart).listen(
(event) { (event) {
if (event.user!.id != _channel.client.state!.user!.id) { if (event.user!.id != _channel.client.state.user!.id) {
_typings[event.user] = DateTime.now(); _typings[event.user] = DateTime.now();
_typingEventsController.add(_typings.keys.toList()); _typingEventsController.add(_typings.keys.toList());
} }
@@ -1773,7 +1773,7 @@ class ChannelClientState {
..add( ..add(
_channel.on(EventType.typingStop).listen( _channel.on(EventType.typingStop).listen(
(event) { (event) {
if (event.user!.id != _channel.client.state!.user!.id) { if (event.user!.id != _channel.client.state.user!.id) {
_typings.remove(event.user); _typings.remove(event.user);
_typingEventsController.add(_typings.keys.toList()); _typingEventsController.add(_typings.keys.toList());
} }
+23 -23
View File
@@ -134,7 +134,7 @@ class StreamChatClient {
RetryPolicy? get retryPolicy => _retryPolicy; RetryPolicy? get retryPolicy => _retryPolicy;
/// This client state /// This client state
ClientState? state; late final ClientState state;
/// By default the Chat client will write all messages with level Warn or /// By default the Chat client will write all messages with level Warn or
/// Error to stdout. /// Error to stdout.
@@ -301,7 +301,7 @@ class StreamChatClient {
if (tokenProvider != null) { if (tokenProvider != null) {
httpClient.lock(); httpClient.lock();
final userId = state!.user!.id; final userId = state.user!.id;
await _disconnect(); await _disconnect();
@@ -389,7 +389,7 @@ class StreamChatClient {
await _disconnect(); await _disconnect();
httpClient.close(); httpClient.close();
await _controller.close(); await _controller.close();
state!.dispose(); state.dispose();
await _wsConnectionStatusController.close(); await _wsConnectionStatusController.close();
} }
@@ -424,7 +424,7 @@ class StreamChatClient {
throw e; throw e;
} }
state!.user = OwnUser.fromJson(user.toJson()); state.user = OwnUser.fromJson(user.toJson());
this.token = token; this.token = token;
_anonymous = false; _anonymous = false;
@@ -490,11 +490,11 @@ class StreamChatClient {
} }
if (event.user != null) { if (event.user != null) {
state!._updateUser(event.user); state._updateUser(event.user);
} }
if (event.me != null) { if (event.me != null) {
state!.user = event.me; state.user = event.me;
} }
_controller.add(event); _controller.add(event);
} }
@@ -518,12 +518,12 @@ class StreamChatClient {
if (_originalChatPersistenceClient != null) { if (_originalChatPersistenceClient != null) {
_chatPersistenceClient = _originalChatPersistenceClient; _chatPersistenceClient = _originalChatPersistenceClient;
await _chatPersistenceClient!.connect(state!.user!.id); await _chatPersistenceClient!.connect(state.user!.id);
} }
_ws = WebSocket( _ws = WebSocket(
baseUrl: baseURL, baseUrl: baseURL,
user: state!.user, user: state.user,
connectParams: { connectParams: {
'api_key': apiKey, 'api_key': apiKey,
'authorization': token, 'authorization': token,
@@ -531,7 +531,7 @@ class StreamChatClient {
'X-Stream-Client': _userAgent, 'X-Stream-Client': _userAgent,
}, },
connectPayload: { connectPayload: {
'user_id': state!.user!.id, 'user_id': state.user!.id,
'server_determines_connection_id': true, 'server_determines_connection_id': true,
}, },
handler: handleEvent, handler: handleEvent,
@@ -552,11 +552,11 @@ class StreamChatClient {
type: EventType.connectionRecovered, type: EventType.connectionRecovered,
online: true, online: true,
)); ));
if (state!.channels?.isNotEmpty == true) { if (state.channels?.isNotEmpty == true) {
// ignore: unawaited_futures // ignore: unawaited_futures
queryChannelsOnline(filter: { queryChannelsOnline(filter: {
'cid': { 'cid': {
'\$in': state!.channels!.keys.toList(), '\$in': state.channels!.keys.toList(),
}, },
}).then( }).then(
(_) async { (_) async {
@@ -757,7 +757,7 @@ class StreamChatClient {
.map((it) => it.user) .map((it) => it.user)
.toList(growable: false); .toList(growable: false);
state!._updateUsers(users); state._updateUsers(users);
logger.info('Got ${res.channels?.length} channels from api'); logger.info('Got ${res.channels?.length} channels from api');
@@ -769,7 +769,7 @@ class StreamChatClient {
clearQueryCache: paginationParams.offset == 0, clearQueryCache: paginationParams.offset == 0,
); );
state!.channels = updateData.key; state.channels = updateData.key;
return updateData.value; return updateData.value;
} }
@@ -785,19 +785,19 @@ class StreamChatClient {
paginationParams: paginationParams, paginationParams: paginationParams,
))!; ))!;
final updatedData = _mapChannelStateToChannel(offlineChannels); final updatedData = _mapChannelStateToChannel(offlineChannels);
state!.channels = updatedData.key; state.channels = updatedData.key;
return updatedData.value; return updatedData.value;
} }
MapEntry<Map<String?, Channel>, List<Channel>> _mapChannelStateToChannel( MapEntry<Map<String?, Channel>, List<Channel>> _mapChannelStateToChannel(
List<ChannelState> channelStates, List<ChannelState> channelStates,
) { ) {
final channels = {...state!.channels ?? {}}; final channels = {...state.channels ?? {}};
final newChannels = <Channel>[]; final newChannels = <Channel>[];
for (final channelState in channelStates) { for (final channelState in channelStates) {
final channel = channels[channelState.channel!.cid]; final channel = channels[channelState.channel!.cid];
if (channel != null) { if (channel != null) {
channel.state?.updateChannelState(channelState); channel.state!.updateChannelState(channelState);
newChannels.add(channel); newChannels.add(channel);
} else { } else {
final newChannel = Channel.fromState(this, channelState); final newChannel = Channel.fromState(this, channelState);
@@ -931,7 +931,7 @@ class StreamChatClient {
'${PACKAGE_VERSION.split('+')[0]}'; '${PACKAGE_VERSION.split('+')[0]}';
Map<String, String?> get _commonQueryParams => { Map<String, String?> get _commonQueryParams => {
'user_id': state!.user?.id, 'user_id': state.user?.id,
'api_key': apiKey, 'api_key': apiKey,
'connection_id': _connectionId, 'connection_id': _connectionId,
}; };
@@ -955,7 +955,7 @@ class StreamChatClient {
_anonymous = true; _anonymous = true;
const uuid = Uuid(); const uuid = Uuid();
state!.user = OwnUser(id: uuid.v4()); state.user = OwnUser(id: uuid.v4());
return connect().then((event) { return connect().then((event) {
_connectCompleter!.complete(event); _connectCompleter!.complete(event);
@@ -1003,7 +1003,7 @@ class StreamChatClient {
_connectCompleter = null; _connectCompleter = null;
if (clearUser == true) { if (clearUser == true) {
state!.dispose(); state.dispose();
state = ClientState(this); state = ClientState(this);
} }
@@ -1053,7 +1053,7 @@ class StreamChatClient {
QueryUsersResponse.fromJson, QueryUsersResponse.fromJson,
); );
state?._updateUsers(response.users!); state._updateUsers(response.users!);
return response; return response;
} }
@@ -1195,9 +1195,9 @@ class StreamChatClient {
String? id, String? id,
Map<String, dynamic>? extraData, Map<String, dynamic>? extraData,
}) { }) {
if (id != null && state!.channels?.containsKey('$type:$id') == true) { if (id != null && state.channels?.containsKey('$type:$id') == true) {
if (state!.channels!['$type:$id'] != null) { if (state.channels!['$type:$id'] != null) {
return state!.channels!['$type:$id'] as Channel; return state.channels!['$type:$id'] as Channel;
} }
} }
@@ -566,7 +566,7 @@ void main() {
tokenProvider: (_) async => '', tokenProvider: (_) async => '',
); );
client.state?.user = OwnUser(id: 'test-id'); client.state.user = OwnUser(id: 'test-id');
final channelClient = client.channel('messaging', id: 'testid'); final channelClient = client.channel('messaging', id: 'testid');
const reactionType = 'test'; const reactionType = 'test';
@@ -617,7 +617,7 @@ void main() {
tokenProvider: (_) async => '', tokenProvider: (_) async => '',
); );
client.state?.user = OwnUser(id: 'test-id'); client.state.user = OwnUser(id: 'test-id');
final channelClient = client.channel('messaging', id: 'testid'); final channelClient = client.channel('messaging', id: 'testid');
@@ -639,7 +639,7 @@ void main() {
type: 'test', type: 'test',
createdAt: DateTime.now(), createdAt: DateTime.now(),
user: User( user: User(
id: client.state?.user?.id ?? '', id: client.state.user?.id ?? '',
), ),
), ),
); );