feat: Added selected image

This commit is contained in:
Deven Joshi
2020-11-09 14:21:32 +05:30
parent 38c06d5de7
commit 812f702845
+261 -206
View File
@@ -20,9 +20,9 @@ import 'stream_channel.dart';
typedef FileUploader = Future<String> Function(PlatformFile, Channel); typedef FileUploader = Future<String> Function(PlatformFile, Channel);
typedef AttachmentThumbnailBuilder = Widget Function( typedef AttachmentThumbnailBuilder = Widget Function(
BuildContext, BuildContext,
_SendingAttachment, _SendingAttachment,
); );
enum ActionsLocation { enum ActionsLocation {
left, left,
@@ -230,7 +230,7 @@ class MessageInputState extends State<MessageInput> {
Checkbox( Checkbox(
value: _sendAsDm, value: _sendAsDm,
onChanged: (val) => setState( onChanged: (val) => setState(
() { () {
_sendAsDm = val; _sendAsDm = val;
}, },
), ),
@@ -247,7 +247,7 @@ class MessageInputState extends State<MessageInput> {
AnimatedCrossFade _animateSendButton(BuildContext context) { AnimatedCrossFade _animateSendButton(BuildContext context) {
return AnimatedCrossFade( return AnimatedCrossFade(
crossFadeState: ((_messageIsPresent || _attachments.isNotEmpty) && crossFadeState: ((_messageIsPresent || _attachments.isNotEmpty) &&
_attachments.every((a) => a.uploaded == true)) _attachments.every((a) => a.uploaded == true))
? CrossFadeState.showFirst ? CrossFadeState.showFirst
: CrossFadeState.showSecond, : CrossFadeState.showSecond,
firstChild: _buildSendButton(context), firstChild: _buildSendButton(context),
@@ -260,7 +260,7 @@ class MessageInputState extends State<MessageInput> {
Widget _buildExpandActionsButton() { Widget _buildExpandActionsButton() {
return AnimatedCrossFade( return AnimatedCrossFade(
crossFadeState: crossFadeState:
_actionsShrunk ? CrossFadeState.showFirst : CrossFadeState.showSecond, _actionsShrunk ? CrossFadeState.showFirst : CrossFadeState.showSecond,
firstChild: IconButton( firstChild: IconButton(
onPressed: () { onPressed: () {
setState(() { setState(() {
@@ -353,7 +353,7 @@ class MessageInputState extends State<MessageInput> {
(s[textEditingController.selection.start - 1] == '@' || (s[textEditingController.selection.start - 1] == '@' ||
textEditingController.text textEditingController.text
.substring( .substring(
0, textEditingController.selection.start) 0, textEditingController.selection.start)
.split(' ') .split(' ')
.last .last
.contains('@'))) { .contains('@'))) {
@@ -371,9 +371,9 @@ class MessageInputState extends State<MessageInput> {
textAlignVertical: TextAlignVertical.center, textAlignVertical: TextAlignVertical.center,
decoration: InputDecoration( decoration: InputDecoration(
hintText: hintText:
(_commandEnabled && _chosenCommand.name == 'giphy') (_commandEnabled && _chosenCommand.name == 'giphy')
? 'Search GIFs' ? 'Search GIFs'
: 'Write a message', : 'Write a message',
prefixText: _commandEnabled ? null : ' ', prefixText: _commandEnabled ? null : ' ',
border: OutlineInputBorder( border: OutlineInputBorder(
borderSide: BorderSide(color: Colors.transparent)), borderSide: BorderSide(color: Colors.transparent)),
@@ -388,31 +388,31 @@ class MessageInputState extends State<MessageInput> {
contentPadding: EdgeInsets.all(8), contentPadding: EdgeInsets.all(8),
prefixIcon: _commandEnabled prefixIcon: _commandEnabled
? Padding( ? Padding(
padding: padding:
const EdgeInsets.symmetric(horizontal: 8.0), const EdgeInsets.symmetric(horizontal: 8.0),
child: Chip( child: Chip(
backgroundColor: backgroundColor:
StreamChatTheme.of(context).accentColor, StreamChatTheme.of(context).accentColor,
label: Text( label: Text(
_chosenCommand?.name ?? "", _chosenCommand?.name ?? "",
style: TextStyle(color: Colors.white), style: TextStyle(color: Colors.white),
), ),
avatar: Icon( avatar: Icon(
StreamIcons.lightning, StreamIcons.lightning,
color: Colors.white, color: Colors.white,
), ),
), ),
) )
: null, : null,
suffixIcon: _commandEnabled suffixIcon: _commandEnabled
? IconButton( ? IconButton(
icon: Icon(Icons.cancel_outlined), icon: Icon(Icons.cancel_outlined),
onPressed: () { onPressed: () {
setState(() { setState(() {
_commandEnabled = false; _commandEnabled = false;
}); });
}, },
) )
: null, : null,
), ),
textCapitalization: TextCapitalization.sentences, textCapitalization: TextCapitalization.sentences,
@@ -454,13 +454,13 @@ class MessageInputState extends State<MessageInput> {
child: Container( child: Container(
constraints: BoxConstraints.loose(Size.fromHeight(400)), constraints: BoxConstraints.loose(Size.fromHeight(400)),
decoration: BoxDecoration( decoration: BoxDecoration(
// boxShadow: [ // boxShadow: [
// BoxShadow( // BoxShadow(
// spreadRadius: -8, // spreadRadius: -8,
// blurRadius: 5.0, // blurRadius: 5.0,
// offset: Offset(0, -4), // offset: Offset(0, -4),
// ), // ),
// ], // ],
color: StreamChatTheme.of(context).primaryColor, color: StreamChatTheme.of(context).primaryColor,
borderRadius: BorderRadius.circular(8.0)), borderRadius: BorderRadius.circular(8.0)),
child: ListView( child: ListView(
@@ -474,7 +474,7 @@ class MessageInputState extends State<MessageInput> {
children: [ children: [
Padding( Padding(
padding: padding:
const EdgeInsets.symmetric(horizontal: 8.0), const EdgeInsets.symmetric(horizontal: 8.0),
child: Icon(StreamIcons.lightning, child: Icon(StreamIcons.lightning,
color: StreamChatTheme.of(context).accentColor), color: StreamChatTheme.of(context).accentColor),
), ),
@@ -485,48 +485,48 @@ class MessageInputState extends State<MessageInput> {
...commands ...commands
.map( .map(
(c) => ListTile( (c) => ListTile(
leading: c.name == 'giphy' leading: c.name == 'giphy'
? CircleAvatar( ? CircleAvatar(
backgroundColor: Colors.black, backgroundColor: Colors.black,
child: Image.asset( child: Image.asset(
'images/giphy_icon.png', 'images/giphy_icon.png',
package: 'stream_chat_flutter', package: 'stream_chat_flutter',
width: 16.0, width: 16.0,
height: 16.0, height: 16.0,
),
maxRadius: 12.0,
)
: null,
title: Text.rich(
TextSpan(
text: '${c.name.capitalize()}',
style: TextStyle(fontWeight: FontWeight.bold),
children: [
TextSpan(
text: ' /${c.name} ${c.args}',
style: TextStyle(
fontWeight: FontWeight.w300,
),
),
],
),
),
trailing: CircleAvatar(
backgroundColor:
StreamChatTheme.of(context).accentColor,
child: Icon(
StreamIcons.lightning,
color: Colors.white,
size: 12.5,
),
maxRadius: 12,
),
//subtitle: Text(c.description),
onTap: () {
_setCommand(c);
},
), ),
maxRadius: 12.0,
) )
: null,
title: Text.rich(
TextSpan(
text: '${c.name.capitalize()}',
style: TextStyle(fontWeight: FontWeight.bold),
children: [
TextSpan(
text: ' /${c.name} ${c.args}',
style: TextStyle(
fontWeight: FontWeight.w300,
),
),
],
),
),
trailing: CircleAvatar(
backgroundColor:
StreamChatTheme.of(context).accentColor,
child: Icon(
StreamIcons.lightning,
color: Colors.white,
size: 12.5,
),
maxRadius: 12,
),
//subtitle: Text(c.description),
onTap: () {
_setCommand(c);
},
),
)
.toList(), .toList(),
], ],
), ),
@@ -637,7 +637,7 @@ class MessageInputState extends State<MessageInput> {
Widget _buildPickerSection() { Widget _buildPickerSection() {
switch (_filePickerIndex) { switch (_filePickerIndex) {
case 0: case 0:
return FutureBuilder<List<Medium>>( return FutureBuilder(
future: _getAllMedia(), future: _getAllMedia(),
builder: (context, mediaData) { builder: (context, mediaData) {
if (!mediaData.hasData) { if (!mediaData.hasData) {
@@ -647,40 +647,46 @@ class MessageInputState extends State<MessageInput> {
} }
return GridView.builder( return GridView.builder(
itemCount: mediaData.data.length, itemCount: mediaData.data.item2.length,
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3), crossAxisCount: 3),
itemBuilder: (context, position) { itemBuilder: (context, position) {
return FutureBuilder<List<dynamic>>( return Padding(
future: PhotoGallery.getThumbnail( padding: const EdgeInsets.symmetric(
mediumId: mediaData.data[position].id), horizontal: 1.0, vertical: 1.0),
builder: (context, snapshot) { child: InkWell(
if (!snapshot.hasData) { child: Stack(
return Center( children: [
child: CircularProgressIndicator(), AspectRatio(
); aspectRatio: 1.0,
} child: Image.memory(
mediaData.data.item2[position],
return Padding( fit: mediaData.data.item1[position].height >
padding: const EdgeInsets.symmetric( mediaData.data.item1[position].width
horizontal: 1.0, vertical: 1.0), ? BoxFit.fitWidth
child: InkWell( : BoxFit.fitHeight,
child: AspectRatio(
child: Image.memory(
snapshot.data,
fit: mediaData.data[position].height >
mediaData.data[position].width
? BoxFit.fitWidth
: BoxFit.fitHeight,
),
aspectRatio: 1.0,
), ),
onTap: () {
_addAttachment(mediaData.data[position]);
},
), ),
); if (_attachments.any((element) =>
}); element.id ==
mediaData.data.item1[position].id))
Container(
color: Colors.black.withOpacity(0.5),
child: Center(
child: Icon(
StreamIcons.check_send,
color: Colors.white,
size: 24.0,
),
),
),
],
),
onTap: () {
_addAttachment(mediaData.data.item1[position]);
},
),
);
}, },
); );
}); });
@@ -715,6 +721,7 @@ class MessageInputState extends State<MessageInput> {
localUri: file.path != null ? Uri.parse(file.path) : null, localUri: file.path != null ? Uri.parse(file.path) : null,
type: medium.mediumType == MediumType.image ? 'image' : 'video', type: medium.mediumType == MediumType.image ? 'image' : 'video',
), ),
id: medium.id,
); );
setState(() { setState(() {
@@ -747,10 +754,11 @@ class MessageInputState extends State<MessageInput> {
}); });
} }
Future<List<Medium>> _getAllMedia() async { Future<Tuple2<List<Medium>, List<dynamic>>> _getAllMedia() async {
var allAlbums = await PhotoGallery.listAlbums(mediumType: MediumType.image); var allAlbums = await PhotoGallery.listAlbums(mediumType: MediumType.image);
//var allVideoAlbums = await PhotoGallery.listAlbums(mediumType: MediumType.video); //var allVideoAlbums = await PhotoGallery.listAlbums(mediumType: MediumType.video);
List<Medium> resultList = []; List<Medium> resultList = [];
List<List<dynamic>> resultThumbnailList = [];
for (var album in allAlbums) { for (var album in allAlbums) {
var data = await album.listMedia(); var data = await album.listMedia();
@@ -764,7 +772,11 @@ class MessageInputState extends State<MessageInput> {
resultList.sort((a, b) => a.modifiedDate.compareTo(b.modifiedDate)); resultList.sort((a, b) => a.modifiedDate.compareTo(b.modifiedDate));
return resultList; for (var e in resultList) {
resultThumbnailList.add(await PhotoGallery.getThumbnail(mediumId: e.id));
}
return Tuple2<List<Medium>, List<dynamic>>(resultList, resultThumbnailList);
} }
OverlayEntry _buildMentionsOverlayEntry() { OverlayEntry _buildMentionsOverlayEntry() {
@@ -784,8 +796,8 @@ class MessageInputState extends State<MessageInput> {
} }
final members = StreamChannel.of(context).channel.state.members?.where((m) { final members = StreamChannel.of(context).channel.state.members?.where((m) {
return m.user.name.toLowerCase().contains(query); return m.user.name.toLowerCase().contains(query);
})?.toList() ?? })?.toList() ??
[]; [];
RenderBox renderBox = context.findRenderObject(); RenderBox renderBox = context.findRenderObject();
@@ -825,38 +837,38 @@ class MessageInputState extends State<MessageInput> {
shrinkWrap: true, shrinkWrap: true,
children: snapshot.data children: snapshot.data
.map((m) => ListTile( .map((m) => ListTile(
leading: UserAvatar( leading: UserAvatar(
user: m.user, user: m.user,
), ),
title: Text( title: Text(
'${m.user.name}', '${m.user.name}',
style: TextStyle(fontWeight: FontWeight.bold), style: TextStyle(fontWeight: FontWeight.bold),
), ),
subtitle: Text('@${m.userId}'), subtitle: Text('@${m.userId}'),
trailing: Icon( trailing: Icon(
StreamIcons.at_mention, StreamIcons.at_mention,
color: StreamChatTheme.of(context).accentColor, color: StreamChatTheme.of(context).accentColor,
), ),
onTap: () { onTap: () {
_mentionedUsers.add(m.user); _mentionedUsers.add(m.user);
splits[splits.length - 1] = m.user.name; splits[splits.length - 1] = m.user.name;
final rejoin = splits.join('@'); final rejoin = splits.join('@');
textEditingController.value = TextEditingValue( textEditingController.value = TextEditingValue(
text: rejoin + text: rejoin +
textEditingController.text.substring( textEditingController.text.substring(
textEditingController textEditingController
.selection.start), .selection.start),
selection: TextSelection.collapsed( selection: TextSelection.collapsed(
offset: rejoin.length, offset: rejoin.length,
), ),
); );
_mentionsOverlay?.remove(); _mentionsOverlay?.remove();
_mentionsOverlay = null; _mentionsOverlay = null;
}, },
)) ))
.toList(), .toList(),
); );
}), }),
@@ -881,44 +893,44 @@ class MessageInputState extends State<MessageInput> {
return _attachments.isEmpty return _attachments.isEmpty
? Container() ? Container()
: LimitedBox( : LimitedBox(
maxHeight: 76.0, maxHeight: 76.0,
child: ListView( child: ListView(
scrollDirection: Axis.horizontal, scrollDirection: Axis.horizontal,
children: _attachments children: _attachments
.map( .map(
(attachment) => Padding( (attachment) => Padding(
padding: const EdgeInsets.all(8.0), padding: const EdgeInsets.all(8.0),
child: ClipRRect( child: ClipRRect(
borderRadius: BorderRadius.circular(10), borderRadius: BorderRadius.circular(10),
child: Stack( child: Stack(
children: <Widget>[ children: <Widget>[
AspectRatio( AspectRatio(
aspectRatio: 1.0, aspectRatio: 1.0,
child: Container( child: Container(
height: 50, height: 50,
width: 50, width: 50,
child: _buildAttachment(attachment), child: _buildAttachment(attachment),
), ),
), ),
_buildRemoveButton(attachment), _buildRemoveButton(attachment),
attachment.uploaded attachment.uploaded
? SizedBox() ? SizedBox()
: Positioned.fill( : Positioned.fill(
child: Center( child: Center(
child: Padding( child: Padding(
padding: const EdgeInsets.all(16.0), padding: const EdgeInsets.all(16.0),
child: CircularProgressIndicator(), child: CircularProgressIndicator(),
),
),
),
],
),
), ),
), ),
) ),
.toList(), ],
),
), ),
); ),
)
.toList(),
),
);
} }
Positioned _buildRemoveButton(_SendingAttachment attachment) { Positioned _buildRemoveButton(_SendingAttachment attachment) {
@@ -954,7 +966,7 @@ class MessageInputState extends State<MessageInput> {
Widget _buildAttachment(_SendingAttachment attachment) { Widget _buildAttachment(_SendingAttachment attachment) {
if (widget.attachmentThumbnailBuilders if (widget.attachmentThumbnailBuilders
?.containsKey(attachment.attachment.type) == ?.containsKey(attachment.attachment.type) ==
true) { true) {
return widget.attachmentThumbnailBuilders[attachment.attachment.type]( return widget.attachmentThumbnailBuilders[attachment.attachment.type](
context, context,
@@ -967,14 +979,14 @@ class MessageInputState extends State<MessageInput> {
case 'giphy': case 'giphy':
return attachment.file != null return attachment.file != null
? Image.memory( ? Image.memory(
attachment.file.bytes, attachment.file.bytes,
fit: BoxFit.cover, fit: BoxFit.cover,
) )
: Image.network( : Image.network(
attachment.attachment.imageUrl ?? attachment.attachment.imageUrl ??
attachment.attachment.thumbUrl, attachment.attachment.thumbUrl,
fit: BoxFit.cover, fit: BoxFit.cover,
); );
break; break;
case 'video': case 'video':
return Container( return Container(
@@ -1020,7 +1032,7 @@ class MessageInputState extends State<MessageInput> {
child: InkWell( child: InkWell(
child: Padding( child: Padding(
padding: padding:
EdgeInsets.only(left: 8.0, right: padding, top: 8.0, bottom: 8.0), EdgeInsets.only(left: 8.0, right: padding, top: 8.0, bottom: 8.0),
child: Icon( child: Icon(
StreamIcons.attach, StreamIcons.attach,
color: Color(0xFF000000).withAlpha(128), color: Color(0xFF000000).withAlpha(128),
@@ -1220,10 +1232,10 @@ class MessageInputState extends State<MessageInput> {
} }
Future<String> _uploadAttachment( Future<String> _uploadAttachment(
PlatformFile file, PlatformFile file,
DefaultAttachmentTypes type, DefaultAttachmentTypes type,
Channel channel, Channel channel,
) async { ) async {
String url; String url;
if (type == DefaultAttachmentTypes.image) { if (type == DefaultAttachmentTypes.image) {
if (widget.doImageUploadRequest != null) { if (widget.doImageUploadRequest != null) {
@@ -1270,19 +1282,19 @@ class MessageInputState extends State<MessageInput> {
Widget _buildIdleSendButton(BuildContext context) { Widget _buildIdleSendButton(BuildContext context) {
return IconTheme( return IconTheme(
data: data:
StreamChatTheme.of(context).channelTheme.messageInputButtonIconTheme, StreamChatTheme.of(context).channelTheme.messageInputButtonIconTheme,
child: Padding( child: Padding(
padding: const EdgeInsets.all(8.0), padding: const EdgeInsets.all(8.0),
child: Center( child: Center(
child: InkWell( child: InkWell(
onTap: () { onTap: () {
sendMessage(); sendMessage();
}, },
child: Icon( child: Icon(
_getIdleSendIcon(), _getIdleSendIcon(),
color: Colors.grey, color: Colors.grey,
), ),
)), )),
), ),
); );
} }
@@ -1290,7 +1302,7 @@ class MessageInputState extends State<MessageInput> {
Widget _buildSendButton(BuildContext context) { Widget _buildSendButton(BuildContext context) {
return IconTheme( return IconTheme(
data: data:
StreamChatTheme.of(context).channelTheme.messageInputButtonIconTheme, StreamChatTheme.of(context).channelTheme.messageInputButtonIconTheme,
child: Center( child: Center(
child: Padding( child: Padding(
padding: const EdgeInsets.all(8.0), padding: const EdgeInsets.all(8.0),
@@ -1370,7 +1382,7 @@ class MessageInputState extends State<MessageInput> {
text: text, text: text,
attachments: _getAttachments(attachments).toList(), attachments: _getAttachments(attachments).toList(),
mentionedUsers: mentionedUsers:
_mentionedUsers.where((u) => text.contains('@${u.name}')).toList(), _mentionedUsers.where((u) => text.contains('@${u.name}')).toList(),
); );
} else { } else {
message = (widget.initialMessage ?? Message()).copyWith( message = (widget.initialMessage ?? Message()).copyWith(
@@ -1378,7 +1390,7 @@ class MessageInputState extends State<MessageInput> {
text: text, text: text,
attachments: _getAttachments(attachments).toList(), attachments: _getAttachments(attachments).toList(),
mentionedUsers: mentionedUsers:
_mentionedUsers.where((u) => text.contains('@${u.name}')).toList(), _mentionedUsers.where((u) => text.contains('@${u.name}')).toList(),
showInChannel: widget.parentMessage != null ? _sendAsDm : null, showInChannel: widget.parentMessage != null ? _sendAsDm : null,
); );
} }
@@ -1392,9 +1404,9 @@ class MessageInputState extends State<MessageInput> {
sendingFuture = channel.sendMessage(message); sendingFuture = channel.sendMessage(message);
} else { } else {
sendingFuture = StreamChat.of(context).client.updateMessage( sendingFuture = StreamChat.of(context).client.updateMessage(
message, message,
channel.cid, channel.cid,
); );
} }
return sendingFuture.then((resp) { return sendingFuture.then((resp) {
@@ -1501,11 +1513,13 @@ class _SendingAttachment {
PlatformFile file; PlatformFile file;
Attachment attachment; Attachment attachment;
bool uploaded; bool uploaded;
String id;
_SendingAttachment({ _SendingAttachment({
this.file, this.file,
this.attachment, this.attachment,
this.uploaded = false, this.uploaded = false,
this.id,
}); });
} }
@@ -1514,3 +1528,44 @@ extension StringExtension on String {
return "${this[0].toUpperCase()}${this.substring(1)}"; 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;
}