Merge branch 'feature/new-ui' into feature/image-detail

This commit is contained in:
Deven Joshi
2020-11-23 16:40:51 +05:30
committed by GitHub
41 changed files with 3532 additions and 1013 deletions
+257 -104
View File
@@ -4,6 +4,7 @@ import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:shimmer/shimmer.dart';
import 'package:stream_chat/stream_chat.dart';
import 'package:stream_chat_flutter/src/channels_bloc.dart';
import 'package:stream_chat_flutter/src/utils.dart';
@@ -67,7 +68,9 @@ class ChannelListView extends StatefulWidget {
this.channelPreviewBuilder,
this.separatorBuilder,
this.errorBuilder,
this.emptyBuilder,
this.onImageTap,
this.onStartChatPressed,
this.swipeToAction = false,
this.pullToRefresh = true,
}) : super(key: key);
@@ -78,6 +81,9 @@ class ChannelListView extends StatefulWidget {
/// If true a default swipe to action behaviour will be added to this widget
final bool swipeToAction;
/// The builder used when the channel list is empty.
final WidgetBuilder emptyBuilder;
/// The query filters to use.
/// You can query on any of the custom fields you've defined on the [Channel].
/// You can also filter other built-in channel fields.
@@ -124,6 +130,9 @@ class ChannelListView extends StatefulWidget {
/// Set it to false to disable the pull-to-refresh widget
final bool pullToRefresh;
/// Callback used in the default empty list widget
final VoidCallback onStartChatPressed;
@override
_ChannelListViewState createState() => _ChannelListViewState();
}
@@ -159,123 +168,265 @@ class _ChannelListViewState extends State<ChannelListView>
return StreamBuilder<List<Channel>>(
stream: channelsBlocState.channelsStream,
builder: (context, snapshot) {
var child;
if (snapshot.hasError) {
if (snapshot.error is Error) {
print((snapshot.error as Error).stackTrace);
child = _buildErrorWidget(
snapshot,
context,
channelsBlocState,
);
} else if (!snapshot.hasData) {
child = _buildLoadingWidget();
} else {
final channels = snapshot.data;
if (channels.isEmpty && widget.emptyBuilder != null) {
child = widget.emptyBuilder(context);
}
if (widget.errorBuilder != null) {
return widget.errorBuilder(snapshot.error);
}
var message = snapshot.error.toString();
if (snapshot.error is DioError) {
final dioError = snapshot.error as DioError;
if (dioError.type == DioErrorType.RESPONSE) {
message = dioError.message;
} else {
message = 'Check your connection and retry';
}
}
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text.rich(
TextSpan(
if (channels.isEmpty && widget.emptyBuilder == null) {
child = LayoutBuilder(
builder: (context, viewportConstraints) {
return SingleChildScrollView(
physics: AlwaysScrollableScrollPhysics(),
child: Stack(
children: [
WidgetSpan(
child: Padding(
padding: const EdgeInsets.only(
right: 2.0,
),
child: Icon(Icons.error_outline),
ConstrainedBox(
constraints: BoxConstraints(
minHeight: viewportConstraints.maxHeight,
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Icon(
StreamIcons.message,
size: 136,
color: Color(0xffDBDBDB),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'Lets start chatting!',
style: TextStyle(
fontSize: 16,
),
),
),
Padding(
padding: const EdgeInsets.symmetric(
vertical: 8.0,
horizontal: 52,
),
child: Text(
'How about sending your first message to a friend?',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 14,
color: Color(0xff7A7A7A),
),
),
),
],
),
),
TextSpan(text: 'Error loading channels'),
if (widget.onStartChatPressed != null)
Positioned(
right: 0,
left: 0,
bottom: 32,
child: Center(
child: FlatButton(
onPressed: widget.onStartChatPressed,
child: Text(
'Start a chat',
style: TextStyle(
color:
StreamChatTheme.of(context).accentColor,
fontWeight: FontWeight.bold,
),
),
),
),
),
],
),
style: Theme.of(context).textTheme.headline6,
),
Padding(
padding: const EdgeInsets.only(
top: 16.0,
),
child: Text(message),
),
FlatButton(
onPressed: () {
channelsBlocState.queryChannels(
filter: widget.filter,
sortOptions: widget.sort,
paginationParams: widget.pagination,
options: widget.options,
);
},
child: Text('Retry'),
),
],
),
);
);
},
);
}
if (channels.isNotEmpty) {
child = ListView.custom(
physics: AlwaysScrollableScrollPhysics(),
controller: _scrollController,
childrenDelegate: SliverChildBuilderDelegate(
(context, i) {
return _itemBuilder(context, i, channels);
},
childCount: (channels.length * 2) + 1,
findChildIndexCallback: (key) {
final ValueKey<String> valueKey = key;
final index = channels.indexWhere(
(channel) => 'CHANNEL-${channel.id}' == valueKey.value);
return index != -1 ? (index * 2) : null;
},
),
);
}
}
if (!snapshot.hasData) {
return LayoutBuilder(
builder: (context, viewportConstraints) {
return SingleChildScrollView(
physics: AlwaysScrollableScrollPhysics(),
child: ConstrainedBox(
constraints: BoxConstraints(
minHeight: viewportConstraints.maxHeight,
),
child: Center(
child: CircularProgressIndicator(),
),
),
);
},
);
}
final channels = snapshot.data;
if (channels.isEmpty) {
return LayoutBuilder(
builder: (context, viewportConstraints) {
return SingleChildScrollView(
physics: AlwaysScrollableScrollPhysics(),
child: ConstrainedBox(
constraints: BoxConstraints(
minHeight: viewportConstraints.maxHeight,
),
child: Center(
child: Text('You have no channels currently'),
),
),
);
},
);
}
return ListView.custom(
physics: AlwaysScrollableScrollPhysics(),
controller: _scrollController,
childrenDelegate: SliverChildBuilderDelegate(
(context, i) {
return _itemBuilder(context, i, channels);
},
childCount: (channels.length * 2) + 1,
findChildIndexCallback: (key) {
final ValueKey<String> valueKey = key;
final index = channels.indexWhere(
(channel) => 'CHANNEL-${channel.id}' == valueKey.value);
return index != -1 ? (index * 2) : null;
},
),
return AnimatedSwitcher(
child: child,
duration: Duration(milliseconds: 500),
);
});
}
Widget _buildLoadingWidget() {
return ListView(
physics: AlwaysScrollableScrollPhysics(),
children: List.generate(
25,
(i) {
if (i % 2 != 0) {
if (widget.separatorBuilder != null) {
return widget.separatorBuilder(context, i);
}
return _separatorBuilder(context, i);
}
return _buildLoadingItem();
},
),
);
}
Shimmer _buildLoadingItem() {
return Shimmer.fromColors(
baseColor: Color(0xffE5E5E5),
highlightColor: Color(0xffffffff),
child: ListTile(
leading: Container(
decoration: BoxDecoration(
color: Colors.white,
shape: BoxShape.circle,
),
constraints: BoxConstraints.tightFor(
height: 40,
width: 40,
),
),
title: Align(
alignment: Alignment.centerLeft,
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(11),
),
constraints: BoxConstraints.tightFor(
height: 16,
width: 82,
),
),
),
subtitle: Row(
children: [
Align(
alignment: Alignment.centerLeft,
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(11),
),
constraints: BoxConstraints.tightFor(
height: 16,
width: 238,
),
),
),
Container(
margin: const EdgeInsets.only(left: 16),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(11),
),
constraints: BoxConstraints.tightFor(
height: 16,
width: 42,
),
),
],
),
),
);
}
Widget _buildErrorWidget(
AsyncSnapshot<List<Channel>> snapshot,
BuildContext context,
ChannelsBlocState channelsBlocState,
) {
if (snapshot.error is Error) {
print((snapshot.error as Error).stackTrace);
}
if (widget.errorBuilder != null) {
return widget.errorBuilder(snapshot.error);
}
var message = snapshot.error.toString();
if (snapshot.error is DioError) {
final dioError = snapshot.error as DioError;
if (dioError.type == DioErrorType.RESPONSE) {
message = dioError.message;
} else {
message = 'Check your connection and retry';
}
}
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text.rich(
TextSpan(
children: [
WidgetSpan(
child: Padding(
padding: const EdgeInsets.only(
right: 2.0,
),
child: Icon(Icons.error_outline),
),
),
TextSpan(text: 'Error loading channels'),
],
),
style: Theme.of(context).textTheme.headline6,
),
Padding(
padding: const EdgeInsets.only(
top: 16.0,
),
child: Text(message),
),
FlatButton(
onPressed: () {
channelsBlocState.queryChannels(
filter: widget.filter,
sortOptions: widget.sort,
paginationParams: widget.pagination,
options: widget.options,
);
},
child: Text('Retry'),
),
],
),
);
}
Widget _itemBuilder(context, int i, List<Channel> channels) {
if (i % 2 != 0) {
if (widget.separatorBuilder != null) {
@@ -433,7 +584,9 @@ class _ChannelListViewState extends State<ChannelListView>
}
Widget _buildQueryProgressIndicator(
context, ChannelsBlocState channelsProvider) {
context,
ChannelsBlocState channelsProvider,
) {
return StreamBuilder<bool>(
stream: channelsProvider.queryChannelsLoading,
initialData: false,
+1 -1
View File
@@ -31,7 +31,7 @@ class ChannelsBloc extends StatefulWidget {
streamChatState = context.findAncestorStateOfType<ChannelsBlocState>();
if (streamChatState == null) {
throw Exception('You must have a ChannelsBloc widget as anchestor');
throw Exception('You must have a ChannelsBloc widget as ancestor');
}
return streamChatState;
+248 -269
View File
@@ -41,219 +41,209 @@ class GiphyAttachment extends StatelessWidget {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
DecoratedBox(
decoration: BoxDecoration(),
child: Card(
elevation: 2,
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topRight: Radius.circular(16.0),
bottomRight: Radius.circular(0.0),
topLeft: Radius.circular(16.0),
bottomLeft: Radius.circular(16.0),
),
Card(
elevation: 2,
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topRight: Radius.circular(16.0),
bottomRight: Radius.circular(0.0),
topLeft: Radius.circular(16.0),
bottomLeft: Radius.circular(16.0),
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Stack(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: GestureDetector(
onTap: () {
final channel = StreamChannel.of(context).channel;
Navigator.push(context,
MaterialPageRoute(builder: (_) {
return StreamChannel(
channel: channel,
child: FullScreenImage(
urls: [attachment.imageUrl ??
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
Stack(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: GestureDetector(
onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (_) {
return FullScreenImage(
urls: [attachment.imageUrl ??
attachment.assetUrl ??
attachment.thumbUrl],
userName: message.user.name,
sentAt: message.createdAt,
message: message,
),
);
}));
},
child: CachedNetworkImage(
height: size?.height,
width: size?.width,
placeholder: (_, __) {
return Container(
width: size?.width,
height: size?.height,
child: Center(
child: CircularProgressIndicator(),
),
);
},
imageUrl: attachment.thumbUrl ??
attachment.imageUrl ??
attachment.assetUrl,
errorWidget: (context, url, error) => AttachmentError(
attachment: attachment,
size: size,
),
fit: BoxFit.cover,
),
),
),
Positioned(
left: 0,
top: 0,
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
bottomRight: Radius.circular(16.0),
)),
child: Padding(
padding: const EdgeInsets.only(
left: 8.0,
right: 8.0,
top: 8.0,
bottom: 4.0,
),
child: Row(
children: [
Icon(
StreamIcons.lightning,
color: StreamChatTheme.of(context).accentColor,
size: 16.0,
),
Text(
'GIPHY',
style: TextStyle(
color:
StreamChatTheme.of(context).accentColor,
fontWeight: FontWeight.bold,
fontSize: 11.0,
),
),
],
),
),
),
),
],
),
if (attachment.title != null)
Container(
alignment: Alignment.bottomCenter,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Card(
elevation: 2,
child: IconButton(
padding: const EdgeInsets.all(0),
constraints: BoxConstraints.tight(Size(32, 32)),
icon: Icon(
StreamIcons.left,
size: 24.0,
),
splashRadius: 16,
onPressed: () {
streamChannel.channel.sendAction(message, {
'image_action': 'shuffle',
});
},
),
shape: CircleBorder(),
),
Expanded(
);
}));
},
child: CachedNetworkImage(
height: size?.height,
width: size?.width,
placeholder: (_, __) {
return Container(
width: size?.width,
height: size?.height,
child: Center(
child: Text(
'"${attachment.title}"',
style: TextStyle(
fontStyle: FontStyle.italic,
),
),
child: CircularProgressIndicator(),
),
),
Card(
elevation: 2,
child: IconButton(
padding: const EdgeInsets.all(0),
constraints: BoxConstraints.tight(Size(32, 32)),
icon: Icon(
StreamIcons.right,
size: 24.0,
),
splashRadius: 16,
onPressed: () {
streamChannel.channel.sendAction(message, {
'image_action': 'shuffle',
});
},
),
shape: CircleBorder(),
),
],
);
},
imageUrl: attachment.thumbUrl ??
attachment.imageUrl ??
attachment.assetUrl,
errorWidget: (context, url, error) => AttachmentError(
attachment: attachment,
size: size,
),
fit: BoxFit.cover,
),
),
),
SizedBox(
height: 4.0,
),
Container(
color: Colors.black.withOpacity(0.2),
width: double.infinity,
height: 0.5,
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: FlatButton(
height: 50,
onPressed: () {
streamChannel.channel.sendAction(message, {
'image_action': 'cancel',
});
},
child: Text(
'Cancel',
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.black.withOpacity(0.5)),
Positioned(
left: 0,
top: 0,
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
bottomRight: Radius.circular(16.0),
)),
child: Padding(
padding: const EdgeInsets.only(
left: 8.0,
right: 8.0,
top: 8.0,
bottom: 4.0,
),
),
),
Container(
width: 0.5,
color: Colors.black.withOpacity(0.2),
height: 50.0,
),
Expanded(
child: FlatButton(
height: 50,
onPressed: () {
streamChannel.channel.sendAction(message, {
'image_action': 'send',
});
},
child: Text(
'Send',
style: TextStyle(
child: Row(
children: [
Icon(
StreamIcons.lightning,
color: StreamChatTheme.of(context).accentColor,
fontWeight: FontWeight.bold),
size: 16.0,
),
Text(
'GIPHY',
style: TextStyle(
color: StreamChatTheme.of(context).accentColor,
fontWeight: FontWeight.bold,
fontSize: 11.0,
),
),
],
),
),
),
],
),
],
),
if (attachment.title != null)
Container(
alignment: Alignment.bottomCenter,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Card(
elevation: 2,
child: IconButton(
padding: const EdgeInsets.all(0),
constraints: BoxConstraints.tight(Size(32, 32)),
icon: Icon(
StreamIcons.left,
size: 24.0,
),
splashRadius: 16,
onPressed: () {
streamChannel.channel.sendAction(message, {
'image_action': 'shuffle',
});
},
),
shape: CircleBorder(),
),
Expanded(
child: Center(
child: Text(
'"${attachment.title}"',
style: TextStyle(
fontStyle: FontStyle.italic,
),
),
),
),
Card(
elevation: 2,
child: IconButton(
padding: const EdgeInsets.all(0),
constraints: BoxConstraints.tight(Size(32, 32)),
icon: Icon(
StreamIcons.right,
size: 24.0,
),
splashRadius: 16,
onPressed: () {
streamChannel.channel.sendAction(message, {
'image_action': 'shuffle',
});
},
),
shape: CircleBorder(),
),
],
),
),
),
],
),
SizedBox(
height: 4.0,
),
Container(
color: Colors.black.withOpacity(0.2),
width: double.infinity,
height: 0.5,
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(
child: FlatButton(
height: 50,
onPressed: () {
streamChannel.channel.sendAction(message, {
'image_action': 'cancel',
});
},
child: Text(
'Cancel',
style: TextStyle(
fontWeight: FontWeight.bold,
color: Colors.black.withOpacity(0.5)),
),
),
),
Container(
width: 0.5,
color: Colors.black.withOpacity(0.2),
height: 50.0,
),
Expanded(
child: FlatButton(
height: 50,
onPressed: () {
streamChannel.channel.sendAction(message, {
'image_action': 'send',
});
},
child: Text(
'Send',
style: TextStyle(
color: StreamChatTheme.of(context).accentColor,
fontWeight: FontWeight.bold),
),
),
),
],
),
],
),
),
SizedBox(
@@ -291,88 +281,77 @@ class GiphyAttachment extends StatelessWidget {
Widget _buildSentAttachment(context) {
return Container(
child: Column(
children: [
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.only(
topRight: Radius.circular(16.0),
bottomRight: Radius.circular(0.0),
topLeft: Radius.circular(16.0),
bottomLeft: Radius.circular(16.0),
),
),
clipBehavior: Clip.antiAlias,
child: GestureDetector(
onTap: () {
final channel = StreamChannel.of(context).channel;
Navigator.push(context, MaterialPageRoute(builder: (_) {
return StreamChannel(
channel: channel,
child: FullScreenImage(
urls: [attachment.imageUrl ??
child: GestureDetector(
onTap: () {
Navigator.push(context, MaterialPageRoute(builder: (_) {
return FullScreenImage(
urls: [attachment.imageUrl ??
attachment.assetUrl ??
attachment.thumbUrl],
userName: message.user.name,
sentAt: message.createdAt,
message: message,
),
);
}));
);
}));
},
child: Stack(
children: [
CachedNetworkImage(
height: size?.height,
width: size?.width,
placeholder: (_, __) {
return Container(
width: size?.width,
height: size?.height,
child: Center(
child: CircularProgressIndicator(),
),
);
},
child: CachedNetworkImage(
height: size?.height,
width: size?.width,
placeholder: (_, __) {
return Container(
width: size?.width,
height: size?.height,
child: Center(
child: CircularProgressIndicator(),
),
);
},
imageUrl: attachment.thumbUrl ??
attachment.imageUrl ??
attachment.assetUrl,
errorWidget: (context, url, error) => AttachmentError(
attachment: attachment,
size: size,
imageUrl: attachment.thumbUrl ??
attachment.imageUrl ??
attachment.assetUrl,
errorWidget: (context, url, error) => AttachmentError(
attachment: attachment,
size: size,
),
fit: BoxFit.cover,
),
Positioned(
bottom: 8,
left: 8,
child: Material(
color: Colors.black.withOpacity(.5),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 8.0,
vertical: 4.0,
),
child: Row(
children: [
Icon(
StreamIcons.lightning,
color: Colors.white,
size: 16,
),
Text(
'GIPHY',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 11,
),
),
],
),
),
fit: BoxFit.cover,
),
),
),
Padding(
padding: const EdgeInsets.only(
top: 8.0,
bottom: 8,
),
child: Row(
children: [
Row(
children: [
Icon(
StreamIcons.lightning,
color: StreamChatTheme.of(context).accentColor,
size: 15.0,
),
Text(
'GIPHY',
style: TextStyle(
color: StreamChatTheme.of(context).accentColor,
fontWeight: FontWeight.bold,
fontSize: 11.0,
),
),
],
),
],
mainAxisAlignment: MainAxisAlignment.start,
),
)
],
],
),
),
);
}
+18 -4
View File
@@ -46,9 +46,16 @@ class GroupImage extends StatelessWidget {
.take(2)
.map((url) => Flexible(
fit: FlexFit.tight,
child: CachedNetworkImage(
imageUrl: url,
child: FittedBox(
fit: BoxFit.cover,
clipBehavior: Clip.antiAlias,
child: Transform.scale(
scale: 1.2,
child: CachedNetworkImage(
imageUrl: url,
fit: BoxFit.cover,
),
),
),
))
.toList(),
@@ -64,9 +71,16 @@ class GroupImage extends StatelessWidget {
.skip(2)
.map((url) => Flexible(
fit: FlexFit.tight,
child: CachedNetworkImage(
imageUrl: url,
child: FittedBox(
fit: BoxFit.cover,
clipBehavior: Clip.antiAlias,
child: Transform.scale(
scale: 1.2,
child: CachedNetworkImage(
imageUrl: url,
fit: BoxFit.cover,
),
),
),
))
.toList(),
+147
View File
@@ -0,0 +1,147 @@
import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:media_gallery/media_gallery.dart';
import 'package:stream_chat_flutter/src/stream_icons.dart';
import 'package:transparent_image/transparent_image.dart';
class MediaListView extends StatefulWidget {
final List<String> selectedIds;
final void Function(Media media) onSelect;
const MediaListView({
Key key,
this.selectedIds = const [],
this.onSelect,
}) : super(key: key);
@override
_MediaListViewState createState() => _MediaListViewState();
}
class _MediaListViewState extends State<MediaListView> {
final _media = <Media>[];
final ScrollController _scrollController = ScrollController();
@override
Widget build(BuildContext context) {
return GridView.builder(
itemCount: _media.length,
controller: _scrollController,
gridDelegate:
SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3),
itemBuilder: (
context,
position,
) {
final media = _media.elementAt(position);
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 1.0, vertical: 1.0),
child: InkWell(
child: Stack(
children: [
AspectRatio(
aspectRatio: 1.0,
child: FadeInImage(
fadeInDuration: Duration(milliseconds: 300),
placeholder: MemoryImage(kTransparentImage),
image: MediaThumbnailProvider(
media: media,
highQuality: true,
),
fit: BoxFit.cover,
),
),
Positioned.fill(
child: IgnorePointer(
child: AnimatedOpacity(
duration: Duration(milliseconds: 300),
opacity: widget.selectedIds.any((id) => id == media.id)
? 1.0
: 0.0,
child: Container(
color: Colors.black.withOpacity(0.5),
alignment: Alignment.topRight,
padding: const EdgeInsets.only(
top: 8,
right: 8,
),
child: CircleAvatar(
radius: 12,
backgroundColor: Colors.white,
child: Icon(
StreamIcons.check,
size: 24,
color: Colors.black,
),
),
),
),
),
),
if (media.mediaType == MediaType.video)
Positioned(
left: 8,
bottom: 10,
child: SvgPicture.asset(
'svgs/video_call_icon.svg',
package: 'stream_chat_flutter',
),
),
],
),
onTap: () {
if (widget.onSelect != null) {
widget.onSelect(media);
}
},
),
);
},
);
}
@override
void initState() {
super.initState();
_getMedia();
}
void _getMedia() async {
final List<MediaCollection> collections =
await MediaGallery.listMediaCollections(
mediaTypes: [
MediaType.video,
MediaType.image,
],
);
if (collections.isEmpty) {
return;
}
final collection = collections.firstWhere(
(element) => element.isAllCollection,
orElse: () => collections.first,
);
final videoPage = await collection.getMedias(
mediaType: MediaType.video,
take: 500,
);
final imagePage = await collection.getMedias(
mediaType: MediaType.image,
take: 500,
);
final allItems = [
...videoPage.items,
...imagePage.items,
]..sort((
a,
b,
) =>
b.creationDate.compareTo(a.creationDate));
setState(() {
_media.addAll(allItems);
});
}
}
+7 -6
View File
@@ -45,14 +45,15 @@ class MessageActionsModal extends StatelessWidget {
@override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
var user = StreamChat.of(context).user;
final size = MediaQuery.of(context).size;
final user = StreamChat.of(context).user;
var roughMaxSize = 2 * size.width / 3;
var roughSentenceSize =
final roughMaxSize = 2 * size.width / 3;
final roughSentenceSize =
message.text.length * messageTheme.messageText.fontSize * 1.2;
var divFactor =
roughSentenceSize == 0 ? 1 : (roughSentenceSize / roughMaxSize);
final divFactor = message.attachments?.isNotEmpty == true
? 1
: (roughSentenceSize == 0 ? 1 : (roughSentenceSize / roughMaxSize));
return GestureDetector(
behavior: HitTestBehavior.translucent,
+525 -194
View File
@@ -1,4 +1,5 @@
import 'dart:async';
import 'dart:io';
import 'dart:math';
import 'package:emojis/emoji.dart';
@@ -8,13 +9,17 @@ import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:http_parser/http_parser.dart';
import 'package:http_parser/http_parser.dart' as httpParser;
import 'package:image_picker/image_picker.dart';
import 'package:media_gallery/media_gallery.dart';
import 'package:mime/mime.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:stream_chat/stream_chat.dart';
import 'package:stream_chat_flutter/src/media_list_view.dart';
import 'package:stream_chat_flutter/src/message_list_view.dart';
import 'package:stream_chat_flutter/src/stream_chat_theme.dart';
import 'package:stream_chat_flutter/src/user_avatar.dart';
import 'package:stream_chat_flutter/src/video_thumbnail.dart';
import 'package:substring_highlight/substring_highlight.dart';
import '../stream_chat_flutter.dart';
@@ -37,6 +42,8 @@ enum DefaultAttachmentTypes {
file,
}
const _kMinMediaPickerSize = 360.0;
/// Inactive state
/// ![screenshot](https://raw.githubusercontent.com/GetStream/stream-chat-flutter/master/screenshots/message_input.png)
/// ![screenshot](https://raw.githubusercontent.com/GetStream/stream-chat-flutter/master/screenshots/message_input_paint.png)
@@ -97,6 +104,7 @@ class MessageInput extends StatefulWidget {
this.actions,
this.actionsLocation = ActionsLocation.left,
this.attachmentThumbnailBuilders,
this.focusNode,
}) : super(key: key);
/// Message to edit
@@ -142,6 +150,9 @@ class MessageInput extends StatefulWidget {
/// Map that defines a thumbnail builder for an attachment type
final Map<String, AttachmentThumbnailBuilder> attachmentThumbnailBuilders;
/// The focus node associated to the TextField
final FocusNode focusNode;
@override
MessageInputState createState() => MessageInputState();
@@ -162,13 +173,13 @@ class MessageInput extends StatefulWidget {
class MessageInputState extends State<MessageInput> {
final List<_SendingAttachment> _attachments = [];
final _focusNode = FocusNode();
final List<User> _mentionedUsers = [];
final _imagePicker = ImagePicker();
FocusNode _focusNode;
bool _inputEnabled = true;
bool _messageIsPresent = false;
bool _typingStarted = false;
bool _animateContainer = true;
bool _commandEnabled = false;
OverlayEntry _commandsOverlay, _mentionsOverlay, _emojiOverlay;
Iterable<String> _emojiNames;
@@ -176,6 +187,9 @@ class MessageInputState extends State<MessageInput> {
Command _chosenCommand;
bool _actionsShrunk = false;
bool _sendAsDm = false;
bool _openFilePickerSection = false;
int _filePickerIndex = 0;
double _filePickerSize = _kMinMediaPickerSize;
/// The editing controller passed to the input TextField
TextEditingController textEditingController;
@@ -201,6 +215,7 @@ class MessageInputState extends State<MessageInput> {
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: _buildDmCheckbox(),
),
_buildFilePickerSection(),
],
),
),
@@ -210,7 +225,7 @@ class MessageInputState extends State<MessageInput> {
Flex _buildTextField(BuildContext context) {
return Flex(
direction: Axis.horizontal,
crossAxisAlignment: CrossAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
if (!_commandEnabled) _buildExpandActionsButton(),
if (widget.actionsLocation == ActionsLocation.left)
@@ -333,7 +348,7 @@ class MessageInputState extends State<MessageInput> {
child: Container(
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(32.0),
borderRadius: BorderRadius.circular(20.0),
border: Border.all(
color: Colors.grey,
),
@@ -355,40 +370,11 @@ class MessageInputState extends State<MessageInput> {
keyboardType: widget.keyboardType,
controller: textEditingController,
focusNode: _focusNode,
onChanged: (s) {
StreamChannel.of(context).channel.keyStroke();
setState(() {
_messageIsPresent = s.trim().isNotEmpty;
_actionsShrunk = s.trim().isNotEmpty;
});
_commandsOverlay?.remove();
_commandsOverlay = null;
_mentionsOverlay?.remove();
_mentionsOverlay = null;
_emojiOverlay?.remove();
_emojiOverlay = null;
_checkCommands(s.trimLeft(), context);
_checkMentions(s, context);
_checkEmoji(s, context);
},
onTap: () {
setState(() {
_typingStarted = true;
});
},
style: Theme.of(context).textTheme.bodyText2,
autofocus: false,
textAlignVertical: TextAlignVertical.center,
decoration: InputDecoration(
hintText:
(_commandEnabled && _chosenCommand.name == 'giphy')
? 'Search GIFs'
: 'Write a message',
hintText: _getHint(),
prefixText: _commandEnabled ? null : ' ',
border: OutlineInputBorder(
borderSide: BorderSide(color: Colors.transparent)),
@@ -440,15 +426,47 @@ class MessageInputState extends State<MessageInput> {
);
}
void _onChanged(BuildContext context, String s) {
StreamChannel.of(context).channel.keyStroke().catchError((e) {});
setState(() {
_messageIsPresent = s.trim().isNotEmpty;
_actionsShrunk = s.trim().isNotEmpty;
});
_commandsOverlay?.remove();
_commandsOverlay = null;
_mentionsOverlay?.remove();
_mentionsOverlay = null;
_emojiOverlay?.remove();
_emojiOverlay = null;
_checkCommands(s.trim(), context);
_checkMentions(s, context);
_checkEmoji(s, context);
}
String _getHint() {
if (_commandEnabled && _chosenCommand.name == 'giphy') {
return 'Search GIFs';
}
if (_attachments.isNotEmpty) {
return 'Add a comment or send';
}
return 'Write a message';
}
void _checkEmoji(String s, BuildContext context) {
if (textEditingController.selection.isCollapsed &&
(s.isNotEmpty && s[textEditingController.selection.start - 1] == ':' ||
textEditingController.text
.substring(
0,
textEditingController.selection.start,
)
.contains(':'))) {
if (s.isNotEmpty &&
textEditingController.selection.baseOffset > 0 &&
textEditingController.text
.substring(
0,
textEditingController.selection.baseOffset,
)
.contains(':')) {
final textToSelection = textEditingController.text
.substring(0, textEditingController.value.selection.start);
final splits = textToSelection.split(':');
@@ -468,13 +486,13 @@ class MessageInputState extends State<MessageInput> {
}
void _checkMentions(String s, BuildContext context) {
if (textEditingController.selection.isCollapsed &&
(s.isNotEmpty && s[textEditingController.selection.start - 1] == '@' ||
textEditingController.text
.substring(0, textEditingController.selection.start)
.split(' ')
.last
.contains('@'))) {
if (s.isNotEmpty &&
textEditingController.selection.baseOffset > 0 &&
textEditingController.text
.substring(0, textEditingController.selection.baseOffset)
.split(' ')
.last
.contains('@')) {
_mentionsOverlay = _buildMentionsOverlayEntry();
Overlay.of(context).insert(_mentionsOverlay);
}
@@ -548,8 +566,10 @@ class MessageInputState extends State<MessageInput> {
Padding(
padding:
const EdgeInsets.symmetric(horizontal: 8.0),
child: Icon(StreamIcons.lightning,
color: StreamChatTheme.of(context).accentColor),
child: Icon(
StreamIcons.lightning,
color: StreamChatTheme.of(context).accentColor,
),
),
Text(
'Instant Commands',
@@ -604,6 +624,257 @@ class MessageInputState extends State<MessageInput> {
});
}
Widget _buildFilePickerSection() {
return AnimatedContainer(
duration: _animateContainer ? Duration(milliseconds: 300) : Duration.zero,
height: _openFilePickerSection ? _filePickerSize : 0,
child: Material(
color: Color(0xFFF2F2F2),
child: Column(
children: [
Row(
mainAxisAlignment: MainAxisAlignment.start,
children: [
IconButton(
icon: Icon(
StreamIcons.picture,
size: 24,
color: _filePickerIndex == 0
? StreamChatTheme.of(context).accentColor
: Colors.black.withOpacity(0.5),
),
onPressed: () {
setState(() {
_filePickerIndex = 0;
});
},
),
IconButton(
icon: Icon(
StreamIcons.folder,
size: 24,
color: _filePickerIndex == 1
? StreamChatTheme.of(context).accentColor
: Colors.black.withOpacity(0.5),
),
onPressed: () {
pickFile(DefaultAttachmentTypes.file, false);
},
),
IconButton(
icon: SvgPicture.asset(
'svgs/icon_camera.svg',
package: 'stream_chat_flutter',
height: 24,
width: 24,
color: _filePickerIndex == 2
? StreamChatTheme.of(context).accentColor
: Colors.black.withOpacity(0.5),
),
onPressed: () {
pickFile(DefaultAttachmentTypes.image, true);
},
),
IconButton(
icon: Icon(
StreamIcons.record,
size: 24,
color: _filePickerIndex == 2
? StreamChatTheme.of(context).accentColor
: Colors.black.withOpacity(0.5),
),
onPressed: () {
pickFile(DefaultAttachmentTypes.video, true);
},
),
],
),
GestureDetector(
onVerticalDragUpdate: (update) {
setState(() {
_animateContainer = false;
_filePickerSize = (_filePickerSize - update.delta.dy).clamp(
_kMinMediaPickerSize,
MediaQuery.of(context).size.height / 1.7,
);
});
},
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(16.0),
topRight: Radius.circular(16.0),
),
),
child: Container(
width: double.infinity,
child: Center(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
width: 40.0,
height: 4.0,
decoration: BoxDecoration(
color: Color(0xFFF2F2F2),
borderRadius: BorderRadius.circular(4.0),
),
),
),
),
),
),
),
if (_openFilePickerSection)
Expanded(
child: Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(8.0),
),
child: _buildPickerSection(),
),
),
],
),
),
);
}
Widget _buildPickerSection() {
switch (_filePickerIndex) {
case 0:
return FutureBuilder<PermissionStatus>(
future: Platform.isAndroid
? Permission.storage.status
: Permission.photos.status,
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
if (snapshot.data.isGranted) {
return MediaListView(
selectedIds: _attachments.map((e) => e.id).toList(),
onSelect: (media) {
if (!_attachments
.any((element) => element.id == media.id)) {
_addAttachment(media);
} else {
setState(() {
_attachments
.removeWhere((element) => element.id == media.id);
});
}
},
);
}
return InkWell(
onTap: () async {
var status = await (Platform.isAndroid
? Permission.storage.status
: Permission.photos.status);
print('status: ${status}');
if (status.isPermanentlyDenied || status.isDenied) {
if (await openAppSettings()) {
setState(() {});
}
} else {
status = await (Platform.isAndroid
? Permission.storage
: Permission.photos)
.request();
if (status.isGranted) {
setState(() {});
}
}
},
child: Container(
color: Color(0xFFF2F2F2),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
SvgPicture.asset(
'svgs/icon_picture_empty_state.svg',
package: 'stream_chat_flutter',
height: 140,
color: StreamChatTheme.of(context).accentColor,
),
Center(
child: Text(
'Allow access to your gallery',
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
color: StreamChatTheme.of(context).accentColor,
),
),
),
],
),
),
);
});
break;
}
}
void _addAttachment(Media medium) async {
final attachment = _SendingAttachment(
id: medium.id,
);
setState(() {
_attachments.add(attachment);
});
final mediaFile = await medium.getFile();
final file = PlatformFile(
path: mediaFile.path,
bytes: mediaFile.readAsBytesSync(),
);
final channel = StreamChannel.of(context).channel;
setState(() {
attachment
..file = file
..attachment = Attachment(
localUri: file.path != null ? Uri.parse(file.path) : null,
type: medium.mediaType == MediaType.image ? 'image' : 'video',
);
});
final url = await _uploadAttachment(
file,
medium.mediaType == MediaType.image
? DefaultAttachmentTypes.image
: DefaultAttachmentTypes.video,
channel);
final fileType = medium.mediaType == MediaType.image
? DefaultAttachmentTypes.image
: DefaultAttachmentTypes.video;
if (fileType == DefaultAttachmentTypes.image) {
attachment.attachment = attachment.attachment.copyWith(
imageUrl: url,
);
} else {
attachment.attachment = attachment.attachment.copyWith(
assetUrl: url,
);
}
setState(() {
attachment.uploaded = true;
});
}
CircleAvatar _buildGiphyIcon() {
if (kIsWeb) {
return CircleAvatar(
@@ -857,24 +1128,11 @@ class MessageInputState extends State<MessageInput> {
_commandsOverlay = null;
}
Gradient _getGradient(BuildContext context) {
if (_typingStarted) {
if (widget.editMessage == null) {
return StreamChatTheme.of(context).channelTheme.inputGradient;
}
return LinearGradient(
colors: [Colors.lightGreen, Colors.green],
);
} else {
return null;
}
}
Widget _buildAttachments() {
return _attachments.isEmpty
? Container()
: LimitedBox(
maxHeight: 76.0,
maxHeight: 104.0,
child: ListView(
scrollDirection: Axis.horizontal,
children: _attachments
@@ -888,8 +1146,8 @@ class MessageInputState extends State<MessageInput> {
AspectRatio(
aspectRatio: 1.0,
child: Container(
height: 50,
width: 50,
height: 104,
width: 104,
child: _buildAttachment(attachment),
),
),
@@ -916,8 +1174,8 @@ class MessageInputState extends State<MessageInput> {
Positioned _buildRemoveButton(_SendingAttachment attachment) {
return Positioned(
height: 16,
width: 16,
height: 24,
width: 24,
top: 4,
right: 4,
child: RawMaterialButton(
@@ -934,11 +1192,12 @@ class MessageInputState extends State<MessageInput> {
_attachments.remove(attachment);
});
},
fillColor: Colors.white.withOpacity(.5),
fillColor: Colors.black.withOpacity(.5),
child: Center(
child: Icon(
Icons.close,
size: 15,
StreamIcons.close,
size: 24,
color: Colors.white,
),
),
),
@@ -955,6 +1214,10 @@ class MessageInputState extends State<MessageInput> {
);
}
if (attachment.attachment == null) {
return SizedBox();
}
switch (attachment.attachment.type) {
case 'image':
case 'giphy':
@@ -964,15 +1227,30 @@ class MessageInputState extends State<MessageInput> {
fit: BoxFit.cover,
)
: Image.network(
attachment.attachment.imageUrl ??
attachment.attachment.thumbUrl,
attachment.attachment.imageUrl,
fit: BoxFit.cover,
);
break;
case 'video':
return Container(
child: Icon(Icons.videocam),
color: Colors.black26,
return Stack(
children: [
Positioned.fill(
child: Container(
child: VideoThumbnail(
file: File(
attachment.file.path,
)),
),
),
Positioned(
left: 8,
bottom: 10,
child: SvgPicture.asset(
'svgs/video_call_icon.svg',
package: 'stream_chat_flutter',
),
),
],
);
break;
default:
@@ -984,26 +1262,24 @@ class MessageInputState extends State<MessageInput> {
}
Widget _buildCommandButton() {
return Center(
child: InkWell(
child: Padding(
padding: const EdgeInsets.only(
left: 4.0, right: 8.0, top: 8.0, bottom: 8.0),
child: Icon(
StreamIcons.lightning,
color: Color(0xFF000000).withAlpha(128),
),
return InkWell(
child: Padding(
padding:
const EdgeInsets.only(left: 4.0, right: 8.0, top: 8.0, bottom: 8.0),
child: Icon(
StreamIcons.lightning,
color: Color(0xFF000000).withAlpha(128),
),
onTap: () {
if (_commandsOverlay == null) {
_commandsOverlay = _buildCommandsOverlayEntry();
Overlay.of(context).insert(_commandsOverlay);
} else {
_commandsOverlay?.remove();
_commandsOverlay = null;
}
},
),
onTap: () {
if (_commandsOverlay == null) {
_commandsOverlay = _buildCommandsOverlayEntry();
Overlay.of(context).insert(_commandsOverlay);
} else {
_commandsOverlay?.remove();
_commandsOverlay = null;
}
},
);
}
@@ -1016,11 +1292,37 @@ class MessageInputState extends State<MessageInput> {
EdgeInsets.only(left: 8.0, right: padding, top: 8.0, bottom: 8.0),
child: Icon(
StreamIcons.attach,
color: Color(0xFF000000).withAlpha(128),
color: _openFilePickerSection
? StreamChatTheme.of(context).accentColor
: Color(0xFF000000).withAlpha(128),
),
),
onTap: () {
showAttachmentModal();
onTap: () async {
_emojiOverlay?.remove();
_emojiOverlay = null;
_commandsOverlay?.remove();
_commandsOverlay = null;
_mentionsOverlay?.remove();
_mentionsOverlay = null;
if (_openFilePickerSection) {
setState(() {
_animateContainer = true;
_openFilePickerSection = false;
_filePickerSize = _kMinMediaPickerSize;
});
} else {
final status = await (Platform.isAndroid
? Permission.storage.status
: Permission.photos.status);
if (status.isUndetermined) {
await (Platform.isAndroid
? Permission.storage
: Permission.photos)
.request();
}
showAttachmentModal();
}
},
),
);
@@ -1032,73 +1334,79 @@ class MessageInputState extends State<MessageInput> {
_focusNode.unfocus();
}
showModalBottomSheet(
clipBehavior: Clip.hardEdge,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(32),
topRight: Radius.circular(32),
if (!kIsWeb) {
setState(() {
_openFilePickerSection = true;
});
} else {
showModalBottomSheet(
clipBehavior: Clip.hardEdge,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(32),
topRight: Radius.circular(32),
),
),
),
context: context,
isScrollControlled: true,
builder: (_) {
return Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ListTile(
title: Text(
'Add a file',
style: TextStyle(
fontWeight: FontWeight.bold,
context: context,
isScrollControlled: true,
builder: (_) {
return Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
ListTile(
title: Text(
'Add a file',
style: TextStyle(
fontWeight: FontWeight.bold,
),
),
),
),
ListTile(
leading: Icon(Icons.image),
title: Text('Upload a photo'),
onTap: () {
pickFile(DefaultAttachmentTypes.image, false);
Navigator.pop(context);
},
),
ListTile(
leading: Icon(Icons.video_library),
title: Text('Upload a video'),
onTap: () {
pickFile(DefaultAttachmentTypes.video, false);
Navigator.pop(context);
},
),
if (!kIsWeb)
ListTile(
leading: Icon(Icons.camera_alt),
title: Text('Photo from camera'),
leading: Icon(Icons.image),
title: Text('Upload a photo'),
onTap: () {
pickFile(DefaultAttachmentTypes.image, true);
pickFile(DefaultAttachmentTypes.image, false);
Navigator.pop(context);
},
),
if (!kIsWeb)
ListTile(
leading: Icon(Icons.videocam),
title: Text('Video from camera'),
leading: Icon(Icons.video_library),
title: Text('Upload a video'),
onTap: () {
pickFile(DefaultAttachmentTypes.video, true);
pickFile(DefaultAttachmentTypes.video, false);
Navigator.pop(context);
},
),
ListTile(
leading: Icon(Icons.insert_drive_file),
title: Text('Upload a file'),
onTap: () {
pickFile(DefaultAttachmentTypes.file, false);
Navigator.pop(context);
},
),
],
);
});
if (!kIsWeb)
ListTile(
leading: Icon(Icons.camera_alt),
title: Text('Photo from camera'),
onTap: () {
pickFile(DefaultAttachmentTypes.image, true);
Navigator.pop(context);
},
),
if (!kIsWeb)
ListTile(
leading: Icon(Icons.videocam),
title: Text('Video from camera'),
onTap: () {
pickFile(DefaultAttachmentTypes.video, true);
Navigator.pop(context);
},
),
ListTile(
leading: Icon(Icons.insert_drive_file),
title: Text('Upload a file'),
onTap: () {
pickFile(DefaultAttachmentTypes.file, false);
Navigator.pop(context);
},
),
],
);
});
}
}
/// Add an attachment to the sending message
@@ -1137,6 +1445,9 @@ class MessageInputState extends State<MessageInput> {
} else if (fileType == DefaultAttachmentTypes.video) {
pickedFile = await _imagePicker.getVideo(source: ImageSource.camera);
}
if (pickedFile == null) {
return;
}
final bytes = await pickedFile.readAsBytes();
file = PlatformFile(
path: pickedFile.path,
@@ -1228,7 +1539,9 @@ class MessageInputState extends State<MessageInput> {
MultipartFile.fromBytes(
bytes,
filename: filename,
contentType: MediaType.parse(lookupMimeType(filename)),
contentType: filename != null
? httpParser.MediaType.parse(lookupMimeType(filename))
: null,
),
);
return res.file;
@@ -1241,7 +1554,7 @@ class MessageInputState extends State<MessageInput> {
MultipartFile.fromBytes(
bytes,
filename: filename,
contentType: MediaType.parse(lookupMimeType(filename)),
contentType: httpParser.MediaType.parse(lookupMimeType(filename)),
),
);
return res.file;
@@ -1332,7 +1645,6 @@ class MessageInputState extends State<MessageInput> {
setState(() {
_messageIsPresent = false;
_typingStarted = false;
_commandEnabled = false;
});
@@ -1400,47 +1712,14 @@ class MessageInputState extends State<MessageInput> {
void initState() {
super.initState();
_focusNode = widget.focusNode ?? FocusNode();
_emojiNames = Emoji.all().map((e) => e.name);
if (!kIsWeb) {
_keyboardListener = KeyboardVisibility.onChange.listen((visible) {
if (visible) {
if (_commandsOverlay != null) {
if (textEditingController.text.trimLeft().startsWith('/')) {
WidgetsBinding.instance.addPostFrameCallback((_) {
_commandsOverlay = _buildCommandsOverlayEntry();
Overlay.of(context).insert(_commandsOverlay);
});
}
}
if (_mentionsOverlay != null) {
if (textEditingController.text.contains('@')) {
WidgetsBinding.instance.addPostFrameCallback((_) {
_mentionsOverlay = _buildCommandsOverlayEntry();
Overlay.of(context).insert(_mentionsOverlay);
});
}
}
if (_emojiOverlay != null) {
if (textEditingController.text.contains(':')) {
WidgetsBinding.instance.addPostFrameCallback((_) {
_emojiOverlay = _buildEmojiOverlay();
Overlay.of(context).insert(_emojiOverlay);
});
}
}
} else {
if (_commandsOverlay != null) {
_commandsOverlay.remove();
}
if (_mentionsOverlay != null) {
_mentionsOverlay.remove();
}
if (_emojiOverlay != null) {
_emojiOverlay.remove();
}
if (_focusNode.hasFocus) {
_onChanged(context, textEditingController.text);
}
});
}
@@ -1450,12 +1729,21 @@ class MessageInputState extends State<MessageInput> {
if (widget.editMessage != null || widget.initialMessage != null) {
_parseExistingMessage(widget.editMessage ?? widget.initialMessage);
}
textEditingController.addListener(() {
_onChanged(context, textEditingController.text);
});
_focusNode.addListener(() {
if (_focusNode.hasFocus) {
_openFilePickerSection = false;
}
});
}
void _parseExistingMessage(Message message) {
textEditingController.text = message.text;
_typingStarted = true;
_messageIsPresent = true;
message.attachments?.forEach((attachment) {
@@ -1490,11 +1778,13 @@ class _SendingAttachment {
PlatformFile file;
Attachment attachment;
bool uploaded;
String id;
_SendingAttachment({
this.file,
this.attachment,
this.uploaded = false,
this.id,
});
}
@@ -1503,3 +1793,44 @@ extension StringExtension on String {
return "${this[0].toUpperCase()}${this.substring(1)}";
}
}
/// Represents a 2-tuple, or pair.
class Tuple2<T1, T2> {
/// Returns the first item of the tuple
final T1 item1;
/// Returns the second item of the tuple
final T2 item2;
/// Creates a new tuple value with the specified items.
const Tuple2(this.item1, this.item2);
/// Create a new tuple value with the specified list [items].
factory Tuple2.fromList(List items) {
if (items.length != 2) {
throw ArgumentError('items must have length 2');
}
return Tuple2<T1, T2>(items[0] as T1, items[1] as T2);
}
/// Returns a tuple with the first item set to the specified value.
Tuple2<T1, T2> withItem1(T1 v) => Tuple2<T1, T2>(v, item2);
/// Returns a tuple with the second item set to the specified value.
Tuple2<T1, T2> withItem2(T2 v) => Tuple2<T1, T2>(item1, v);
/// Creates a [List] containing the items of this [Tuple2].
///
/// The elements are in item order. The list is variable-length
/// if [growable] is true.
List toList({bool growable = false}) =>
List.from([item1, item2], growable: growable);
@override
String toString() => '[$item1, $item2]';
@override
bool operator ==(Object other) =>
other is Tuple2 && other.item1 == item1 && other.item2 == item2;
}
+19
View File
@@ -180,7 +180,26 @@ class _MessageListViewState extends State<MessageListView> {
? streamChannel.channel.state.threads[widget.parentMessage.id]
: streamChannel.channel.state.messages,
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
}
final messages = snapshot.data?.reversed?.toList() ?? [];
if (messages.isEmpty) {
return Center(
child: Text(
'No chats here yet...',
style: TextStyle(
fontSize: 12,
color: Colors.black.withOpacity(.5),
),
),
);
}
return Stack(
alignment: Alignment.center,
children: [
+7 -6
View File
@@ -36,14 +36,15 @@ class MessageReactionsModal extends StatelessWidget {
@override
Widget build(BuildContext context) {
var size = MediaQuery.of(context).size;
var user = StreamChat.of(context).user;
final size = MediaQuery.of(context).size;
final user = StreamChat.of(context).user;
var roughMaxSize = 2 * size.width / 3;
var roughSentenceSize =
final roughMaxSize = 2 * size.width / 3;
final roughSentenceSize =
message.text.length * messageTheme.messageText.fontSize * 1.2;
var divFactor =
roughSentenceSize == 0 ? 1 : (roughSentenceSize / roughMaxSize);
final divFactor = message.attachments?.isNotEmpty == true
? 1
: (roughSentenceSize == 0 ? 1 : (roughSentenceSize / roughMaxSize));
return GestureDetector(
behavior: HitTestBehavior.translucent,
+25 -12
View File
@@ -493,7 +493,10 @@ class _MessageWidgetState extends State<MessageWidget> {
message: widget.message,
editMessageInputBuilder: widget.editMessageInputBuilder,
onThreadTap: widget.onThreadTap,
showEditMessage: widget.showEditMessage,
showEditMessage: widget.showEditMessage &&
widget.message.attachments
?.any((element) => element.type == 'giphy') !=
true,
showReactions: widget.showReactions,
showReply:
widget.showReplyIndicator && widget.onThreadTap != null,
@@ -582,14 +585,22 @@ class _MessageWidgetState extends State<MessageWidget> {
widget.message,
attachment,
);
return wrapAttachmentWidget(context, attachmentWidget,
attachment: attachment);
return wrapAttachmentWidget(
context,
attachmentWidget,
attachment: attachment,
);
})?.toList() ??
[];
}
Padding wrapAttachmentWidget(BuildContext context, Widget attachmentWidget,
{Attachment attachment}) {
Padding wrapAttachmentWidget(
BuildContext context,
Widget attachmentWidget, {
Attachment attachment,
}) {
final attachmentShape =
widget.attachmentShape ?? widget.shape ?? _getDefaultShape(context);
return Padding(
padding: EdgeInsets.only(
bottom: 4,
@@ -602,13 +613,13 @@ class _MessageWidgetState extends State<MessageWidget> {
? Colors.white
: _getBackgroundColor(),
clipBehavior: Clip.hardEdge,
shape: widget.attachmentShape ??
widget.shape ??
_getDefaultShape(context),
shape: attachmentShape,
child: Padding(
padding: widget.attachmentPadding,
child: ClipRRect(
borderRadius: BorderRadius.circular(6),
child: Material(
clipBehavior: Clip.hardEdge,
shape: attachmentShape,
type: MaterialType.transparency,
child: Transform(
transform: Matrix4.rotationY(widget.reverse ? pi : 0),
alignment: Alignment.center,
@@ -806,7 +817,8 @@ class _MessageWidgetState extends State<MessageWidget> {
),
),
if (widget.message.attachments
.any((element) => element.ogScrapeUrl != null))
?.any((element) => element.ogScrapeUrl != null) ==
true)
_buildUrlAttachment(),
],
),
@@ -833,7 +845,8 @@ class _MessageWidgetState extends State<MessageWidget> {
}
if (widget.message.attachments
.any((element) => element.ogScrapeUrl != null)) {
?.any((element) => element.ogScrapeUrl != null) ==
true) {
return Color(0xFFE9F2FF);
}
+3 -1
View File
@@ -12,12 +12,14 @@ class StreamChannel extends StatefulWidget {
Key key,
@required this.child,
@required this.channel,
this.showLoading = true,
}) : super(
key: key,
);
final Widget child;
final Channel channel;
final bool showLoading;
/// Use this method to get the current [StreamChannelState] instance
static StreamChannelState of(BuildContext context) {
@@ -155,7 +157,7 @@ class StreamChannelState extends State<StreamChannel> {
future: widget.channel.initialized,
initialData: widget.channel.state != null,
builder: (context, snapshot) {
if (!snapshot.hasData || !snapshot.data) {
if (widget.showLoading && (!snapshot.hasData || !snapshot.data)) {
return Container(
height: 30,
child: Center(
+1
View File
@@ -229,6 +229,7 @@ class StreamChatThemeData {
backgroundColor: isDark ? Colors.black : Colors.white,
defaultUserImage: (context, user) => Center(
child: CachedNetworkImage(
filterQuality: FilterQuality.high,
imageUrl: getRandomPicUrl(user),
fit: BoxFit.cover,
),
+3 -3
View File
@@ -4,9 +4,9 @@ import 'package:stream_chat_flutter/src/utils.dart';
import 'package:stream_chat_flutter/stream_chat_flutter.dart';
class UrlAttachment extends StatelessWidget {
Attachment urlAttachment;
String hostDisplayName;
EdgeInsets textPadding;
final Attachment urlAttachment;
final String hostDisplayName;
final EdgeInsets textPadding;
UrlAttachment({
@required this.urlAttachment,
+55 -34
View File
@@ -11,16 +11,26 @@ class UserAvatar extends StatelessWidget {
this.constraints,
this.onlineIndicatorConstraints,
this.onTap,
this.onLongPress,
this.showOnlineStatus = true,
this.borderRadius,
this.onlineIndicatorAlignment = Alignment.topRight,
this.selected = false,
this.selectionColor = const Color(0xFF006CFF),
this.selectionThickness = 4,
}) : super(key: key);
final User user;
final Alignment onlineIndicatorAlignment;
final BoxConstraints constraints;
final BorderRadius borderRadius;
final BoxConstraints onlineIndicatorConstraints;
final void Function(User) onTap;
final void Function(User) onLongPress;
final bool showOnlineStatus;
final bool selected;
final Color selectionColor;
final double selectionThickness;
@override
Widget build(BuildContext context) {
@@ -28,42 +38,54 @@ class UserAvatar extends StatelessWidget {
user.extraData['image'] != null &&
user.extraData['image'] != '';
final streamChatTheme = StreamChatTheme.of(context);
Widget avatar = ClipRRect(
borderRadius: borderRadius ??
streamChatTheme.ownMessageTheme.avatarTheme.borderRadius,
child: Container(
constraints: constraints ??
streamChatTheme.ownMessageTheme.avatarTheme.constraints,
decoration: BoxDecoration(
color: streamChatTheme.accentColor,
),
child: hasImage
? CachedNetworkImage(
filterQuality: FilterQuality.high,
imageUrl: user.extraData['image'],
errorWidget: (_, __, ___) {
return streamChatTheme.defaultUserImage(context, user);
},
fit: BoxFit.cover,
)
: streamChatTheme.defaultUserImage(context, user),
),
);
if (selected) {
avatar = ClipRRect(
borderRadius: (borderRadius ??
streamChatTheme.ownMessageTheme.avatarTheme.borderRadius) +
BorderRadius.circular(selectionThickness),
child: Container(
color: selectionColor,
child: Padding(
padding: EdgeInsets.all(selectionThickness),
child: avatar,
),
),
);
}
return GestureDetector(
onTap: onTap != null
? () {
if (onTap != null) {
onTap(user);
}
}
: null,
onTap: onTap != null ? () => onTap(user) : null,
onLongPress: onLongPress != null ? () => onLongPress(user) : null,
child: Stack(
children: <Widget>[
ClipRRect(
borderRadius: borderRadius ??
streamChatTheme.ownMessageTheme.avatarTheme.borderRadius,
child: Container(
constraints: constraints ??
streamChatTheme.ownMessageTheme.avatarTheme.constraints,
decoration: BoxDecoration(
color: streamChatTheme.accentColor,
),
child: hasImage
? CachedNetworkImage(
imageUrl: user.extraData['image'],
errorWidget: (_, __, ___) {
return streamChatTheme.defaultUserImage(context, user);
},
fit: BoxFit.cover,
)
: streamChatTheme.defaultUserImage(context, user),
),
),
avatar,
if (showOnlineStatus && user.online == true)
Positioned(
top: 0,
right: 0,
child: Material(
child: Center(
Positioned.fill(
child: Align(
alignment: onlineIndicatorAlignment,
child: Material(
type: MaterialType.circle,
child: Container(
padding: const EdgeInsets.all(2.0),
constraints: onlineIndicatorConstraints ??
@@ -76,9 +98,8 @@ class UserAvatar extends StatelessWidget {
color: Color(0xff20E070),
),
),
color: Colors.white,
),
shape: CircleBorder(),
color: Colors.white,
),
),
],
+94
View File
@@ -0,0 +1,94 @@
import 'package:flutter/material.dart';
import 'package:jiffy/jiffy.dart';
import 'package:stream_chat/stream_chat.dart';
import 'package:stream_chat_flutter/src/user_list_view.dart';
import 'package:stream_chat_flutter/stream_chat_flutter.dart';
import 'stream_chat_theme.dart';
///
/// It shows the current [User] preview.
///
/// The widget uses a [StreamBuilder] to render the user information image as soon as it updates.
///
/// Usually you don't use this widget as it's the default user preview used by [UserListView].
///
/// The widget renders the ui based on the first ancestor of type [StreamChatTheme].
/// Modify it to change the widget appearance.
class UserItem extends StatelessWidget {
/// Instantiate a new UserItem
const UserItem({
Key key,
@required this.user,
this.onTap,
this.onLongPress,
this.onImageTap,
this.selected = false,
this.showLastOnline = true,
}) : super(key: key);
/// Function called when tapping this widget
final void Function(User) onTap;
/// Function called when long pressing this widget
final void Function(User) onLongPress;
/// User displayed
final User user;
/// The function called when the image is tapped
final void Function(User) onImageTap;
/// If true the [UserItem] will show a trailing checkmark
final bool selected;
/// If true the [UserItem] will show the last seen
final bool showLastOnline;
@override
Widget build(BuildContext context) {
return ListTile(
onTap: () {
if (onTap != null) {
onTap(user);
}
},
onLongPress: () {
if (onLongPress != null) {
onLongPress(user);
}
},
leading: UserAvatar(
user: user,
showOnlineStatus: true,
onTap: (user) {
if (onImageTap != null) {
onImageTap(user);
}
},
constraints: BoxConstraints.tightFor(
height: 40,
width: 40,
),
),
trailing: selected
? CircleAvatar(
child: Icon(
StreamIcons.check,
size: 20,
),
radius: 10,
)
: null,
title: Text(
user.name,
style: TextStyle(fontWeight: FontWeight.bold),
),
subtitle: showLastOnline ? _buildLastActive(context) : null,
);
}
Widget _buildLastActive(context) {
return Text('Last online ${Jiffy(user.lastActive).fromNow()}');
}
}
+578
View File
@@ -0,0 +1,578 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:stream_chat/stream_chat.dart';
import 'package:stream_chat_flutter/src/users_bloc.dart';
import 'package:stream_chat_flutter/stream_chat_flutter.dart';
import 'stream_chat.dart';
import 'user_item.dart';
/// Callback called when tapping on a user
typedef UserTapCallback = void Function(User, Widget);
/// Builder used to create a custom [ListUserItem] from a [User]
typedef UserItemBuilder = Widget Function(BuildContext, User, bool);
///
/// It shows the list of current users.
///
/// ```dart
/// class UsersListPage extends StatelessWidget {
/// @override
/// Widget build(BuildContext context) {
/// return Scaffold(
/// body: UsersListView(
/// filter: {
/// 'members': {
/// '\$in': [StreamChat.of(context).user.id],
/// }
/// },
/// sort: [SortOption('last_message_at')],
/// pagination: PaginationParams(
/// limit: 20,
/// ),
/// channelWidget: ChannelPage(),
/// ),
/// );
/// }
/// }
/// ```
///
///
/// Make sure to have a [StreamChat] ancestor in order to provide the information about the channels.
/// The widget uses a [ListView.custom] to render the list of channels.
///
/// The widget components render the ui based on the first ancestor of type [StreamChatTheme].
/// Modify it to change the widget appearance.
class UserListView extends StatefulWidget {
/// Instantiate a new UserListView
const UserListView({
Key key,
this.errorBuilder,
this.emptyBuilder,
this.filter,
this.options,
this.sort,
this.pagination,
this.onUserTap,
this.onUserLongPress,
this.userWidget,
this.userItemBuilder,
this.separatorBuilder,
this.onImageTap,
this.selectedUsers,
this.swipeToAction = false,
this.pullToRefresh = true,
this.groupAlphabetically = false,
this.crossAxisCount = 1,
}) : assert(
crossAxisCount == 1 || groupAlphabetically == false,
'Cannot group alphabetically when crossAxisCount > 1',
),
super(key: key);
/// The builder that will be used in case of error
final Widget Function(Error error) errorBuilder;
/// If true a default swipe to action behaviour will be added to this widget
final bool swipeToAction;
/// The builder used when the channel list is empty.
final WidgetBuilder emptyBuilder;
/// The query filters to use.
/// You can query on any of the custom fields you've defined on the [Channel].
/// You can also filter other built-in channel fields.
final Map<String, dynamic> filter;
/// Query channels options.
///
/// state: if true returns the Channel state
/// watch: if true listen to changes to this Channel in real time.
final Map<String, dynamic> options;
/// The sorting used for the channels matching the filters.
/// Sorting is based on field and direction, multiple sorting options can be provided.
/// You can sort based on last_updated, last_message_at, updated_at, created_at or member_count.
/// Direction can be ascending or descending.
final List<SortOption> sort;
/// Pagination parameters
/// limit: the number of users to return (max is 30)
/// offset: the offset (max is 1000)
/// message_limit: how many messages should be included to each channel
final PaginationParams pagination;
/// Function called when tapping on a channel
/// By default it calls [Navigator.push] building a [MaterialPageRoute]
/// with the widget [userWidget] as child.
final UserTapCallback onUserTap;
/// Function called when long pressing on a channel
final Function(User) onUserLongPress;
/// Widget used when opening a channel
final Widget userWidget;
/// Builder used to create a custom user preview
final UserItemBuilder userItemBuilder;
/// Builder used to create a custom item separator
final Function(BuildContext, int) separatorBuilder;
/// The function called when the image is tapped
final Function(User) onImageTap;
/// Set it to false to disable the pull-to-refresh widget
final bool pullToRefresh;
/// Sets a blue trailing checkMark in [ListUserItem] for all the [selectedUsers]
final Set<User> selectedUsers;
/// Set it to true to group users by their first character
///
/// defaults to false
final bool groupAlphabetically;
/// The number of children in the cross axis.
final int crossAxisCount;
@override
_UserListViewState createState() => _UserListViewState();
}
class _UserListViewState extends State<UserListView>
with WidgetsBindingObserver {
final ScrollController _scrollController = ScrollController();
bool get _isListView => widget.crossAxisCount == 1;
@override
void initState() {
super.initState();
final usersBloc = UsersBloc.of(context);
usersBloc.queryUsers(
filter: widget.filter,
sort: widget.sort,
pagination: widget.pagination,
options: widget.options,
);
_scrollController.addListener(() {
usersBloc.queryUsersLoading.first.then((loading) {
if (!loading) {
_listenUserPagination(usersBloc);
}
});
});
}
@override
Widget build(BuildContext context) {
final usersBloc = UsersBloc.of(context);
if (!widget.pullToRefresh) {
return _buildListView(usersBloc);
}
return RefreshIndicator(
onRefresh: () async {
return usersBloc.queryUsers(
filter: widget.filter,
sort: widget.sort,
options: widget.options,
pagination: widget.pagination,
);
},
child: _buildListView(usersBloc),
);
}
bool get isListAlreadySorted =>
widget.sort?.any((e) => e.field == 'name' && e.direction == 1) ?? false;
Stream<List<ListItem>> _buildUserStream(
UsersBlocState usersBlocState,
) {
return usersBlocState.usersStream.map(
(users) {
if (widget.groupAlphabetically) {
var temp = users;
if (!isListAlreadySorted) {
temp = users..sort((curr, next) => curr.name.compareTo(next.name));
}
final groupedUsers = <String, List<User>>{};
for (var e in temp) {
final alphabet = e.name[0];
groupedUsers[alphabet] = [...groupedUsers[alphabet] ?? [], e];
}
final items = <ListItem>[];
for (var key in groupedUsers.keys) {
items.add(ListHeaderItem(key));
items.addAll(groupedUsers[key].map((e) => ListUserItem(e)));
}
return items;
}
return users.map((e) => ListUserItem(e)).toList();
},
);
}
StreamBuilder<List<ListItem>> _buildListView(
UsersBlocState usersBlocState,
) {
return StreamBuilder(
stream: _buildUserStream(usersBlocState),
builder: (context, snapshot) {
if (snapshot.hasError) {
if (snapshot.error is Error) {
print((snapshot.error as Error).stackTrace);
}
if (widget.errorBuilder != null) {
return widget.errorBuilder(snapshot.error);
}
var message = snapshot.error.toString();
if (snapshot.error is DioError) {
final dioError = snapshot.error as DioError;
if (dioError.type == DioErrorType.RESPONSE) {
message = dioError.message;
} else {
message = 'Check your connection and retry';
}
}
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text.rich(
TextSpan(
children: [
WidgetSpan(
child: Padding(
padding: const EdgeInsets.only(
right: 2.0,
),
child: Icon(Icons.error_outline),
),
),
TextSpan(text: 'Error loading channels'),
],
),
style: Theme.of(context).textTheme.headline6,
),
Padding(
padding: const EdgeInsets.only(
top: 16.0,
),
child: Text(message),
),
FlatButton(
onPressed: () {
usersBlocState.queryUsers(
filter: widget.filter,
sort: widget.sort,
pagination: widget.pagination,
options: widget.options,
);
},
child: Text('Retry'),
),
],
),
);
}
if (!snapshot.hasData) {
return LayoutBuilder(
builder: (context, viewportConstraints) {
return SingleChildScrollView(
physics: AlwaysScrollableScrollPhysics(),
child: ConstrainedBox(
constraints: BoxConstraints(
minHeight: viewportConstraints.maxHeight,
),
child: Center(
child: CircularProgressIndicator(),
),
),
);
},
);
}
final items = snapshot.data;
if (items.isEmpty && widget.emptyBuilder != null) {
return widget.emptyBuilder(context);
}
if (items.isEmpty && widget.emptyBuilder == null) {
return LayoutBuilder(
builder: (context, viewportConstraints) {
return SingleChildScrollView(
physics: AlwaysScrollableScrollPhysics(),
child: ConstrainedBox(
constraints: BoxConstraints(
minHeight: viewportConstraints.maxHeight,
),
child: Center(
child: Text('There are no users currently'),
),
),
);
},
);
}
if (_isListView) {
return ListView.custom(
physics: AlwaysScrollableScrollPhysics(),
controller: _scrollController,
childrenDelegate: SliverChildBuilderDelegate(
(context, i) {
return _listItemBuilder(context, i, items);
},
childCount: (items.length * 2) + 1,
findChildIndexCallback: (key) {
final ValueKey<String> valueKey = key;
final index =
items.indexWhere((item) => item.key == valueKey.value);
return index != -1 ? (index * 2) : null;
},
),
);
}
return GridView.custom(
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: widget.crossAxisCount,
),
physics: AlwaysScrollableScrollPhysics(),
controller: _scrollController,
childrenDelegate: SliverChildBuilderDelegate(
(context, i) {
return _gridItemBuilder(context, i, items);
},
childCount: items.length,
findChildIndexCallback: (key) {
final ValueKey<String> valueKey = key;
final index =
items.indexWhere((item) => item.key == valueKey.value);
return index != -1 ? index : null;
},
),
);
},
);
}
Widget _listItemBuilder(BuildContext context, int i, List<ListItem> items) {
if (i % 2 != 0) {
if (widget.separatorBuilder != null) {
return widget.separatorBuilder(context, i);
}
return _separatorBuilder(context, i);
}
i = i ~/ 2;
final usersProvider = UsersBloc.of(context);
if (i < items.length) {
final item = items[i];
return item.when(
headerItem: (header) {
return Container(
key: ValueKey<String>('HEADER-$header'),
color: Colors.black.withOpacity(0.05),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 6),
child: Text(
header,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 12,
color: Colors.black.withOpacity(0.3)),
),
),
);
},
userItem: (user) {
final selected = widget.selectedUsers?.contains(user) ?? false;
return Container(
key: ValueKey<String>('USER-${user.id}'),
child: widget.userItemBuilder != null
? widget.userItemBuilder(context, user, selected)
: UserItem(
user: user,
onTap: (user) => widget.onUserTap(user, widget.userWidget),
onLongPress: widget.onUserLongPress,
onImageTap: widget.onImageTap,
selected: selected,
),
);
},
);
} else {
return _buildQueryProgressIndicator(context, usersProvider);
}
}
Widget _gridItemBuilder(BuildContext context, int i, List<ListItem> items) {
final usersProvider = UsersBloc.of(context);
if (i < items.length) {
final item = items[i];
return item.when(
headerItem: (_) => Offstage(),
userItem: (user) {
final selected = widget.selectedUsers?.contains(user) ?? false;
return Container(
key: ValueKey<String>('USER-${user.id}'),
child: widget.userItemBuilder != null
? widget.userItemBuilder(context, user, selected)
: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
UserAvatar(
user: user,
borderRadius: BorderRadius.circular(32),
selected: selected,
constraints: BoxConstraints.tightFor(
height: 64,
width: 64,
),
onTap: (user) =>
widget.onUserTap(user, widget.userWidget),
onLongPress: widget.onUserLongPress,
),
SizedBox(height: 4),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Text(
user.name,
textAlign: TextAlign.center,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 12,
),
),
),
],
),
);
},
);
} else {
return _buildQueryProgressIndicator(context, usersProvider);
}
}
Widget _buildQueryProgressIndicator(context, UsersBlocState usersProvider) {
return StreamBuilder<bool>(
stream: usersProvider.queryUsersLoading,
initialData: false,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Container(
color: Color(0xffd0021B).withAlpha(26),
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 16.0),
child: Center(
child: Text('Error loading users'),
),
),
);
}
return Container(
height: 100,
padding: EdgeInsets.all(32),
child: Center(
child: snapshot.data ? CircularProgressIndicator() : Container(),
),
);
});
}
Widget _separatorBuilder(context, i) {
return Container(
height: 1,
color: Theme.of(context).brightness == Brightness.dark
? Colors.white.withOpacity(0.1)
: Colors.black.withOpacity(0.1),
);
}
void _listenUserPagination(UsersBlocState usersProvider) {
if (_scrollController.position.maxScrollExtent ==
_scrollController.offset &&
_scrollController.offset != 0) {
usersProvider.queryUsers(
filter: widget.filter,
sort: widget.sort,
pagination: widget.pagination.copyWith(
offset: usersProvider.users?.length ?? 0,
),
options: widget.options,
);
}
}
@override
void didUpdateWidget(UserListView oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.filter?.toString() != oldWidget.filter?.toString() ||
jsonEncode(widget.sort) != jsonEncode(oldWidget.sort) ||
widget.pagination?.toJson()?.toString() !=
oldWidget.pagination?.toJson()?.toString() ||
widget.options?.toString() != oldWidget.options?.toString()) {
final usersBloc = UsersBloc.of(context);
usersBloc.queryUsers(
filter: widget.filter,
sort: widget.sort,
pagination: widget.pagination,
options: widget.options,
);
}
}
}
abstract class ListItem {
String get key {
if (this is ListHeaderItem) {
final header = (this as ListHeaderItem).heading;
return 'HEADER-$header';
}
if (this is ListUserItem) {
final user = (this as ListUserItem).user;
return 'USER-${user.id}';
}
}
Widget when({
@required Widget Function(String heading) headerItem,
@required Widget Function(User user) userItem,
}) {
if (this is ListHeaderItem) {
return headerItem((this as ListHeaderItem).heading);
}
if (this is ListUserItem) {
return userItem((this as ListUserItem).user);
}
}
}
class ListHeaderItem extends ListItem {
final String heading;
ListHeaderItem(this.heading);
}
class ListUserItem extends ListItem {
final User user;
ListUserItem(this.user);
}
+108
View File
@@ -0,0 +1,108 @@
import 'package:flutter/material.dart';
import 'package:rxdart/rxdart.dart';
import 'package:stream_chat/stream_chat.dart';
import 'stream_chat.dart';
/// Widget dedicated to the management of a users list with pagination
class UsersBloc extends StatefulWidget {
/// The widget child
final Widget child;
/// Instantiate a new UsersBloc
const UsersBloc({
Key key,
@required this.child,
}) : super(key: key);
@override
UsersBlocState createState() => UsersBlocState();
/// Use this method to get the current [UsersBlocState] instance
static UsersBlocState of(BuildContext context) {
UsersBlocState state;
state = context.findAncestorStateOfType<UsersBlocState>();
if (state == null) {
throw Exception('You must have a UsersBloc widget as ancestor');
}
return state;
}
}
/// The current state of the [UsersBloc]
class UsersBlocState extends State<UsersBloc>
with AutomaticKeepAliveClientMixin {
/// The current users list
List<User> get users => _usersController.value;
/// The current users list as a stream
Stream<List<User>> get usersStream => _usersController.stream;
final BehaviorSubject<List<User>> _usersController = BehaviorSubject();
final BehaviorSubject<bool> _queryUsersLoadingController =
BehaviorSubject.seeded(false);
/// The stream notifying the state of queryUsers call
Stream<bool> get queryUsersLoading => _queryUsersLoadingController.stream;
/// Calls [Client.queryUsers] updating [queryUsersLoading] stream
Future<void> queryUsers({
Map<String, dynamic> filter,
List<SortOption> sort,
Map<String, dynamic> options,
PaginationParams pagination,
}) async {
final client = StreamChat.of(context).client;
if (client.state?.user == null ||
_queryUsersLoadingController.value == true) {
return;
}
_queryUsersLoadingController.add(true);
try {
final clear = pagination == null ||
pagination.offset == null ||
pagination.offset == 0;
final oldUsers = List<User>.from(users ?? []);
final usersResponse = await client.queryUsers(
filter: filter,
sort: sort,
options: options,
pagination: pagination,
);
if (clear) {
_usersController.add(usersResponse.users);
} else {
final temp = oldUsers + usersResponse.users;
_usersController.add(temp);
}
_queryUsersLoadingController.add(false);
} catch (err, stackTrace) {
_queryUsersLoadingController.addError(err, stackTrace);
}
}
@override
Widget build(BuildContext context) {
super.build(context);
return widget.child;
}
@override
void dispose() {
_usersController.close();
_queryUsersLoadingController.close();
super.dispose();
}
@override
bool get wantKeepAlive => true;
}
+37
View File
@@ -0,0 +1,37 @@
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
class VideoThumbnail extends StatefulWidget {
final File file;
const VideoThumbnail({
Key key,
@required this.file,
}) : super(key: key);
@override
_VideoThumbnailState createState() => _VideoThumbnailState();
}
class _VideoThumbnailState extends State<VideoThumbnail> {
VideoPlayerController _videoPlayerController;
@override
Widget build(BuildContext context) {
return VideoPlayer(_videoPlayerController);
}
@override
void initState() {
_videoPlayerController = VideoPlayerController.file(widget.file)
..initialize();
super.initState();
}
@override
void dispose() {
_videoPlayerController.dispose();
super.dispose();
}
}