repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
---|---|---|---|
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib | mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib/pages/group_chat_details_screen.dart | import 'package:example/state/new_group_chat_state.dart';
import 'package:example/utils/localizations.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:stream_chat_flutter/stream_chat_flutter.dart';
import '../routes/routes.dart';
class GroupChatDetailsScreen extends StatefulWidget {
final NewGroupChatState groupChatState;
const GroupChatDetailsScreen({
Key? key,
required this.groupChatState,
}) : super(key: key);
@override
State<GroupChatDetailsScreen> createState() => _GroupChatDetailsScreenState();
}
class _GroupChatDetailsScreenState extends State<GroupChatDetailsScreen> {
late final TextEditingController _groupNameController =
TextEditingController()..addListener(_groupNameListener);
bool _isGroupNameEmpty = true;
int get _totalUsers => widget.groupChatState.users.length;
void _groupNameListener() {
final name = _groupNameController.text;
if (mounted) {
setState(() {
_isGroupNameEmpty = name.isEmpty;
});
}
}
@override
void dispose() {
_groupNameController.removeListener(_groupNameListener);
_groupNameController.clear();
_groupNameController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return WillPopScope(
onWillPop: () async {
GoRouter.of(context).pop();
return false;
},
child: Scaffold(
backgroundColor: StreamChatTheme.of(context).colorTheme.appBg,
appBar: AppBar(
elevation: 1,
backgroundColor: StreamChatTheme.of(context).colorTheme.barsBg,
leading: const StreamBackButton(),
title: Text(
AppLocalizations.of(context).nameOfGroupChat,
style: TextStyle(
color: StreamChatTheme.of(context).colorTheme.textHighEmphasis,
fontSize: 16,
),
),
centerTitle: true,
bottom: PreferredSize(
preferredSize: const Size.fromHeight(kToolbarHeight),
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 18, horizontal: 16),
child: Row(
children: [
Text(
AppLocalizations.of(context).name.toUpperCase(),
style: TextStyle(
fontSize: 12,
color: StreamChatTheme.of(context)
.colorTheme
.textLowEmphasis,
),
),
const SizedBox(width: 16),
Expanded(
child: TextField(
controller: _groupNameController,
decoration: InputDecoration(
isDense: true,
border: InputBorder.none,
focusedBorder: InputBorder.none,
enabledBorder: InputBorder.none,
errorBorder: InputBorder.none,
disabledBorder: InputBorder.none,
contentPadding: const EdgeInsets.all(0),
hintText:
AppLocalizations.of(context).chooseAGroupChatName,
hintStyle: TextStyle(
fontSize: 14,
color: StreamChatTheme.of(context)
.colorTheme
.textLowEmphasis,
),
),
),
),
],
),
),
),
actions: [
StreamNeumorphicButton(
child: IconButton(
padding: const EdgeInsets.all(0),
icon: StreamSvgIcon.check(
size: 24,
color: _isGroupNameEmpty
? StreamChatTheme.of(context).colorTheme.textLowEmphasis
: StreamChatTheme.of(context).colorTheme.accentPrimary,
),
onPressed: _isGroupNameEmpty
? null
: () async {
try {
final groupName = _groupNameController.text;
final client = StreamChat.of(context).client;
final router = GoRouter.of(context);
final channel = client.channel('messaging',
id: const Uuid().v4(),
extraData: {
'members': [
client.state.currentUser!.id,
...widget.groupChatState.users
.map((e) => e.id),
],
'name': groupName,
});
await channel.watch();
router.goNamed(
Routes.CHANNEL_PAGE.name,
pathParameters: Routes.CHANNEL_PAGE.params(channel),
);
} catch (err) {
_showErrorAlert();
}
},
),
),
],
),
body: StreamConnectionStatusBuilder(
statusBuilder: (context, status) {
String statusString = '';
bool showStatus = true;
switch (status) {
case ConnectionStatus.connected:
statusString = AppLocalizations.of(context).connected;
showStatus = false;
break;
case ConnectionStatus.connecting:
statusString = AppLocalizations.of(context).reconnecting;
break;
case ConnectionStatus.disconnected:
statusString = AppLocalizations.of(context).disconnected;
break;
}
return StreamInfoTile(
showMessage: showStatus,
tileAnchor: Alignment.topCenter,
childAnchor: Alignment.topCenter,
message: statusString,
child: Column(
children: [
Container(
width: double.maxFinite,
decoration: BoxDecoration(
gradient:
StreamChatTheme.of(context).colorTheme.bgGradient,
),
child: Padding(
padding: const EdgeInsets.symmetric(
vertical: 8,
horizontal: 8,
),
child: Text(
'$_totalUsers ${_totalUsers > 1 ? AppLocalizations.of(context).members : AppLocalizations.of(context).member}',
style: TextStyle(
color: StreamChatTheme.of(context)
.colorTheme
.textLowEmphasis,
),
),
),
),
AnimatedBuilder(
animation: widget.groupChatState,
builder: (context, child) {
return Expanded(
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onPanDown: (_) => FocusScope.of(context).unfocus(),
child: ListView.separated(
itemCount: widget.groupChatState.users.length + 1,
separatorBuilder: (_, __) => Container(
height: 1,
color: StreamChatTheme.of(context)
.colorTheme
.borders,
),
itemBuilder: (_, index) {
if (index ==
widget.groupChatState.users.length) {
return Container(
height: 1,
color: StreamChatTheme.of(context)
.colorTheme
.borders,
);
}
final user = widget.groupChatState.users
.elementAt(index);
return ListTile(
key: ObjectKey(user),
leading: StreamUserAvatar(
user: user,
constraints: const BoxConstraints.tightFor(
width: 40,
height: 40,
),
),
title: Text(
user.name,
style: const TextStyle(
fontWeight: FontWeight.bold),
),
contentPadding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 8,
),
trailing: IconButton(
icon: Icon(
Icons.clear_rounded,
color: StreamChatTheme.of(context)
.colorTheme
.textHighEmphasis,
),
padding: const EdgeInsets.all(0),
splashRadius: 24,
onPressed: () {
widget.groupChatState.removeUser(user);
if (widget.groupChatState.users.isEmpty) {
GoRouter.of(context).pop();
}
},
),
);
},
),
),
);
}),
],
),
);
},
),
),
);
}
void _showErrorAlert() {
showModalBottomSheet(
useRootNavigator: false,
backgroundColor: StreamChatTheme.of(context).colorTheme.barsBg,
context: context,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(16.0),
topRight: Radius.circular(16.0),
)),
builder: (context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
const SizedBox(
height: 26.0,
),
StreamSvgIcon.error(
color: StreamChatTheme.of(context).colorTheme.accentError,
size: 24.0,
),
const SizedBox(
height: 26.0,
),
Text(
AppLocalizations.of(context).somethingWentWrongErrorMessage,
style: StreamChatTheme.of(context).textTheme.headlineBold,
),
const SizedBox(
height: 7.0,
),
Text(AppLocalizations.of(context).operationCouldNotBeCompleted),
const SizedBox(
height: 36.0,
),
Container(
color: StreamChatTheme.of(context)
.colorTheme
.textHighEmphasis
.withOpacity(.08),
height: 1.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextButton(
onPressed: GoRouter.of(context).pop,
child: Text(
AppLocalizations.of(context).ok,
style: StreamChatTheme.of(context)
.textTheme
.bodyBold
.copyWith(
color: StreamChatTheme.of(context)
.colorTheme
.accentPrimary),
),
),
],
),
],
);
},
);
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib | mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib/pages/channel_media_display_screen.dart | import 'package:example/utils/localizations.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:stream_chat_flutter/stream_chat_flutter.dart';
import 'package:video_player/video_player.dart';
import '../routes/routes.dart';
class ChannelMediaDisplayScreen extends StatefulWidget {
final StreamMessageThemeData messageTheme;
const ChannelMediaDisplayScreen({
Key? key,
required this.messageTheme,
}) : super(key: key);
@override
State<ChannelMediaDisplayScreen> createState() =>
_ChannelMediaDisplayScreenState();
}
class _ChannelMediaDisplayScreenState extends State<ChannelMediaDisplayScreen> {
final Map<String?, VideoPlayerController?> controllerCache = {};
late final controller = StreamMessageSearchListController(
client: StreamChat.of(context).client,
filter: Filter.in_(
'cid',
[StreamChannel.of(context).channel.cid!],
),
messageFilter: Filter.in_(
'attachments.type',
const ['image', 'video'],
),
sort: [
const SortOption(
'created_at',
direction: SortOption.ASC,
),
],
limit: 20,
);
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: StreamChatTheme.of(context).colorTheme.barsBg,
appBar: AppBar(
elevation: 1,
centerTitle: true,
title: Text(
AppLocalizations.of(context).photosAndVideos,
style: TextStyle(
color: StreamChatTheme.of(context).colorTheme.textHighEmphasis,
fontSize: 16.0,
),
),
leading: const StreamBackButton(),
backgroundColor: StreamChatTheme.of(context).colorTheme.barsBg,
),
body: ValueListenableBuilder(
valueListenable: controller,
builder: (BuildContext context,
PagedValue<String, GetMessageResponse> value, Widget? child) {
return value.when(
(items, nextPageKey, error) {
if (items.isEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
StreamSvgIcon.pictures(
size: 136.0,
color: StreamChatTheme.of(context).colorTheme.disabled,
),
const SizedBox(height: 16.0),
Text(
AppLocalizations.of(context).noMedia,
style: TextStyle(
fontSize: 14.0,
color: StreamChatTheme.of(context)
.colorTheme
.textHighEmphasis,
),
),
const SizedBox(height: 8.0),
Text(
AppLocalizations.of(context)
.photosOrVideosWillAppearHere,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 14.0,
color: StreamChatTheme.of(context)
.colorTheme
.textHighEmphasis
.withOpacity(0.5),
),
),
],
),
);
}
final media = <_AssetPackage>[];
for (final item in value.asSuccess.items) {
item.message.attachments
.where((e) =>
(e.type == 'image' || e.type == 'video') &&
e.ogScrapeUrl == null)
.forEach((e) {
VideoPlayerController? controller;
if (e.type == 'video') {
final cachedController = controllerCache[e.assetUrl];
if (cachedController == null) {
controller = VideoPlayerController.network(e.assetUrl!);
controller.initialize();
controllerCache[e.assetUrl] = controller;
} else {
controller = cachedController;
}
}
media.add(_AssetPackage(e, item.message, controller));
});
}
return LazyLoadScrollView(
onEndOfPage: () async {
if (nextPageKey != null) {
controller.loadMore(nextPageKey);
}
},
child: GridView.builder(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3),
itemBuilder: (context, position) {
var channel = StreamChannel.of(context).channel;
return Padding(
padding: const EdgeInsets.all(1.0),
child: InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => StreamChannel(
channel: channel,
child: StreamFullScreenMedia(
mediaAttachmentPackages: media
.map(
(e) => StreamAttachmentPackage(
attachment: e.attachment,
message: e.message,
),
)
.toList(),
startIndex: position,
userName: media[position].message.user!.name,
onShowMessage: (m, c) async {
final router = GoRouter.of(context);
if (channel.state == null) {
await channel.watch();
}
router.pushNamed(
Routes.CHANNEL_PAGE.name,
pathParameters:
Routes.CHANNEL_PAGE.params(channel),
queryParameters:
Routes.CHANNEL_PAGE.queryParams(m),
);
},
),
),
),
);
},
child: media[position].attachment.type == 'image'
? IgnorePointer(
child: StreamImageAttachment(
attachment: media[position].attachment,
message: media[position].message,
showTitle: false,
messageTheme: widget.messageTheme,
),
)
: VideoPlayer(media[position].videoPlayer!),
),
);
},
itemCount: media.length,
),
);
},
loading: () => const Center(
child: CircularProgressIndicator(),
),
error: (_) => const Offstage(),
);
},
),
);
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
@override
void initState() {
controller.doInitialLoad();
super.initState();
}
}
class _AssetPackage {
Attachment attachment;
Message message;
VideoPlayerController? videoPlayer;
_AssetPackage(this.attachment, this.message, this.videoPlayer);
}
| 0 |
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib | mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib/pages/new_chat_screen.dart | import 'dart:async';
import 'package:example/utils/localizations.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:stream_chat_flutter/stream_chat_flutter.dart';
import '../widgets/chips_input_text_field.dart';
import '../routes/routes.dart';
class NewChatScreen extends StatefulWidget {
const NewChatScreen({super.key});
@override
State<NewChatScreen> createState() => _NewChatScreenState();
}
class _NewChatScreenState extends State<NewChatScreen> {
final _chipInputTextFieldStateKey =
GlobalKey<ChipInputTextFieldState<User>>();
late TextEditingController _controller;
late final userListController = StreamUserListController(
client: StreamChat.of(context).client,
limit: 25,
filter: Filter.and([
Filter.notEqual('id', StreamChat.of(context).currentUser!.id),
]),
sort: [
const SortOption(
'name',
direction: 1,
),
],
);
ChipInputTextFieldState? get _chipInputTextFieldState =>
_chipInputTextFieldStateKey.currentState;
String _userNameQuery = '';
final _selectedUsers = <User>{};
final _searchFocusNode = FocusNode();
final _messageInputFocusNode = FocusNode();
bool _isSearchActive = false;
Channel? channel;
Timer? _debounce;
bool _showUserList = true;
void _userNameListener() {
if (_debounce?.isActive ?? false) _debounce!.cancel();
_debounce = Timer(const Duration(milliseconds: 350), () {
if (mounted) {
setState(() {
_userNameQuery = _controller.text;
_isSearchActive = _userNameQuery.isNotEmpty;
});
userListController.filter = Filter.and([
if (_userNameQuery.isNotEmpty)
Filter.autoComplete('name', _userNameQuery),
Filter.notEqual('id', StreamChat.of(context).currentUser!.id),
]);
userListController.doInitialLoad();
}
});
}
@override
void initState() {
super.initState();
channel = StreamChat.of(context).client.channel('messaging');
_controller = TextEditingController()..addListener(_userNameListener);
_searchFocusNode.addListener(() async {
if (_searchFocusNode.hasFocus && !_showUserList) {
setState(() {
_showUserList = true;
});
}
});
_messageInputFocusNode.addListener(() async {
if (_messageInputFocusNode.hasFocus && _selectedUsers.isNotEmpty) {
final chatState = StreamChat.of(context);
final res = await chatState.client.queryChannelsOnline(
state: false,
watch: false,
filter: Filter.raw(value: {
'members': [
..._selectedUsers.map((e) => e.id),
chatState.currentUser!.id,
],
'distinct': true,
}),
messageLimit: 0,
paginationParams: const PaginationParams(
limit: 1,
),
);
final channelExisted = res.length == 1;
if (channelExisted) {
channel = res.first;
await channel!.watch();
} else {
channel = chatState.client.channel(
'messaging',
extraData: {
'members': [
..._selectedUsers.map((e) => e.id),
chatState.currentUser!.id,
],
},
);
}
setState(() {
_showUserList = false;
});
}
});
}
@override
void dispose() {
_searchFocusNode.dispose();
_messageInputFocusNode.dispose();
_controller.clear();
_controller.removeListener(_userNameListener);
_controller.dispose();
userListController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: StreamChatTheme.of(context).colorTheme.appBg,
appBar: AppBar(
elevation: 0,
backgroundColor: StreamChatTheme.of(context).colorTheme.barsBg,
leading: const StreamBackButton(),
title: Text(
AppLocalizations.of(context).newChat,
style: StreamChatTheme.of(context).textTheme.headlineBold.copyWith(
color: StreamChatTheme.of(context).colorTheme.textHighEmphasis),
),
centerTitle: true,
),
body: StreamConnectionStatusBuilder(
statusBuilder: (context, status) {
String statusString = '';
bool showStatus = true;
switch (status) {
case ConnectionStatus.connected:
statusString = AppLocalizations.of(context).connected;
showStatus = false;
break;
case ConnectionStatus.connecting:
statusString = AppLocalizations.of(context).reconnecting;
break;
case ConnectionStatus.disconnected:
statusString = AppLocalizations.of(context).disconnected;
break;
}
return StreamInfoTile(
showMessage: showStatus,
tileAnchor: Alignment.topCenter,
childAnchor: Alignment.topCenter,
message: statusString,
child: StreamChannel(
showLoading: false,
channel: channel!,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ChipsInputTextField<User>(
key: _chipInputTextFieldStateKey,
controller: _controller,
focusNode: _searchFocusNode,
hint: AppLocalizations.of(context).typeANameHint,
chipBuilder: (context, user) {
return GestureDetector(
onTap: () {
_chipInputTextFieldState?.removeItem(user);
_searchFocusNode.requestFocus();
},
child: Stack(
alignment: AlignmentDirectional.centerStart,
children: [
Container(
decoration: BoxDecoration(
color: StreamChatTheme.of(context)
.colorTheme
.disabled,
borderRadius: BorderRadius.circular(12),
),
padding: const EdgeInsets.only(left: 24),
child: Padding(
padding: const EdgeInsets.fromLTRB(8, 4, 12, 4),
child: Text(
user.name,
maxLines: 1,
style: TextStyle(
color: StreamChatTheme.of(context)
.colorTheme
.textHighEmphasis,
),
),
),
),
Container(
foregroundDecoration: BoxDecoration(
color: StreamChatTheme.of(context)
.colorTheme
.overlay,
shape: BoxShape.circle,
),
child: StreamUserAvatar(
showOnlineStatus: false,
user: user,
constraints: const BoxConstraints.tightFor(
height: 24,
width: 24,
),
),
),
StreamSvgIcon.close(),
],
),
);
},
onChipAdded: (user) {
setState(() => _selectedUsers.add(user));
},
onChipRemoved: (user) {
setState(() => _selectedUsers.remove(user));
},
),
if (!_isSearchActive && !_selectedUsers.isNotEmpty)
InkWell(
onTap: () {
GoRouter.of(context).pushNamed(
Routes.NEW_GROUP_CHAT.name,
);
},
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Row(
children: [
StreamNeumorphicButton(
child: Center(
child: StreamSvgIcon.contacts(
color: StreamChatTheme.of(context)
.colorTheme
.accentPrimary,
size: 24,
),
),
),
const SizedBox(width: 8),
Text(
AppLocalizations.of(context).createAGroup,
style: StreamChatTheme.of(context)
.textTheme
.bodyBold,
),
],
),
),
),
if (_showUserList)
Container(
width: double.maxFinite,
decoration: BoxDecoration(
gradient:
StreamChatTheme.of(context).colorTheme.bgGradient,
),
child: Padding(
padding: const EdgeInsets.symmetric(
vertical: 8,
horizontal: 8,
),
child: Text(
_isSearchActive
? '${AppLocalizations.of(context).matchesFor} "$_userNameQuery"'
: AppLocalizations.of(context).onThePlatorm,
style: StreamChatTheme.of(context)
.textTheme
.footnote
.copyWith(
color: StreamChatTheme.of(context)
.colorTheme
.textHighEmphasis
.withOpacity(.5))),
),
),
Expanded(
child: _showUserList
? GestureDetector(
behavior: HitTestBehavior.opaque,
onPanDown: (_) => FocusScope.of(context).unfocus(),
child: StreamUserListView(
controller: userListController,
onUserTap: (user) {
_controller.clear();
if (!_selectedUsers.contains(user)) {
_chipInputTextFieldState
?..addItem(user)
..pauseItemAddition();
} else {
_chipInputTextFieldState!.removeItem(user);
}
},
itemBuilder: (
context,
users,
index,
defaultWidget,
) {
return defaultWidget.copyWith(
selected:
_selectedUsers.contains(users[index]),
);
},
emptyBuilder: (_) {
return LayoutBuilder(
builder: (context, viewportConstraints) {
return SingleChildScrollView(
physics:
const AlwaysScrollableScrollPhysics(),
child: ConstrainedBox(
constraints: BoxConstraints(
minHeight:
viewportConstraints.maxHeight,
),
child: Center(
child: Column(
children: [
Padding(
padding:
const EdgeInsets.all(24),
child: StreamSvgIcon.search(
size: 96,
color: Colors.grey,
),
),
Text(
AppLocalizations.of(context)
.noUserMatchesTheseKeywords,
style: StreamChatTheme.of(
context)
.textTheme
.footnote
.copyWith(
color: StreamChatTheme
.of(context)
.colorTheme
.textHighEmphasis
.withOpacity(.5)),
),
],
),
),
),
);
},
);
},
),
)
: FutureBuilder<bool>(
future: channel!.initialized,
builder: (context, snapshot) {
if (snapshot.data == true) {
return const StreamMessageListView();
}
return Center(
child: Text(
AppLocalizations.of(context).noChatsHereYet,
style: TextStyle(
fontSize: 12,
color: StreamChatTheme.of(context)
.colorTheme
.textHighEmphasis
.withOpacity(.5),
),
),
);
},
),
),
StreamMessageInput(
focusNode: _messageInputFocusNode,
preMessageSending: (message) async {
await channel!.watch();
return message;
},
onMessageSent: (m) {
GoRouter.of(context).goNamed(
Routes.CHANNEL_PAGE.name,
pathParameters: Routes.CHANNEL_PAGE.params(channel!),
);
},
),
],
),
),
);
},
),
);
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib | mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib/pages/user_mentions_page.dart | import 'package:example/utils/localizations.dart';
import 'package:example/routes/routes.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:stream_chat_flutter/stream_chat_flutter.dart';
class UserMentionsPage extends StatefulWidget {
const UserMentionsPage({super.key});
@override
State<UserMentionsPage> createState() => _UserMentionsPageState();
}
class _UserMentionsPageState extends State<UserMentionsPage> {
late final controller = StreamMessageSearchListController(
client: StreamChat.of(context).client,
filter: Filter.in_('members', [StreamChat.of(context).currentUser!.id]),
messageFilter: Filter.custom(
operator: r'$contains',
key: 'mentioned_users.id',
value: StreamChat.of(context).currentUser!.id,
),
sort: [
const SortOption(
'created_at',
direction: SortOption.ASC,
),
],
limit: 20,
);
@override
Widget build(BuildContext context) {
return StreamMessageSearchListView(
controller: controller,
emptyBuilder: (_) {
return LayoutBuilder(
builder: (context, viewportConstraints) {
return SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(),
child: ConstrainedBox(
constraints: BoxConstraints(
minHeight: viewportConstraints.maxHeight,
),
child: Center(
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(24),
child: StreamSvgIcon.mentions(
size: 96,
color:
StreamChatTheme.of(context).colorTheme.disabled,
),
),
Text(
AppLocalizations.of(context).noMentionsExistYet,
style:
StreamChatTheme.of(context).textTheme.body.copyWith(
color: StreamChatTheme.of(context)
.colorTheme
.textLowEmphasis,
),
),
],
),
),
),
);
},
);
},
onMessageTap: (messageResponse) async {
final client = StreamChat.of(context).client;
final router = GoRouter.of(context);
final message = messageResponse.message;
final channel = client.channel(
messageResponse.channel!.type,
id: messageResponse.channel!.id,
);
if (channel.state == null) {
await channel.watch();
}
router.pushNamed(
Routes.CHANNEL_PAGE.name,
pathParameters: Routes.CHANNEL_PAGE.params(channel),
queryParameters: Routes.CHANNEL_PAGE.queryParams(message),
);
},
);
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib | mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib/pages/chat_info_screen.dart | import 'package:example/pages/channel_file_display_screen.dart';
import 'package:example/utils/localizations.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:stream_chat_flutter/stream_chat_flutter.dart';
import 'package:example/pages/channel_media_display_screen.dart';
import 'package:example/pages/pinned_messages_screen.dart';
/// Detail screen for a 1:1 chat correspondence
class ChatInfoScreen extends StatefulWidget {
/// User in consideration
final User? user;
final StreamMessageThemeData messageTheme;
const ChatInfoScreen({
Key? key,
required this.messageTheme,
this.user,
}) : super(key: key);
@override
State<ChatInfoScreen> createState() => _ChatInfoScreenState();
}
class _ChatInfoScreenState extends State<ChatInfoScreen> {
ValueNotifier<bool?> mutedBool = ValueNotifier(false);
@override
void initState() {
super.initState();
mutedBool = ValueNotifier(StreamChannel.of(context).channel.isMuted);
}
@override
Widget build(BuildContext context) {
final channel = StreamChannel.of(context).channel;
return Scaffold(
backgroundColor: StreamChatTheme.of(context).colorTheme.appBg,
body: ListView(
children: [
_buildUserHeader(),
Container(
height: 8.0,
color: StreamChatTheme.of(context).colorTheme.disabled,
),
_buildOptionListTiles(),
Container(
height: 8.0,
color: StreamChatTheme.of(context).colorTheme.disabled,
),
if (channel.ownCapabilities.contains(PermissionType.deleteChannel))
_buildDeleteListTile(),
],
),
);
}
Widget _buildUserHeader() {
return Material(
color: StreamChatTheme.of(context).colorTheme.appBg,
child: SafeArea(
child: Stack(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.all(16.0),
child: StreamUserAvatar(
user: widget.user!,
constraints: const BoxConstraints.tightFor(
width: 72.0,
height: 72.0,
),
borderRadius: BorderRadius.circular(36.0),
showOnlineStatus: false,
),
),
Text(
widget.user!.name,
style: const TextStyle(
fontSize: 16.0, fontWeight: FontWeight.bold),
),
const SizedBox(height: 7.0),
_buildConnectedTitleState(),
const SizedBox(height: 15.0),
StreamOptionListTile(
title: '@${widget.user!.id}',
tileColor: StreamChatTheme.of(context).colorTheme.appBg,
trailing: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: Text(
widget.user!.name,
style: TextStyle(
color: StreamChatTheme.of(context)
.colorTheme
.textHighEmphasis
.withOpacity(0.5),
fontSize: 16.0),
),
),
onTap: () {},
),
],
),
const Positioned(
top: 0,
left: 0,
width: 58,
child: StreamBackButton(),
),
],
),
),
);
}
Widget _buildOptionListTiles() {
final channel = StreamChannel.of(context);
return Column(
children: [
StreamBuilder<bool>(
stream: StreamChannel.of(context).channel.isMutedStream,
builder: (context, snapshot) {
mutedBool.value = snapshot.data;
return StreamOptionListTile(
tileColor: StreamChatTheme.of(context).colorTheme.appBg,
title: AppLocalizations.of(context).muteUser,
titleTextStyle: StreamChatTheme.of(context).textTheme.body,
leading: Padding(
padding: const EdgeInsets.symmetric(horizontal: 22.0),
child: StreamSvgIcon.mute(
size: 24.0,
color: StreamChatTheme.of(context)
.colorTheme
.textHighEmphasis
.withOpacity(0.5),
),
),
trailing: snapshot.data == null
? const CircularProgressIndicator()
: ValueListenableBuilder<bool?>(
valueListenable: mutedBool,
builder: (context, value, _) {
return CupertinoSwitch(
value: value!,
onChanged: (val) {
mutedBool.value = val;
if (snapshot.data!) {
channel.channel.unmute();
} else {
channel.channel.mute();
}
},
);
}),
onTap: () {},
);
}),
StreamOptionListTile(
title: AppLocalizations.of(context).pinnedMessages,
tileColor: StreamChatTheme.of(context).colorTheme.appBg,
titleTextStyle: StreamChatTheme.of(context).textTheme.body,
leading: Padding(
padding: const EdgeInsets.symmetric(horizontal: 22.0),
child: StreamSvgIcon.pin(
size: 24.0,
color: StreamChatTheme.of(context)
.colorTheme
.textHighEmphasis
.withOpacity(0.5),
),
),
trailing: StreamSvgIcon.right(
color: StreamChatTheme.of(context).colorTheme.textLowEmphasis,
),
onTap: () {
final channel = StreamChannel.of(context).channel;
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => StreamChannel(
channel: channel,
child: const PinnedMessagesScreen(),
),
),
);
},
),
StreamOptionListTile(
title: AppLocalizations.of(context).photosAndVideos,
tileColor: StreamChatTheme.of(context).colorTheme.appBg,
titleTextStyle: StreamChatTheme.of(context).textTheme.body,
leading: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: StreamSvgIcon.pictures(
size: 36.0,
color: StreamChatTheme.of(context)
.colorTheme
.textHighEmphasis
.withOpacity(0.5),
),
),
trailing: StreamSvgIcon.right(
color: StreamChatTheme.of(context).colorTheme.textLowEmphasis,
),
onTap: () {
final channel = StreamChannel.of(context).channel;
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => StreamChannel(
channel: channel,
child: ChannelMediaDisplayScreen(
messageTheme: widget.messageTheme,
),
),
),
);
},
),
StreamOptionListTile(
title: AppLocalizations.of(context).files,
tileColor: StreamChatTheme.of(context).colorTheme.appBg,
titleTextStyle: StreamChatTheme.of(context).textTheme.body,
leading: Padding(
padding: const EdgeInsets.symmetric(horizontal: 18.0),
child: StreamSvgIcon.files(
size: 32.0,
color: StreamChatTheme.of(context)
.colorTheme
.textHighEmphasis
.withOpacity(0.5),
),
),
trailing: StreamSvgIcon.right(
color: StreamChatTheme.of(context).colorTheme.textLowEmphasis,
),
onTap: () {
final channel = StreamChannel.of(context).channel;
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => StreamChannel(
channel: channel,
child: ChannelFileDisplayScreen(
messageTheme: widget.messageTheme,
),
),
),
);
},
),
StreamOptionListTile(
title: AppLocalizations.of(context).sharedGroups,
tileColor: StreamChatTheme.of(context).colorTheme.appBg,
titleTextStyle: StreamChatTheme.of(context).textTheme.body,
leading: Padding(
padding: const EdgeInsets.symmetric(horizontal: 22.0),
child: StreamSvgIcon.iconGroup(
size: 24.0,
color: StreamChatTheme.of(context)
.colorTheme
.textHighEmphasis
.withOpacity(0.5),
),
),
trailing: StreamSvgIcon.right(
color: StreamChatTheme.of(context).colorTheme.textLowEmphasis,
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => _SharedGroupsScreen(
StreamChat.of(context).currentUser, widget.user)));
},
),
],
);
}
Widget _buildDeleteListTile() {
return StreamOptionListTile(
title: 'Delete Conversation',
tileColor: StreamChatTheme.of(context).colorTheme.appBg,
titleTextStyle: StreamChatTheme.of(context).textTheme.body.copyWith(
color: StreamChatTheme.of(context).colorTheme.accentError,
),
leading: Padding(
padding: const EdgeInsets.symmetric(horizontal: 22.0),
child: StreamSvgIcon.delete(
color: StreamChatTheme.of(context).colorTheme.accentError,
size: 24.0,
),
),
onTap: () {
_showDeleteDialog();
},
titleColor: StreamChatTheme.of(context).colorTheme.accentError,
);
}
void _showDeleteDialog() async {
final streamChannel = StreamChannel.of(context);
final res = await showConfirmationBottomSheet(
context,
title: AppLocalizations.of(context).deleteConversationTitle,
okText: AppLocalizations.of(context).delete.toUpperCase(),
question: AppLocalizations.of(context).deleteConversationAreYouSure,
cancelText: AppLocalizations.of(context).cancel.toUpperCase(),
icon: StreamSvgIcon.delete(
color: StreamChatTheme.of(context).colorTheme.accentError,
),
);
final channel = streamChannel.channel;
if (res == true) {
await channel.delete().then((value) {
Navigator.pop(context);
Navigator.pop(context);
});
}
}
Widget _buildConnectedTitleState() {
late Text alternativeWidget;
final otherMember = widget.user;
if (otherMember != null) {
if (otherMember.online) {
alternativeWidget = Text(
AppLocalizations.of(context).online,
style: TextStyle(
color: StreamChatTheme.of(context)
.colorTheme
.textHighEmphasis
.withOpacity(0.5)),
);
} else {
alternativeWidget = Text(
'${AppLocalizations.of(context).lastSeen} ${Jiffy.parseFromDateTime(otherMember.lastActive!).fromNow()}',
style: TextStyle(
color: StreamChatTheme.of(context)
.colorTheme
.textHighEmphasis
.withOpacity(0.5)),
);
}
}
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (widget.user!.online)
Material(
type: MaterialType.circle,
color: StreamChatTheme.of(context).colorTheme.barsBg,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
constraints: const BoxConstraints.tightFor(
width: 24,
height: 12,
),
child: Material(
shape: const CircleBorder(),
color: StreamChatTheme.of(context).colorTheme.accentInfo,
),
),
),
alternativeWidget,
if (widget.user!.online)
const SizedBox(
width: 24.0,
),
],
);
}
}
class _SharedGroupsScreen extends StatefulWidget {
final User? mainUser;
final User? otherUser;
const _SharedGroupsScreen(this.mainUser, this.otherUser);
@override
__SharedGroupsScreenState createState() => __SharedGroupsScreenState();
}
class __SharedGroupsScreenState extends State<_SharedGroupsScreen> {
@override
Widget build(BuildContext context) {
final chat = StreamChat.of(context);
return Scaffold(
backgroundColor: StreamChatTheme.of(context).colorTheme.appBg,
appBar: AppBar(
elevation: 1,
centerTitle: true,
title: Text(
AppLocalizations.of(context).sharedGroups,
style: TextStyle(
color: StreamChatTheme.of(context).colorTheme.textHighEmphasis,
fontSize: 16.0),
),
leading: const StreamBackButton(),
backgroundColor: StreamChatTheme.of(context).colorTheme.barsBg,
),
body: StreamBuilder<List<Channel>>(
stream: chat.client.queryChannels(
filter: Filter.and([
Filter.in_('members', [widget.otherUser!.id]),
Filter.in_('members', [widget.mainUser!.id]),
]),
),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const Center(
child: CircularProgressIndicator(),
);
}
if (snapshot.data!.isEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
StreamSvgIcon.message(
size: 136.0,
color: StreamChatTheme.of(context).colorTheme.disabled,
),
const SizedBox(height: 16.0),
Text(
AppLocalizations.of(context).noSharedGroups,
style: TextStyle(
fontSize: 14.0,
color: StreamChatTheme.of(context)
.colorTheme
.textHighEmphasis,
),
),
const SizedBox(height: 8.0),
Text(
AppLocalizations.of(context).groupSharedWithUserAppearHere,
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 14.0,
color: StreamChatTheme.of(context)
.colorTheme
.textHighEmphasis
.withOpacity(0.5),
),
),
],
),
);
}
final channels = snapshot.data!
.where((c) =>
c.state!.members.any((m) =>
m.userId != widget.mainUser!.id &&
m.userId != widget.otherUser!.id) ||
!c.isDistinct)
.toList();
return ListView.builder(
itemCount: channels.length,
itemBuilder: (context, position) {
return StreamChannel(
channel: channels[position],
child: _buildListTile(channels[position]),
);
},
);
},
),
);
}
Widget _buildListTile(Channel channel) {
final extraData = channel.extraData;
final members = channel.state!.members;
const textStyle = TextStyle(fontSize: 14.0, fontWeight: FontWeight.bold);
return SizedBox(
height: 64.0,
child: LayoutBuilder(
builder: (context, constraints) {
String? title;
if (extraData['name'] == null) {
final otherMembers = members.where((member) =>
member.userId != StreamChat.of(context).currentUser!.id);
if (otherMembers.isNotEmpty) {
final maxWidth = constraints.maxWidth;
final maxChars = maxWidth / textStyle.fontSize!;
var currentChars = 0;
final currentMembers = <Member>[];
for (final element in otherMembers) {
final newLength = currentChars + element.user!.name.length;
if (newLength < maxChars) {
currentChars = newLength;
currentMembers.add(element);
}
}
final exceedingMembers =
otherMembers.length - currentMembers.length;
title =
'${currentMembers.map((e) => e.user!.name).join(', ')} ${exceedingMembers > 0 ? '+ $exceedingMembers' : ''}';
} else {
title = 'No title';
}
} else {
title = extraData['name'] as String;
}
return Column(
children: [
Expanded(
child: Row(
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: StreamChannelAvatar(
channel: channel,
constraints: const BoxConstraints(
maxWidth: 40.0, maxHeight: 40.0),
),
),
Expanded(
child: Text(
title,
style: textStyle,
)),
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'${channel.memberCount} ${AppLocalizations.of(context).members.toLowerCase()}',
style: TextStyle(
color: StreamChatTheme.of(context)
.colorTheme
.textHighEmphasis
.withOpacity(0.5)),
),
)
],
),
),
Container(
height: 1.0,
color: StreamChatTheme.of(context)
.colorTheme
.textHighEmphasis
.withOpacity(.08),
),
],
);
},
),
);
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib | mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib/state/init_data.dart | import 'package:flutter/widgets.dart';
import 'package:stream_chat_flutter/stream_chat_flutter.dart';
import 'package:streaming_shared_preferences/streaming_shared_preferences.dart';
/// {@template init_notifier}
/// [ChangeNotifier] to store [InitData] and notify listeners on change.
/// {@endtemplate}
class InitNotifier extends ChangeNotifier {
/// {@macro init_notifier}
InitNotifier();
InitData? _initData;
set initData(InitData? data) {
_initData = data;
notifyListeners();
}
InitData? get initData => _initData;
}
/// {@template init_data}
/// Manages the initialization data for the sample application.
///
/// Stores a reference to the current [StreamChatClient].
/// {@endtemplate}
class InitData {
/// {@macro init_data}
InitData(this.client, this.preferences);
final StreamChatClient client;
final StreamingSharedPreferences preferences;
InitData copyWith({required StreamChatClient client}) =>
InitData(client, preferences);
}
| 0 |
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib | mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib/state/new_group_chat_state.dart | import 'package:flutter/widgets.dart';
import 'package:stream_chat_flutter/stream_chat_flutter.dart';
class NewGroupChatState extends ChangeNotifier {
final users = <User>{};
void addUser(User user) {
if (!users.contains(user)) {
users.add(user);
notifyListeners();
}
}
void removeUser(User user) {
if (users.contains(user)) {
users.remove(user);
notifyListeners();
}
}
void addOrRemoveUser(User user) {
if (users.contains(user)) {
users.remove(user);
} else {
users.add(user);
}
notifyListeners();
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib | mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib/utils/notifications_service.dart | import 'package:example/routes/routes.dart';
import 'package:example/utils/localizations.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart'
hide Message;
import 'package:go_router/go_router.dart';
import 'package:stream_chat_flutter/stream_chat_flutter.dart';
void showLocalNotification(
Event event,
String currentUserId,
BuildContext context,
) async {
// Don't show notification if the event is from the current user.
if (event.user!.id == currentUserId) return;
// Don't show notification if the event is not a message.
if (![
EventType.messageNew,
EventType.notificationMessageNew,
].contains(event.type)) return;
// Return if the message is null.
if (event.message == null) return;
final flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
const initializationSettings = InitializationSettings(
iOS: DarwinInitializationSettings(),
android: AndroidInitializationSettings('ic_notification_in_app'),
);
final appLocalizations = AppLocalizations.of(context);
await flutterLocalNotificationsPlugin.initialize(
initializationSettings,
onDidReceiveNotificationResponse: (response) async {
final channelCid = response.payload;
if (channelCid == null) return;
final channelType = channelCid.split(':')[0];
final channelId = channelCid.split(':')[1];
final client = StreamChat.of(context).client;
final router = GoRouter.of(context);
final channel = client.channel(channelType, id: channelId);
await channel.watch();
router.pushNamed(
Routes.CHANNEL_PAGE.name,
pathParameters: Routes.CHANNEL_PAGE.params(channel),
);
},
);
await flutterLocalNotificationsPlugin.show(
event.message!.id.hashCode,
event.message!.user!.name,
event.message!.text,
NotificationDetails(
android: AndroidNotificationDetails(
'message channel',
appLocalizations.messageChannelName,
channelDescription: appLocalizations.messageChannelDescription,
priority: Priority.high,
importance: Importance.high,
),
iOS: const DarwinNotificationDetails(),
),
payload: '${event.channelType}:${event.channelId}',
);
}
Future<void> cancelLocalNotifications() async {
final flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
await flutterLocalNotificationsPlugin.cancelAll();
}
| 0 |
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib | mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib/utils/app_config.dart | import 'package:stream_chat_flutter/stream_chat_flutter.dart';
const sentryDsn =
'https://[email protected]/6352870';
const kDefaultStreamApiKey = 'kv7mcsxr24p8';
final defaultUsers = <String, User>{
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoic2FsdmF0b3JlIn0.pgiJz7sIc7iP29BHKFwe3nLm5-OaR_1l2P-SlgiC9a8':
User(
id: 'salvatore',
extraData: const {
'name': 'Salvatore Giordano',
'image':
'https://avatars.githubusercontent.com/u/20601437?s=460&u=3f66c22a7483980624804054ae7f357cf102c784&v=4',
},
),
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoic2FoaWwifQ.WnIUoB5gR2kcAsFhiDvkiD6zdHXZ-VSU2aQWWkhsvfo':
User(
id: 'sahil',
extraData: const {
'name': 'Sahil Kumar',
'image':
'https://avatars.githubusercontent.com/u/25670178?s=400&u=30ded3784d8d2310c5748f263fd5e6433c119aa1&v=4',
},
),
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiYmVuIn0.nAz2sNFGQwY7rl2Og2z3TGHUsdpnN53tOsUglJFvLmg':
User(
id: 'ben',
extraData: const {
'name': 'Ben Golden',
'image': 'https://avatars.githubusercontent.com/u/1581974?s=400&v=4',
},
),
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoidGhpZXJyeSJ9.lEq6TrZtHzjoNtf7HHRufUPyGo_pa8vg4_XhEBp4ckY':
User(
id: 'thierry',
extraData: const {
'name': 'Thierry Schellenbach',
'image':
'https://avatars.githubusercontent.com/u/265409?s=400&u=2d0e3bb1820db992066196bff7b004f0eee8e28d&v=4',
},
),
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoidG9tbWFzbyJ9.GLSI0ESshERMo2WjUpysD709NEtn1zmGimUN2an7g9o':
User(
id: 'tommaso',
extraData: const {
'name': 'Tommaso Barbugli',
'image': 'https://avatars.githubusercontent.com/u/88735?s=400&v=4',
},
),
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoiZGV2ZW4ifQ.z3zI4PqJnNhc-1o-VKcmb6BnnQ0oxFNCRHwEulHqcWc':
User(
id: 'deven',
extraData: const {
'name': 'Deven Joshi',
'image':
'https://avatars.githubusercontent.com/u/26357843?s=400&u=0c61d890866e67bf69f58878be58915e9bfd39ee&v=4',
},
),
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoibmVldmFzaCJ9.3EdHegTxibrz3A9cTiKmpEyawwcCVB8FXnoFzr4eKvw':
User(
id: 'neevash',
extraData: const {
'name': 'Neevash Ramdial',
'image':
'https://avatars.githubusercontent.com/u/25674767?s=400&u=1d7333baf7dd9d143db8bfcdb31a838b89cfff9c&v=4',
},
),
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoicWF0ZXN0MSJ9.fnelU7HcP7QoEEsCGteNlF1fppofzNlrnpDQuIgeKCU':
User(
id: 'qatest1',
extraData: const {
'name': 'QA test 1',
},
),
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoicWF0ZXN0MiJ9.vSCqAEbs2WVmMWsOsa7065Fsjq-rsTih6qsHPynl7XM':
User(
id: 'qatest2',
extraData: const {
'name': 'QA test 2',
},
),
};
| 0 |
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib | mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib/utils/local_notification_observer.dart | import 'dart:async';
import 'package:example/routes/routes.dart';
import 'package:example/utils/notifications_service.dart' as pn;
import 'package:flutter/material.dart';
import 'package:stream_chat_flutter/stream_chat_flutter.dart';
class LocalNotificationObserver extends NavigatorObserver {
Route? currentRoute;
late final StreamSubscription _subscription;
LocalNotificationObserver(
StreamChatClient client,
GlobalKey<NavigatorState> navigatorKey,
) {
_subscription = client
.on(
EventType.messageNew,
EventType.notificationMessageNew,
)
.listen((event) {
_handleEvent(event, client, navigatorKey);
});
}
void _handleEvent(Event event, StreamChatClient client,
GlobalKey<NavigatorState> navigatorKey) {
if (event.message?.user?.id == client.state.currentUser?.id) {
return;
}
final channelId = event.cid;
if (currentRoute?.settings.name == Routes.CHANNEL_PAGE.name) {
final args = currentRoute?.settings.arguments as Map<String, String>;
if (args['cid'] == channelId) {
return;
}
}
pn.showLocalNotification(
event,
client.state.currentUser!.id,
navigatorKey.currentState!.context,
);
}
@override
void didPop(Route route, Route? previousRoute) {
currentRoute = route;
}
@override
void didPush(Route route, Route? previousRoute) {
currentRoute = route;
}
@override
void didRemove(Route route, Route? previousRoute) {
currentRoute = route;
}
@override
void didReplace({Route? newRoute, Route? oldRoute}) {
currentRoute = newRoute;
}
void dispose() {
_subscription.cancel();
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib | mirrored_repositories/flutter-samples/packages/stream_chat_v1/lib/utils/localizations.dart | import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class AppLocalizations {
static const _localizedValues = <String, Map<String, String>>{
'en': {
'add_a_group_name': 'Add a group name',
'add_group_members': 'Add Group Members',
'advanced_options': 'Advanced Options',
'api_key_error': 'Please enter the Chat API Key',
'attachment': 'attachment',
'attachments': 'attachments',
'cancel': 'Cancel',
'chat_api_key': 'Chat API Key',
'chats': 'Chats',
'choose_a_group_chat_name': 'Choose a group chat name',
'connected': 'Connected',
'create_a_group': 'Create a Group',
'custom_settings': 'Custom settings',
'delete': 'Delete',
'delete_conversation_are_you_sure':
'Are you sure you want to delete this conversation?',
'delete_conversation_title': 'Delete Conversation',
'disconnected': 'Disconnected',
'error_connecting': 'Error connecting, retry',
'files': 'Files',
'files_appear_here': 'Files sent in this chat will appear here',
'group_shared_with_user_appear_here':
'Group shared with User will appear here.',
'last_seen': 'Last seen',
'leave': 'Leave',
'leave_conversation': 'Leave conversation',
'leave_conversation_are_you_sure':
'Are you sure you want to leave this conversation?',
'leave_group': 'Leave Group',
'loading': 'Loading...',
'login': 'Login',
'long_press_message': 'Long-press an important message and\nchoose',
'matches_for': 'Matches for',
'member': 'Member',
'members': 'Members',
'mentions': 'Mentions',
'message': 'Message',
'message_channel_description': 'Channel used for showing messages',
'message_channel_name': 'Message channel',
'more': 'more',
'mute_group': 'Mute group',
'mute_user': 'Mute user',
'name': 'Name',
'name_of_group_chat': 'Name of Group Chat',
'new_chat': 'New Chat',
'new_direct_message': 'New direct message',
'new_group': 'New group',
'no_chats_here_yet': 'No chats here yet...',
'no_files': 'No Files',
'no_media': 'No Media',
'no_mentions_exist_yet': 'No mentions exist yet...',
'no_pinned_items': 'No pinned items',
'no_results': 'No results...',
'no_shared_groups': 'No Shared Groups',
'no_title': 'No title',
'no_user_matches_these_keywords': 'No user matches these keywords...',
'ok': 'OK',
'online': 'Online',
'on_the_platform': 'On the platform',
'operation_could_not_be_completed':
'The operation couldn\'t be completed.',
'owner': 'Owner',
'photos_and_videos': 'Photos & Videos',
'photos_or_videos_will_appear_here':
'Photos or videos sent in this chat will \nappear here',
'pinned_messages': 'Pinned Messages',
'pin_to_conversation': 'Pin to conversation',
'reconnecting': 'Reconnecting...',
'remove': 'Remove',
'remove_from_group': 'Remove From Group',
'remove_member': 'Remove member',
'remove_member_are_you_sure':
'Are you sure you want to remove this member?',
'search': 'Search',
'select_user_to_try_flutter_sdk': 'Select a user to try the Flutter SDK',
'shared_groups': 'Shared Groups',
'sign_out': 'Sign out',
'something_went_wrong_error_message': 'Something went wrong',
'stream_sdk': 'Stream SDK',
'stream_test_account': 'Stream test account',
'to': 'To',
'type_a_name_hint': 'Type a name',
'user_id': 'User ID',
'user_id_error': 'Please enter the User ID',
'username_optional': 'Username (optional)',
'user_token': 'User Token',
'user_token_error': 'Please enter the user token',
'view_info': 'View info',
'welcome_to_stream_chat': 'Welcome to Stream Chat',
},
'it': {
'add_a_group_name': 'Aggiungi un nome al gruppo',
'add_group_members': 'Aggiungi un membro',
'advanced_options': 'Opzioni Avanzate',
'api_key_error': 'Per favore inserisci l\'API Key',
'attachment': 'allegato',
'attachments': 'allegati',
'cancel': 'Annulla',
'chat_api_key': 'Chat API Key',
'chats': 'Conversazioni',
'choose_a_group_chat_name': 'Scegli un nome per il gruppo',
'connected': 'Connesso',
'create_a_group': 'Crea un Gruppo',
'custom_settings': 'Opzioni Personalizzate',
'delete': 'Cancella',
'delete_conversation_are_you_sure':
'Sei sicuro di voler eliminare la conversazione?',
'delete_conversation_title': 'Elimina Conversazione',
'disconnected': 'Disconnesso',
'error_connecting': 'Errore durante la connessione, riprova',
'files': 'File',
'files_appear_here': 'I file inviati in questa chat compariranno qui',
'group_shared_with_user_appear_here':
'I gruppi in comune con quest\'utente compariranno qui',
'last_seen': 'Ultimo accesso',
'leave': 'Lascia',
'leave_conversation': 'Lascia conversazione',
'leave_conversation_are_you_sure':
'Sei sicuro di voler lasciare questa conversazione?',
'leave_group': 'Lascia Gruppo',
'loading': 'Caricamento...',
'login': 'Login',
'long_press_message': 'Premi a lungo su un messaggio importante e scegli',
'matches_for': 'Risultati per',
'member': 'Membro',
'members': 'Membri',
'mentions': 'Menzioni',
'message': 'Messaggi',
'message_channel_description': 'Canale usato per mostrare i messaggi',
'message_channel_name': 'Invia un messaggio al canale',
'more': 'altro',
'mute_group': 'Silenzia gruppo',
'mute_user': 'Silenzia utente',
'name': 'Nome',
'name_of_group_chat': 'Nome del gruppo',
'new_chat': 'Nuova conversazione',
'new_direct_message': 'Nuovo messaggio diretto',
'new_group': 'Nuovo gruppo',
'no_chats_here_yet': 'Ancora nessun messaggio...',
'no_files': 'Nessun File',
'no_media': 'Nessun Media',
'no_mentions_exist_yet': 'Ancora nessuna menzione...',
'no_pinned_items': 'Nessun messaggio in evidenza',
'no_results': 'Nessun risultato...',
'no_shared_groups': 'Nessun gruppo in comune',
'no_title': 'Nessun titolo',
'no_user_matches_these_keywords': 'Nessun utente per questa ricerca...',
'ok': 'OK',
'online': 'Online',
'on_the_platform': 'Sulla piattaforma',
'operation_could_not_be_completed':
'Non é stato possibile completare l\'operazione.',
'owner': 'Proprietario',
'photos_and_videos': 'Foto & Video',
'photos_or_videos_will_appear_here':
'Foto or video inviati in questa chat \ncompariranno qui',
'pinned_messages': 'Messaggi in evidenza',
'pin_to_conversation': 'Metti in evidenza',
'reconnecting': 'Riconnessione...',
'remove': 'Rimuovi',
'remove_from_group': 'Rimuovi Dal Gruppo',
'remove_member': 'Rimuovi membro',
'remove_member_are_you_sure':
'Sei sicuro di voler rimuovere questo membro?',
'search': 'Cerca',
'select_user_to_try_flutter_sdk':
'Seleziona un utente per provare l\'SDK Flutter',
'shared_groups': 'Gruppi in comune',
'sign_out': 'Sign out',
'something_went_wrong_error_message': 'Qualcosa é andato storto',
'stream_sdk': 'Stream SDK',
'stream_test_account': 'Account di test',
'to': 'A',
'type_a_name_hint': 'Scrivi un nome',
'user_id': 'User ID',
'user_id_error': 'Per favore inserisci l\'ID dell\'utente',
'username_optional': 'Username (opzionale)',
'user_token': 'Token Utente',
'user_token_error': 'Per favore inserisci il token',
'view_info': 'Vedi info',
'welcome_to_stream_chat': 'Benvenuto in Stream Chat',
},
};
final Locale locale;
AppLocalizations(this.locale);
String get addAGroupName {
return _localizedValues[locale.languageCode]!['add_a_group_name']!;
}
String get addGroupMembers {
return _localizedValues[locale.languageCode]!['add_group_members']!;
}
String get advancedOptions {
return _localizedValues[locale.languageCode]!['advanced_options']!;
}
String get apiKeyError {
return _localizedValues[locale.languageCode]!['api_key_error']!;
}
String get attachment {
return _localizedValues[locale.languageCode]!['attachment']!;
}
String get attachments {
return _localizedValues[locale.languageCode]!['attachments']!;
}
String get cancel {
return _localizedValues[locale.languageCode]!['cancel']!;
}
String get chatApiKey {
return _localizedValues[locale.languageCode]!['chat_api_key']!;
}
String get chats {
return _localizedValues[locale.languageCode]!['chats']!;
}
String get chooseAGroupChatName {
return _localizedValues[locale.languageCode]!['choose_a_group_chat_name']!;
}
String get connected {
return _localizedValues[locale.languageCode]!['connected']!;
}
String get createAGroup {
return _localizedValues[locale.languageCode]!['create_a_group']!;
}
String get customSettings {
return _localizedValues[locale.languageCode]!['custom_settings']!;
}
String get delete {
return _localizedValues[locale.languageCode]!['delete']!;
}
String get deleteConversationAreYouSure {
return _localizedValues[locale.languageCode]![
'delete_conversation_are_you_sure']!;
}
String get deleteConversationTitle {
return _localizedValues[locale.languageCode]!['delete_conversation_title']!;
}
String get disconnected {
return _localizedValues[locale.languageCode]!['disconnected']!;
}
String get errorConnecting {
return _localizedValues[locale.languageCode]!['error_connecting']!;
}
String get files {
return _localizedValues[locale.languageCode]!['files']!;
}
String get filesAppearHere {
return _localizedValues[locale.languageCode]!['files_appear_here']!;
}
String get groupSharedWithUserAppearHere {
return _localizedValues[locale.languageCode]![
'group_shared_with_user_appear_here']!;
}
String get lastSeen {
return _localizedValues[locale.languageCode]!['last_seen']!;
}
String get leave {
return _localizedValues[locale.languageCode]!['leave']!;
}
String get leaveConversation {
return _localizedValues[locale.languageCode]!['leave_conversation']!;
}
String get leaveConversationAreYouSure {
return _localizedValues[locale.languageCode]![
'leave_conversation_are_you_sure']!;
}
String get leaveGroup {
return _localizedValues[locale.languageCode]!['leave_group']!;
}
String get loading {
return _localizedValues[locale.languageCode]!['loading']!;
}
String get login {
return _localizedValues[locale.languageCode]!['login']!;
}
String get longPressMessage {
return _localizedValues[locale.languageCode]!['long_press_message']!;
}
String get matchesFor {
return _localizedValues[locale.languageCode]!['matches_for']!;
}
String get member {
return _localizedValues[locale.languageCode]!['member']!;
}
String get members {
return _localizedValues[locale.languageCode]!['members']!;
}
String get mentions {
return _localizedValues[locale.languageCode]!['mentions']!;
}
String get message {
return _localizedValues[locale.languageCode]!['message']!;
}
String get messageChannelDescription {
return _localizedValues[locale.languageCode]![
'message_channel_description']!;
}
String get messageChannelName {
return _localizedValues[locale.languageCode]!['message_channel_name']!;
}
String get more {
return _localizedValues[locale.languageCode]!['more']!;
}
String get muteGroup {
return _localizedValues[locale.languageCode]!['mute_group']!;
}
String get muteUser {
return _localizedValues[locale.languageCode]!['mute_user']!;
}
String get name {
return _localizedValues[locale.languageCode]!['name']!;
}
String get nameOfGroupChat {
return _localizedValues[locale.languageCode]!['name_of_group_chat']!;
}
String get newChat {
return _localizedValues[locale.languageCode]!['new_chat']!;
}
String get newDirectMessage {
return _localizedValues[locale.languageCode]!['new_direct_message']!;
}
String get newGroup {
return _localizedValues[locale.languageCode]!['new_group']!;
}
String get noChatsHereYet {
return _localizedValues[locale.languageCode]!['no_chats_here_yet']!;
}
String get noFiles {
return _localizedValues[locale.languageCode]!['no_files']!;
}
String get noMedia {
return _localizedValues[locale.languageCode]!['no_media']!;
}
String get noMentionsExistYet {
return _localizedValues[locale.languageCode]!['no_mentions_exist_yet']!;
}
String get noPinnedItems {
return _localizedValues[locale.languageCode]!['no_pinned_items']!;
}
String get noResults {
return _localizedValues[locale.languageCode]!['no_results']!;
}
String get noSharedGroups {
return _localizedValues[locale.languageCode]!['no_shared_groups']!;
}
String get noTitle {
return _localizedValues[locale.languageCode]!['no_title']!;
}
String get noUserMatchesTheseKeywords {
return _localizedValues[locale.languageCode]![
'no_user_matches_these_keywords']!;
}
String get ok {
return _localizedValues[locale.languageCode]!['ok']!;
}
String get online {
return _localizedValues[locale.languageCode]!['online']!;
}
String get onThePlatorm {
return _localizedValues[locale.languageCode]!['on_the_platform']!;
}
String get operationCouldNotBeCompleted {
return _localizedValues[locale.languageCode]![
'operation_could_not_be_completed']!;
}
String get owner {
return _localizedValues[locale.languageCode]!['owner']!;
}
String get photosAndVideos {
return _localizedValues[locale.languageCode]!['photos_and_videos']!;
}
String get photosOrVideosWillAppearHere {
return _localizedValues[locale.languageCode]![
'photos_or_videos_will_appear_here']!;
}
String get pinnedMessages {
return _localizedValues[locale.languageCode]!['pinned_messages']!;
}
String get pinToConversation {
return _localizedValues[locale.languageCode]!['pin_to_conversation']!;
}
String get reconnecting {
return _localizedValues[locale.languageCode]!['reconnecting']!;
}
String get remove {
return _localizedValues[locale.languageCode]!['remove']!;
}
String get removeFromGroup {
return _localizedValues[locale.languageCode]!['remove_from_group']!;
}
String get removeMember {
return _localizedValues[locale.languageCode]!['remove_member']!;
}
String get removeMemberAreYouSure {
return _localizedValues[locale.languageCode]![
'remove_member_are_you_sure']!;
}
String get search {
return _localizedValues[locale.languageCode]!['search']!;
}
String get selectUserToTryFlutterSDK {
return _localizedValues[locale.languageCode]![
'select_user_to_try_flutter_sdk']!;
}
String get sharedGroups {
return _localizedValues[locale.languageCode]!['shared_groups']!;
}
String get signOut {
return _localizedValues[locale.languageCode]!['sign_out']!;
}
String get somethingWentWrongErrorMessage {
return _localizedValues[locale.languageCode]![
'something_went_wrong_error_message']!;
}
String get streamSDK {
return _localizedValues[locale.languageCode]!['stream_sdk']!;
}
String get streamTestAccount {
return _localizedValues[locale.languageCode]!['stream_test_account']!;
}
String get to {
return _localizedValues[locale.languageCode]!['to']!;
}
String get typeANameHint {
return _localizedValues[locale.languageCode]!['type_a_name_hint']!;
}
String get userId {
return _localizedValues[locale.languageCode]!['user_id']!;
}
String get userIdError {
return _localizedValues[locale.languageCode]!['user_id_error']!;
}
String get usernameOptional {
return _localizedValues[locale.languageCode]!['username_optional']!;
}
String get userToken {
return _localizedValues[locale.languageCode]!['user_token']!;
}
String get userTokenError {
return _localizedValues[locale.languageCode]!['user_token_error']!;
}
String get viewInfo {
return _localizedValues[locale.languageCode]!['view_info']!;
}
String get welcomeToStreamChat {
return _localizedValues[locale.languageCode]!['welcome_to_stream_chat']!;
}
static List<String> languages() => _localizedValues.keys.toList();
static AppLocalizations of(BuildContext context) {
return Localizations.of<AppLocalizations>(context, AppLocalizations)!;
}
}
class AppLocalizationsDelegate extends LocalizationsDelegate<AppLocalizations> {
const AppLocalizationsDelegate();
@override
bool isSupported(Locale locale) =>
AppLocalizations.languages().contains(locale.languageCode);
@override
Future<AppLocalizations> load(Locale locale) {
return SynchronousFuture<AppLocalizations>(AppLocalizations(locale));
}
@override
bool shouldReload(AppLocalizationsDelegate old) => false;
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty | mirrored_repositories/flutter-samples/packages/chatty/lib/navigator_utils.dart | import 'package:flutter/material.dart';
Future pushToPage(BuildContext context, Widget widget) async {
await Navigator.of(context).push(
MaterialPageRoute(
builder: (_) => widget,
),
);
}
Future pushAndReplaceToPage(BuildContext context, Widget widget) async {
await Navigator.of(context).pushReplacement(
MaterialPageRoute(
builder: (_) => widget,
),
);
}
Future popAllAndPush(BuildContext context, Widget widget) async {
await Navigator.pushAndRemoveUntil(
context,
MaterialPageRoute(builder: (BuildContext context) => widget),
ModalRoute.withName('/'));
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty | mirrored_repositories/flutter-samples/packages/chatty/lib/dependencies.dart | import 'package:stream_chatter/data/auth_repository.dart';
import 'package:stream_chatter/data/image_picker_repository.dart';
import 'package:stream_chatter/data/local/image_picker_impl.dart';
import 'package:stream_chatter/data/persistent_storage_repository.dart';
import 'package:stream_chatter/data/prod/auth_impl.dart';
import 'package:stream_chatter/data/prod/persistent_storage_impl.dart';
import 'package:stream_chatter/data/prod/stream_api_impl.dart';
import 'package:stream_chatter/data/prod/upload_storage_impl.dart';
import 'package:stream_chatter/data/stream_api_repository.dart';
import 'package:stream_chatter/data/upload_storage_repository.dart';
import 'package:stream_chatter/domain/usecases/create_group_usecase.dart';
import 'package:stream_chatter/domain/usecases/login_usecase.dart';
import 'package:stream_chatter/domain/usecases/logout_usecase.dart';
import 'package:stream_chatter/domain/usecases/profile_sign_in_usecase.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:stream_chat_flutter/stream_chat_flutter.dart';
List<RepositoryProvider> buildRepositories(StreamChatClient client) {
//TODO: Here you can use your local implementations of your repositories
return [
RepositoryProvider<StreamApiRepository>(
create: (_) => StreamApiImpl(client)),
RepositoryProvider<PersistentStorageRepository>(
create: (_) => PersistentStorageImpl()),
RepositoryProvider<AuthRepository>(create: (_) => AuthImpl()),
RepositoryProvider<UploadStorageRepository>(
create: (_) => UploadStorageImpl()),
RepositoryProvider<ImagePickerRepository>(create: (_) => ImagePickerImpl()),
RepositoryProvider<ProfileSignInUseCase>(
create: (context) => ProfileSignInUseCase(
context.read(),
context.read(),
context.read(),
),
),
RepositoryProvider<CreateGroupUseCase>(
create: (context) => CreateGroupUseCase(
context.read(),
context.read(),
),
),
RepositoryProvider<LogoutUseCase>(
create: (context) => LogoutUseCase(
context.read(),
context.read(),
),
),
RepositoryProvider<LoginUseCase>(
create: (context) => LoginUseCase(
context.read(),
context.read(),
),
),
];
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty | mirrored_repositories/flutter-samples/packages/chatty/lib/main.dart | import 'package:firebase_core/firebase_core.dart';
import 'package:stream_chatter/dependencies.dart';
import 'package:stream_chatter/ui/app_theme_cubit.dart';
import 'package:stream_chatter/ui/splash/splash_view.dart';
import 'package:stream_chatter/ui/themes.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:stream_chat_flutter/stream_chat_flutter.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
final _streamChatClient = StreamChatClient('c2rynysx9x6b');
@override
Widget build(BuildContext context) {
SystemChrome.setEnabledSystemUIMode(
SystemUiMode.manual,
overlays: [SystemUiOverlay.bottom],
);
return MultiRepositoryProvider(
providers: buildRepositories(_streamChatClient),
child: BlocProvider(
create: (context) => AppThemeCubit(context.read())..init(),
child: BlocBuilder<AppThemeCubit, bool>(builder: (context, snapshot) {
return MaterialApp(
title: 'Stream Chatty',
home: SplashView(),
theme: snapshot ? Themes.themeDark : Themes.themeLight,
builder: (context, child) {
return StreamChat(
child: child,
client: _streamChatClient,
streamChatThemeData:
StreamChatThemeData.fromTheme(Theme.of(context)).copyWith(
ownMessageTheme: MessageThemeData(
messageBackgroundColor:
Theme.of(context).colorScheme.secondary,
messageTextStyle: TextStyle(color: Colors.white),
),
),
);
},
);
}),
),
);
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib | mirrored_repositories/flutter-samples/packages/chatty/lib/data/stream_api_repository.dart | import 'package:stream_chatter/domain/models/chat_user.dart';
import 'package:stream_chat_flutter/stream_chat_flutter.dart';
abstract class StreamApiRepository {
Future<List<ChatUser>> getChatUsers();
Future<String> getToken(String userId);
Future<bool> connectIfExist(String userId);
Future<ChatUser> connectUser(ChatUser user, String token);
Future<Channel> createGroupChat(
String channelId,
String? name,
List<String?>? members, {
String? image,
});
Future<Channel> createSimpleChat(String? friendId);
Future<void> logout();
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib | mirrored_repositories/flutter-samples/packages/chatty/lib/data/upload_storage_repository.dart | import 'dart:io';
abstract class UploadStorageRepository {
Future<String> uploadPhoto(File? file, String path);
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib | mirrored_repositories/flutter-samples/packages/chatty/lib/data/persistent_storage_repository.dart | abstract class PersistentStorageRepository {
Future<bool> isDarkMode();
Future<void> updateDarkMode(bool isDarkMode);
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib | mirrored_repositories/flutter-samples/packages/chatty/lib/data/image_picker_repository.dart | import 'dart:io';
abstract class ImagePickerRepository {
Future<File?> pickImage();
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib | mirrored_repositories/flutter-samples/packages/chatty/lib/data/auth_repository.dart | import 'package:stream_chatter/domain/models/auth_user.dart';
abstract class AuthRepository {
Future<AuthUser?> getAuthUser();
Future<AuthUser> signIn();
Future<void> logout();
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib/data | mirrored_repositories/flutter-samples/packages/chatty/lib/data/local/stream_api_local_impl.dart | import 'package:stream_chatter/data/stream_api_repository.dart';
import 'package:stream_chatter/domain/models/chat_user.dart';
import 'package:stream_chat_flutter/stream_chat_flutter.dart';
class StreamApiLocalImpl extends StreamApiRepository {
StreamApiLocalImpl(this._client);
final StreamChatClient _client;
@override
Future<ChatUser> connectUser(ChatUser user, String token) async {
Map<String, dynamic> extraData = {};
if (user.image != null) {
extraData['image'] = user.image;
}
if (user.name != null) {
extraData['name'] = user.name;
}
await _client.disconnectUser();
await _client.connectUser(
User(id: user.id!, extraData: extraData as Map<String, Object>),
token,
);
return user;
}
@override
Future<List<ChatUser>> getChatUsers() async {
final result = await _client.queryUsers();
final chatUsers = result.users
.where((element) => element.id != _client.state.currentUser!.id)
.map(
(e) => ChatUser(
id: e.id,
name: e.name,
image: e.extraData['image'] as String?,
),
)
.toList();
return chatUsers;
}
@override
Future<String> getToken(String userId) async {
return _client.devToken(userId).rawValue;
}
@override
Future<Channel> createGroupChat(
String channelId, String? name, List<String?>? members,
{String? image}) async {
final channel = _client.channel('messaging', id: channelId, extraData: {
'name': name!,
'image': image!,
'members': [_client.state.currentUser!.id, ...members!],
});
await channel.watch();
return channel;
}
@override
Future<Channel> createSimpleChat(String? friendId) async {
final channel = _client.channel('messaging',
id: '${_client.state.currentUser!.id.hashCode}${friendId.hashCode}',
extraData: {
'members': [
friendId,
_client.state.currentUser!.id,
],
});
await channel.watch();
return channel;
}
@override
Future<void> logout() {
return _client.disconnectUser();
}
@override
Future<bool> connectIfExist(String userId) async {
final token = await getToken(userId);
await _client.connectUser(
User(id: userId),
token,
);
return _client.state.currentUser!.name != userId;
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib/data | mirrored_repositories/flutter-samples/packages/chatty/lib/data/local/image_picker_impl.dart | import 'dart:io';
import 'package:image_picker/image_picker.dart';
import 'package:stream_chatter/data/image_picker_repository.dart';
class ImagePickerImpl extends ImagePickerRepository {
@override
Future<File?> pickImage() async {
final picker = ImagePicker();
final pickedFile = await picker.pickImage(
source: ImageSource.gallery,
maxWidth: 400,
);
if (pickedFile == null) {
return null;
}
return File(pickedFile.path);
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib/data | mirrored_repositories/flutter-samples/packages/chatty/lib/data/local/upload_storage_local_impl.dart | import 'dart:io';
import 'package:stream_chatter/data/upload_storage_repository.dart';
class UploadStorageLocalImpl extends UploadStorageRepository {
@override
Future<String> uploadPhoto(File? file, String path) async {
return 'https://lh3.googleusercontent.com/a-/AOh14GjhqGZ-V7tNXS1pOIp9vbBij4OS9JbzxXgxgy1t=s600-k-no-rp-mo';
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib/data | mirrored_repositories/flutter-samples/packages/chatty/lib/data/local/auth_local_impl.dart | import 'package:stream_chatter/data/auth_repository.dart';
import 'package:stream_chatter/domain/models/auth_user.dart';
class AuthLocalImpl extends AuthRepository {
@override
Future<AuthUser> getAuthUser() async {
await Future.delayed(const Duration(seconds: 2));
return AuthUser('diego');
}
@override
Future<AuthUser> signIn() async {
await Future.delayed(const Duration(seconds: 2));
return AuthUser('diego');
}
@override
Future<void> logout() async {
return;
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib/data | mirrored_repositories/flutter-samples/packages/chatty/lib/data/local/persistent_storage_local_impl.dart | import 'package:stream_chatter/data/persistent_storage_repository.dart';
class PersistentStorageLocalImpl extends PersistentStorageRepository {
@override
Future<bool> isDarkMode() async {
await Future.delayed(const Duration(milliseconds: 50));
return false;
}
@override
Future<void> updateDarkMode(bool isDarkMode) async {
await Future.delayed(const Duration(milliseconds: 50));
return;
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib/data | mirrored_repositories/flutter-samples/packages/chatty/lib/data/prod/stream_api_impl.dart | import 'dart:convert';
import 'package:stream_chatter/data/stream_api_repository.dart';
import 'package:stream_chatter/domain/models/chat_user.dart';
import 'package:stream_chat_flutter/stream_chat_flutter.dart';
import 'package:http/http.dart' as http;
class StreamApiImpl extends StreamApiRepository {
StreamApiImpl(this._client);
final StreamChatClient _client;
@override
Future<ChatUser> connectUser(ChatUser user, String token) async {
Map<String, dynamic> extraData = {};
if (user.image != null) {
extraData['image'] = user.image;
}
if (user.name != null) {
extraData['name'] = user.name;
}
await _client.disconnectUser();
await _client.connectUser(
User(id: user.id!, extraData: extraData as Map<String, Object>),
token,
);
return user;
}
@override
Future<List<ChatUser>> getChatUsers() async {
final result = await _client.queryUsers();
final chatUsers = result.users
.where((element) => element.id != _client.state.currentUser!.id)
.map(
(e) => ChatUser(
id: e.id,
name: e.name,
image: e.extraData['image'] as String?,
),
)
.toList();
return chatUsers;
}
@override
Future<String> getToken(String userId) async {
//TODO: use your own implementation in Production
final response = await http.post(
Uri.parse('your_backend_url'),
body: jsonEncode(<String, String>{'id': userId}),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
);
final token = jsonDecode(response.body)['token'];
//In Development mode you can just use :
// _client.devToken(userId);
return token;
}
@override
Future<Channel> createGroupChat(
String id, String? name, List<String?>? members,
{String? image}) async {
final channel = _client.channel('messaging', id: id, extraData: {
'name': name!,
'image': image!,
'members': [_client.state.currentUser!.id, ...members!],
});
await channel.watch();
return channel;
}
@override
Future<Channel> createSimpleChat(String? friendId) async {
final channel = _client.channel('messaging',
id: '${_client.state.currentUser!.id.hashCode}${friendId.hashCode}',
extraData: {
'members': [
friendId,
_client.state.currentUser!.id,
],
});
await channel.watch();
return channel;
}
@override
Future<void> logout() async {
return _client.disconnectUser();
}
@override
Future<bool> connectIfExist(String userId) async {
final token = await getToken(userId);
await _client.connectUser(
User(id: userId),
token,
);
return _client.state.currentUser!.name != userId;
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib/data | mirrored_repositories/flutter-samples/packages/chatty/lib/data/prod/persistent_storage_impl.dart | import 'package:stream_chatter/data/persistent_storage_repository.dart';
import 'package:shared_preferences/shared_preferences.dart';
const _isDarkMode = 'isDarkMode';
class PersistentStorageImpl extends PersistentStorageRepository {
@override
Future<bool> isDarkMode() async {
final preference = await SharedPreferences.getInstance();
return preference.getBool(_isDarkMode) ?? false;
}
@override
Future<void> updateDarkMode(bool isDarkMode) async {
final preference = await SharedPreferences.getInstance();
await preference.setBool(_isDarkMode, isDarkMode);
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib/data | mirrored_repositories/flutter-samples/packages/chatty/lib/data/prod/auth_impl.dart | import 'package:firebase_auth/firebase_auth.dart';
import 'package:stream_chatter/data/auth_repository.dart';
import 'package:stream_chatter/domain/models/auth_user.dart';
import 'package:google_sign_in/google_sign_in.dart';
class AuthImpl extends AuthRepository {
FirebaseAuth _auth = FirebaseAuth.instance;
@override
Future<AuthUser?> getAuthUser() async {
final user = _auth.currentUser;
if (user != null) {
return AuthUser(user.uid);
}
return null;
}
@override
Future<AuthUser> signIn() async {
try {
UserCredential userCredential;
final GoogleSignInAccount? googleUser = await GoogleSignIn().signIn();
if (googleUser == null) {
throw Exception('login error');
}
final GoogleSignInAuthentication googleAuth =
await googleUser.authentication;
final GoogleAuthCredential googleAuthCredential =
GoogleAuthProvider.credential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
) as GoogleAuthCredential;
userCredential = await _auth.signInWithCredential(googleAuthCredential);
final user = userCredential.user!;
return AuthUser(user.uid);
} catch (e) {
print(e);
throw Exception('login error');
}
}
@override
Future<void> logout() async {
return _auth.signOut();
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib/data | mirrored_repositories/flutter-samples/packages/chatty/lib/data/prod/upload_storage_impl.dart | import 'dart:io';
import 'package:firebase_storage/firebase_storage.dart' as firebase_storage;
import 'package:stream_chatter/data/upload_storage_repository.dart';
class UploadStorageImpl extends UploadStorageRepository {
@override
Future<String> uploadPhoto(File? file, String path) async {
final ref = firebase_storage.FirebaseStorage.instance.ref(path);
final uploadTask = ref.putFile(file!);
await uploadTask;
return await ref.getDownloadURL();
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib/domain | mirrored_repositories/flutter-samples/packages/chatty/lib/domain/models/auth_user.dart | class AuthUser {
AuthUser(this.id);
final String id;
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib/domain | mirrored_repositories/flutter-samples/packages/chatty/lib/domain/models/chat_user.dart | class ChatUser {
const ChatUser({this.name, this.image, this.id});
final String? name;
final String? image;
final String? id;
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib/domain | mirrored_repositories/flutter-samples/packages/chatty/lib/domain/exceptions/auth_exception.dart | enum AuthErrorCode {
not_auth,
not_chat_user,
}
class AuthException implements Exception {
AuthException(this.error);
final AuthErrorCode error;
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib/domain | mirrored_repositories/flutter-samples/packages/chatty/lib/domain/usecases/create_group_usecase.dart | import 'dart:io';
import 'package:stream_chatter/data/stream_api_repository.dart';
import 'package:stream_chatter/data/upload_storage_repository.dart';
import 'package:stream_chat_flutter/stream_chat_flutter.dart';
import 'package:uuid/uuid.dart';
class CreateGroupInput {
CreateGroupInput({this.imageFile, this.name, this.members});
final File? imageFile;
final String? name;
final List<String?>? members;
}
class CreateGroupUseCase {
CreateGroupUseCase(
this._streamApiRepository,
this._uploadStorageRepository,
);
final UploadStorageRepository _uploadStorageRepository;
final StreamApiRepository _streamApiRepository;
Future<Channel> createGroup(CreateGroupInput input) async {
final channelId = Uuid().v4();
String? image;
if (input.imageFile != null) {
image = await _uploadStorageRepository.uploadPhoto(
input.imageFile, 'channels/$channelId');
}
final channel = await _streamApiRepository.createGroupChat(
channelId,
input.name,
input.members,
image: image,
);
return channel;
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib/domain | mirrored_repositories/flutter-samples/packages/chatty/lib/domain/usecases/profile_sign_in_usecase.dart | import 'dart:io';
import 'package:stream_chatter/data/auth_repository.dart';
import 'package:stream_chatter/data/stream_api_repository.dart';
import 'package:stream_chatter/data/upload_storage_repository.dart';
import 'package:stream_chatter/domain/models/chat_user.dart';
import '../exceptions/auth_exception.dart';
class ProfileInput {
ProfileInput({this.imageFile, this.name});
final File? imageFile;
final String? name;
}
class ProfileSignInUseCase {
ProfileSignInUseCase(
this._authRepository,
this._streamApiRepository,
this._uploadStorageRepository,
);
final AuthRepository _authRepository;
final UploadStorageRepository _uploadStorageRepository;
final StreamApiRepository _streamApiRepository;
Future<void> verify(ProfileInput input) async {
final auth = await _authRepository.getAuthUser();
if (auth == null) {
throw AuthException(AuthErrorCode.not_auth);
}
final token = await _streamApiRepository.getToken(auth.id);
String? image;
if (input.imageFile != null) {
image = await _uploadStorageRepository.uploadPhoto(
input.imageFile, 'users/${auth.id}');
}
await _streamApiRepository.connectUser(
ChatUser(
name: input.name,
id: auth.id,
image: image,
),
token,
);
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib/domain | mirrored_repositories/flutter-samples/packages/chatty/lib/domain/usecases/logout_usecase.dart | import 'package:stream_chatter/data/auth_repository.dart';
import 'package:stream_chatter/data/stream_api_repository.dart';
class LogoutUseCase {
LogoutUseCase(this.streamApiRepository, this.authRepository);
final StreamApiRepository streamApiRepository;
final AuthRepository authRepository;
Future<void> logout() async {
await streamApiRepository.logout();
await authRepository.logout();
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib/domain | mirrored_repositories/flutter-samples/packages/chatty/lib/domain/usecases/login_usecase.dart | import 'package:stream_chatter/data/auth_repository.dart';
import 'package:stream_chatter/data/stream_api_repository.dart';
import 'package:stream_chatter/domain/exceptions/auth_exception.dart';
import 'package:stream_chatter/domain/models/auth_user.dart';
class LoginUseCase {
LoginUseCase(this.authRepository, this.streamApiRepository);
final AuthRepository authRepository;
final StreamApiRepository streamApiRepository;
Future<bool> validateLogin() async {
print('validateLogin');
final user = await authRepository.getAuthUser();
print('user: ${user?.id}');
if (user != null) {
final result = await streamApiRepository.connectIfExist(user.id);
if (result) {
return true;
} else {
throw AuthException(AuthErrorCode.not_chat_user);
}
}
throw AuthException(AuthErrorCode.not_auth);
}
Future<AuthUser> signIn() async {
return await authRepository.signIn();
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib | mirrored_repositories/flutter-samples/packages/chatty/lib/ui/app_theme_cubit.dart | import 'package:stream_chatter/data/persistent_storage_repository.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class AppThemeCubit extends Cubit<bool> {
AppThemeCubit(this._persistentStorageRepository) : super(false);
final PersistentStorageRepository _persistentStorageRepository;
bool _isDark = false;
bool get isDark => _isDark;
Future<void> init() async {
_isDark = await _persistentStorageRepository.isDarkMode();
emit(_isDark);
}
Future<void> updateTheme(bool isDarkMode) async {
_isDark = isDarkMode;
await _persistentStorageRepository.updateDarkMode(isDarkMode);
emit(_isDark);
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib | mirrored_repositories/flutter-samples/packages/chatty/lib/ui/themes.dart | import 'package:flutter/material.dart';
const primaryColor = Color(0xFF3883FB);
const backgroundLightColor = Color(0xFFFCFCFC);
const backgroundDarkColor = Color(0xFF1F2026);
const navigationBarLightColor = Colors.white;
const navigationBarDarkColor = Color(0xFF30313C);
class Themes {
static final themeLight = ThemeData.light().copyWith(
backgroundColor: backgroundLightColor,
// selected color
colorScheme:
ThemeData.light().colorScheme.copyWith(secondary: primaryColor),
// floating action button
floatingActionButtonTheme: FloatingActionButtonThemeData(
backgroundColor: primaryColor,
foregroundColor: Colors.white,
),
// bottom bar
bottomNavigationBarTheme: BottomNavigationBarThemeData(
backgroundColor: navigationBarLightColor,
selectedItemColor: primaryColor,
unselectedItemColor: Colors.grey[200],
),
// switch active color
toggleableActiveColor: primaryColor,
canvasColor: backgroundLightColor,
appBarTheme: AppBarTheme(
color: Colors.black,
));
static final themeDark = ThemeData.dark().copyWith(
backgroundColor: backgroundDarkColor,
// selected color
colorScheme:
ThemeData.dark().colorScheme.copyWith(secondary: primaryColor),
// floating action button
floatingActionButtonTheme: FloatingActionButtonThemeData(
backgroundColor: primaryColor,
foregroundColor: Colors.white,
),
// bottom bar
bottomNavigationBarTheme: BottomNavigationBarThemeData(
backgroundColor: navigationBarDarkColor,
selectedItemColor: primaryColor,
unselectedItemColor: Colors.grey[300],
),
textSelectionTheme: TextSelectionThemeData(selectionColor: Colors.white),
// switch active color
toggleableActiveColor: primaryColor,
canvasColor: backgroundDarkColor,
appBarTheme: AppBarTheme(
color: Colors.white,
));
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib/ui | mirrored_repositories/flutter-samples/packages/chatty/lib/ui/sign_in/sign_in_view.dart | import 'package:stream_chatter/navigator_utils.dart';
import 'package:stream_chatter/ui/home/home_view.dart';
import 'package:stream_chatter/ui/profile_verify/profile_verify_view.dart';
import 'package:stream_chatter/ui/sign_in/sign_in_cubit.dart';
import 'package:stream_chatter/ui/common/initial_background_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class SignInView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => SignInCubit(context.read()),
child:
BlocConsumer<SignInCubit, SignInState>(listener: (context, snapshot) {
if (snapshot == SignInState.none) {
pushAndReplaceToPage(context, ProfileVerifyView());
} else {
pushAndReplaceToPage(context, HomeView());
}
}, builder: (context, snapshot) {
return Scaffold(
backgroundColor: Theme.of(context).canvasColor,
body: Stack(children: [
InitialBackgroundView(),
Padding(
padding: const EdgeInsets.only(left: 25.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(height: 150),
Hero(
tag: 'logo_hero',
child: Image.asset(
'assets/logo.png',
height: 50,
),
),
const SizedBox(height: 30),
Text(
'Welcome to\nChatty',
style: TextStyle(
fontSize: 30,
fontWeight: FontWeight.w900,
),
),
Padding(
padding: const EdgeInsets.only(top: 8.0, bottom: 40),
child: Text(
'A platform to chat with users very easily and friendly',
style: TextStyle(
fontWeight: FontWeight.w600,
color: Colors.grey,
),
),
),
Material(
elevation: 2,
shadowColor: Colors.black45,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
color: Theme.of(context)
.bottomNavigationBarTheme
.backgroundColor,
child: InkWell(
onTap: () {
context.read<SignInCubit>().signIn();
},
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset('assets/icon-google.png', height: 20),
const SizedBox(width: 15),
Text('Login with Google'),
],
),
),
),
),
Spacer(),
Align(
alignment: Alignment.bottomLeft,
child: Text(
'"in the modern world the\nquality of life is the quality\nof communication',
style: TextStyle(
fontWeight: FontWeight.w400,
color: Colors.grey,
),
),
),
const SizedBox(height: 20),
],
),
),
]),
);
}),
);
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib/ui | mirrored_repositories/flutter-samples/packages/chatty/lib/ui/sign_in/sign_in_cubit.dart | import 'package:stream_chatter/domain/usecases/login_usecase.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
enum SignInState {
none,
existing_user,
}
class SignInCubit extends Cubit<SignInState> {
SignInCubit(
this._loginUseCase,
) : super(SignInState.none);
final LoginUseCase _loginUseCase;
void signIn() async {
try {
final result = await _loginUseCase.validateLogin();
if (result) {
emit(SignInState.existing_user);
}
} catch (ex) {
_loginUseCase.signIn();
emit(SignInState.none);
}
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib/ui | mirrored_repositories/flutter-samples/packages/chatty/lib/ui/profile_verify/profile_verify_view.dart | import 'package:stream_chatter/navigator_utils.dart';
import 'package:stream_chatter/ui/common/avatar_image_view.dart';
import 'package:stream_chatter/ui/common/loading_view.dart';
import 'package:stream_chatter/ui/home/home_view.dart';
import 'package:stream_chatter/ui/profile_verify/profile_verify_cubit.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class ProfileVerifyView extends StatelessWidget {
ProfileVerifyView();
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => ProfileVerifyCubit(context.read(), context.read()),
child: BlocConsumer<ProfileVerifyCubit, ProfileState>(
listener: (context, snapshot) {
if (snapshot.success) {
pushAndReplaceToPage(context, HomeView());
}
}, builder: (context, snapshot) {
//refresh the photo
return LoadingView(
isLoading: snapshot.loading,
child: Scaffold(
backgroundColor: Theme.of(context).canvasColor,
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Verify your identity',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.w800,
),
),
AvatarImageView(
onTap: context.read<ProfileVerifyCubit>().pickImage,
child: snapshot.file != null
? Image.file(
snapshot.file!,
fit: BoxFit.cover,
)
: Icon(
Icons.person_outline,
size: 100,
color: Colors.grey[400],
),
),
Text(
'Your name',
style: TextStyle(
fontWeight: FontWeight.w700,
),
),
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 50.0,
vertical: 20,
),
child: TextField(
controller:
context.read<ProfileVerifyCubit>().nameController,
decoration: InputDecoration(
fillColor: Theme.of(context)
.bottomNavigationBarTheme
.backgroundColor,
hintText: 'Or just how people now you',
hintStyle: TextStyle(
fontSize: 13,
color: Colors.grey[400],
),
border: InputBorder.none,
enabledBorder: InputBorder.none,
),
),
),
Hero(
tag: 'home_hero',
child: Material(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
color: Theme.of(context).colorScheme.secondary,
child: InkWell(
onTap: () {
context.read<ProfileVerifyCubit>().startChatting();
},
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 40.0,
vertical: 15,
),
child: Text(
'Start chatting now',
style: TextStyle(
color: Colors.white,
),
),
)),
),
),
],
),
),
),
);
}),
);
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib/ui | mirrored_repositories/flutter-samples/packages/chatty/lib/ui/profile_verify/profile_verify_cubit.dart | import 'dart:io';
import 'package:stream_chatter/data/image_picker_repository.dart';
import 'package:stream_chatter/domain/usecases/profile_sign_in_usecase.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class ProfileState {
const ProfileState(
this.file, {
this.success = false,
this.loading = false,
});
final File? file;
final bool success;
final bool loading;
}
class ProfileVerifyCubit extends Cubit<ProfileState> {
ProfileVerifyCubit(
this._imagePickerRepository,
this._profileSignInUseCase,
) : super(ProfileState(null));
final nameController = TextEditingController();
final ImagePickerRepository _imagePickerRepository;
final ProfileSignInUseCase _profileSignInUseCase;
void startChatting() async {
final file = state.file;
emit(ProfileState(file, loading: true));
final name = nameController.text;
await _profileSignInUseCase.verify(ProfileInput(
imageFile: file,
name: name,
));
emit(ProfileState(file, success: true, loading: false));
}
void pickImage() async {
final file = await _imagePickerRepository.pickImage();
emit(ProfileState(file));
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib/ui | mirrored_repositories/flutter-samples/packages/chatty/lib/ui/common/my_channel_preview.dart | import 'package:collection/collection.dart' show IterableExtension;
import 'package:flutter/material.dart';
import 'package:stream_chat_flutter/stream_chat_flutter.dart';
/*Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return StreamChannel(
child: widget.channelWidget,
channel: client,
);
},
),
);
*/
/// 
/// 
///
/// It shows the current [Channel] preview.
///
/// The widget uses a [StreamBuilder] to render the channel information image as soon as it updates.
///
/// Usually you don't use this widget as it's the default channel preview used by [ChannelListView].
///
/// The widget renders the ui based on the first ancestor of type [StreamChatTheme].
/// Modify it to change the widget appearance.
class MyChannelPreview extends StatelessWidget {
/// Function called when tapping this widget
final void Function(Channel)? onTap;
/// Function called when long pressing this widget
final void Function(Channel)? onLongPress;
/// Channel displayed
final Channel channel;
/// The function called when the image is tapped
final VoidCallback? onImageTap;
final String? heroTag;
MyChannelPreview({
required this.channel,
Key? key,
this.onTap,
this.onLongPress,
this.onImageTap,
this.heroTag,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return StreamBuilder<bool>(
stream: channel.isMutedStream,
initialData: channel.isMuted,
builder: (context, snapshot) {
return Opacity(
opacity: snapshot.data! ? 0.5 : 1,
child: ListTile(
contentPadding: const EdgeInsets.symmetric(
horizontal: 8,
),
onTap: () {
if (onTap != null) {
onTap!(channel);
}
},
onLongPress: () {
if (onLongPress != null) {
onLongPress!(channel);
}
},
leading: Material(
child: Hero(
tag: heroTag!,
child: StreamChannel(
channel: channel,
child: ChannelAvatar(
onTap: onImageTap,
),
),
),
),
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Flexible(
child: ChannelName(
textStyle: StreamChatTheme.of(context)
.channelPreviewTheme
.titleStyle,
),
),
StreamBuilder<List<Member>>(
stream: channel.state!.membersStream,
initialData: channel.state!.members,
builder: (context, snapshot) {
if (!snapshot.hasData ||
snapshot.data!.isEmpty ||
!snapshot.data!.any((Member e) =>
e.user!.id ==
channel.client.state.currentUser!.id)) {
return SizedBox();
}
return ChannelUnreadIndicator(
channel: channel,
);
}),
],
),
subtitle: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Flexible(child: _buildSubtitle(context)),
Builder(
builder: (context) {
final lastMessage =
channel.state!.messages.lastWhereOrNull(
(m) => !m.isDeleted && m.shadowed != true,
);
if (lastMessage?.user?.id ==
StreamChat.of(context).currentUser!.id) {
return Padding(
padding: const EdgeInsets.only(right: 4.0),
child: SendingIndicator(
message: lastMessage!,
size: StreamChatTheme.of(context)
.channelPreviewTheme
.indicatorIconSize,
isMessageRead: channel.state!.read
.where((element) =>
element.user.id !=
channel.client.state.currentUser!.id)
.where((element) => element.lastRead
.isAfter(lastMessage.createdAt))
.isNotEmpty ==
true,
),
);
}
return SizedBox();
},
),
_buildDate(context),
],
),
),
);
});
}
Widget _buildDate(BuildContext context) {
return StreamBuilder<DateTime?>(
stream: channel.lastMessageAtStream,
initialData: channel.lastMessageAt,
builder: (context, snapshot) {
if (!snapshot.hasData) {
return SizedBox();
}
final lastMessageAt = snapshot.data!.toLocal();
String stringDate;
final now = DateTime.now();
final startOfDay = DateTime(now.year, now.month, now.day);
if (lastMessageAt.millisecondsSinceEpoch >=
startOfDay.millisecondsSinceEpoch) {
stringDate = Jiffy(lastMessageAt.toLocal()).format('HH:mm');
} else if (lastMessageAt.millisecondsSinceEpoch >=
startOfDay.subtract(Duration(days: 1)).millisecondsSinceEpoch) {
stringDate = 'Yesterday';
} else if (startOfDay.difference(lastMessageAt).inDays < 7) {
stringDate = Jiffy(lastMessageAt.toLocal()).EEEE;
} else {
stringDate = Jiffy(lastMessageAt.toLocal()).format('dd/MM/yyyy');
}
return Text(
stringDate,
style: StreamChatTheme.of(context)
.channelPreviewTheme
.lastMessageAtStyle,
);
},
);
}
Widget _buildSubtitle(BuildContext context) {
if (channel.isMuted) {
return Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: <Widget>[
StreamSvgIcon.mute(
size: 16,
),
Text(
' Channel is muted',
style: StreamChatTheme.of(context)
.channelPreviewTheme
.subtitleStyle!
.copyWith(
color: StreamChatTheme.of(context)
.channelPreviewTheme
.subtitleStyle!
.color,
),
),
],
);
}
return TypingIndicator(
channel: channel,
alternativeWidget: _buildLastMessage(context),
style: StreamChatTheme.of(context)
.channelPreviewTheme
.subtitleStyle!
.copyWith(
color: StreamChatTheme.of(context)
.channelPreviewTheme
.subtitleStyle!
.color,
),
);
}
Widget _buildLastMessage(BuildContext context) {
return StreamBuilder<List<Message>?>(
stream: channel.state!.messagesStream,
initialData: channel.state!.messages,
builder: (context, snapshot) {
final lastMessage = snapshot.data
?.lastWhereOrNull((m) => m.shadowed != true && !m.isDeleted);
if (lastMessage == null) {
return SizedBox();
}
var text = lastMessage.text;
final parts = <String>[
...lastMessage.attachments.map((e) {
if (e.type == 'image') {
return '📷';
} else if (e.type == 'video') {
return '🎬';
} else if (e.type == 'giphy') {
return '[GIF]';
}
return e == lastMessage.attachments.last
? (e.title ?? 'File')
: '${e.title ?? 'File'} , ';
}),
lastMessage.text ?? '',
];
text = parts.join(' ');
return Text.rich(
_getDisplayText(
text,
lastMessage.mentionedUsers,
lastMessage.attachments,
StreamChatTheme.of(context)
.channelPreviewTheme
.subtitleStyle!
.copyWith(
color:
StreamChatTheme.of(context)
.channelPreviewTheme
.subtitleStyle!
.color,
fontStyle: (lastMessage.isSystem || lastMessage.isDeleted)
? FontStyle.italic
: FontStyle.normal),
StreamChatTheme.of(context)
.channelPreviewTheme
.subtitleStyle!
.copyWith(
color:
StreamChatTheme.of(context)
.channelPreviewTheme
.subtitleStyle!
.color,
fontStyle: (lastMessage.isSystem || lastMessage.isDeleted)
? FontStyle.italic
: FontStyle.normal,
fontWeight: FontWeight.bold),
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
);
},
);
}
TextSpan _getDisplayText(
String text,
List<User> mentions,
List<Attachment> attachments,
TextStyle normalTextStyle,
TextStyle mentionsTextStyle) {
final textList = text.split(' ');
final resList = <TextSpan>[];
for (final e in textList) {
if (mentions.isNotEmpty &&
mentions.any((element) => '@${element.name}' == e)) {
resList.add(TextSpan(
text: '$e ',
style: mentionsTextStyle,
));
} else if (attachments.isNotEmpty &&
attachments
.where((e) => e.title != null)
.any((element) => element.title == e)) {
resList.add(TextSpan(
text: '$e ',
style: normalTextStyle.copyWith(fontStyle: FontStyle.italic),
));
} else {
resList.add(TextSpan(
text: e == textList.last ? '$e' : '$e ',
style: normalTextStyle,
));
}
}
return TextSpan(children: resList);
}
}
class ChannelUnreadIndicator extends StatelessWidget {
const ChannelUnreadIndicator({
Key? key,
required this.channel,
}) : super(key: key);
final Channel channel;
@override
Widget build(BuildContext context) {
return StreamBuilder<int>(
stream: channel.state!.unreadCountStream,
initialData: channel.state!.unreadCount,
builder: (context, snapshot) {
if (!snapshot.hasData || snapshot.data == 0) {
return SizedBox();
}
return Material(
borderRadius: BorderRadius.circular(8),
color: StreamChatTheme.of(context)
.channelPreviewTheme
.unreadCounterColor,
child: Padding(
padding: const EdgeInsets.only(
left: 5.0,
right: 5.0,
top: 2,
bottom: 1,
),
child: Center(
child: Text(
'${snapshot.data! > 99 ? '99+' : snapshot.data}',
style: TextStyle(
fontSize: 11,
color: Colors.white,
),
),
),
),
);
},
);
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib/ui | mirrored_repositories/flutter-samples/packages/chatty/lib/ui/common/avatar_image_view.dart | import 'package:flutter/material.dart';
class AvatarImageView extends StatelessWidget {
const AvatarImageView({Key? key, this.onTap, this.child}) : super(key: key);
final Widget? child;
final VoidCallback? onTap;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(20.0),
child: Stack(
clipBehavior: Clip.none,
children: [
ClipOval(
child: Container(
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Colors.grey[100],
),
height: 180,
width: 180,
child: child,
),
),
Positioned(
bottom: -15,
right: 0,
child: GestureDetector(
onTap: onTap,
child: CircleAvatar(
backgroundColor: Colors.white,
radius: 30,
child: Icon(
Icons.camera_alt_outlined,
color: Colors.black,
),
),
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib/ui | mirrored_repositories/flutter-samples/packages/chatty/lib/ui/common/loading_view.dart | import 'package:flutter/material.dart';
class LoadingView extends StatelessWidget {
final bool isLoading;
final Widget child;
const LoadingView({
Key? key,
required this.child,
this.isLoading = false,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
child,
if (isLoading)
Container(
color: Colors.black26,
child: Center(
child: CircularProgressIndicator(),
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib/ui | mirrored_repositories/flutter-samples/packages/chatty/lib/ui/common/initial_background_view.dart | import 'package:flutter/material.dart';
class InitialBackgroundView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Stack(
children: [
Positioned(
top: 20,
right: -75,
child: Image.asset(
'assets/icon-top-right.png',
height: 150,
),
),
Positioned(
bottom: -50,
right: -50,
child: Image.asset(
'assets/icon-bottom-right.png',
height: 200,
),
),
],
);
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib/ui | mirrored_repositories/flutter-samples/packages/chatty/lib/ui/home/home_view.dart | import 'package:stream_chatter/navigator_utils.dart';
import 'package:stream_chatter/ui/home/chat/chat_view.dart';
import 'package:stream_chatter/ui/home/chat/selection/friends_selection_view.dart';
import 'package:stream_chatter/ui/home/home_cubit.dart';
import 'package:stream_chatter/ui/home/settings/settings_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class HomeView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Theme.of(context).canvasColor,
body: BlocProvider(
create: (_) => HomeCubit(),
child: Column(
children: [
Expanded(
child: BlocBuilder<HomeCubit, int>(builder: (context, snapshot) {
return IndexedStack(
index: snapshot,
children: [
ChatView(),
SettingsView(),
],
);
}),
),
HomeNavigationBar(),
],
),
),
);
}
}
class HomeNavigationBar extends StatelessWidget {
const HomeNavigationBar({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
final cubit = BlocProvider.of<HomeCubit>(context, listen: true);
final navigationBarSize = 80.0;
final buttonSize = 56.0;
final buttonMargin = 4.0;
final topMargin = buttonSize / 2 + buttonMargin / 2;
final canvasColor = Theme.of(context).canvasColor;
return Padding(
padding: const EdgeInsets.only(bottom: 20.0),
child: Material(
child: Container(
height: navigationBarSize + topMargin,
width: MediaQuery.of(context).size.width * 0.7,
color: canvasColor,
child: Stack(
children: [
Positioned.fill(
top: topMargin,
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(25),
color: Theme.of(context)
.bottomNavigationBarTheme
.backgroundColor,
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
_HomeNavItem(
text: 'Chats',
iconData: Icons.chat_bubble,
onTap: () => cubit.onChangeTab(0),
selected: cubit.state == 0,
),
_HomeNavItem(
text: 'Settings',
iconData: Icons.settings,
onTap: () => cubit.onChangeTab(1),
selected: cubit.state == 1,
),
],
),
),
),
Align(
alignment: Alignment.topCenter,
child: Container(
decoration: BoxDecoration(
color: canvasColor,
shape: BoxShape.circle,
),
padding: EdgeInsets.all(buttonMargin / 2),
child: FloatingActionButton(
onPressed: () {
pushToPage(context, FriendsSelectionView());
},
child: Icon(Icons.add),
),
),
),
],
),
),
),
);
}
}
class _HomeNavItem extends StatelessWidget {
const _HomeNavItem({
Key? key,
this.iconData,
this.text,
this.onTap,
this.selected = false,
}) : super(key: key);
final IconData? iconData;
final String? text;
final VoidCallback? onTap;
final bool selected;
@override
Widget build(BuildContext context) {
final selectedColor =
Theme.of(context).bottomNavigationBarTheme.selectedItemColor;
final unselectedColor =
Theme.of(context).bottomNavigationBarTheme.unselectedItemColor;
final color = selected ? selectedColor : unselectedColor;
return GestureDetector(
onTap: onTap,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(iconData, color: color),
Text(text!, style: TextStyle(color: color)),
],
),
);
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib/ui | mirrored_repositories/flutter-samples/packages/chatty/lib/ui/home/home_cubit.dart | import 'package:flutter_bloc/flutter_bloc.dart';
class HomeCubit extends Cubit<int> {
HomeCubit() : super(0);
void onChangeTab(int index) => emit(index);
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib/ui/home | mirrored_repositories/flutter-samples/packages/chatty/lib/ui/home/chat/chat_view.dart | import 'package:stream_chatter/ui/common/my_channel_preview.dart';
import 'package:flutter/material.dart';
import 'package:stream_chat_flutter/stream_chat_flutter.dart';
class ChatView extends StatelessWidget {
@override
Widget build(BuildContext context) {
final textColor = Theme.of(context).appBarTheme.backgroundColor;
return Scaffold(
backgroundColor: Theme.of(context).canvasColor,
appBar: AppBar(
title: Text(
'Chats',
style: TextStyle(
fontSize: 24,
color: textColor,
fontWeight: FontWeight.w800,
),
),
centerTitle: false,
elevation: 0,
backgroundColor: Theme.of(context).canvasColor,
),
body: ChannelsBloc(
child: ChannelListView(
filter: Filter.in_(
'members',
[StreamChat.of(context).currentUser!.id],
),
sort: [SortOption('last_message_at')],
channelPreviewBuilder: (context, channel) {
return Container(
color: Theme.of(context).canvasColor,
child: MyChannelPreview(
channel: channel,
heroTag: channel.id,
onImageTap: () {
String? name;
String? image;
final currentUser =
StreamChat.of(context).client.state.currentUser;
if (channel.isGroup) {
name = channel.extraData['name'] as String?;
image = channel.extraData['image'] as String?;
} else {
final friend = channel.state!.members
.where((element) => element.userId != currentUser!.id)
.first
.user!;
name = friend.name;
image = friend.extraData['image'] as String?;
}
Navigator.of(context).push(
PageRouteBuilder(
barrierColor: Colors.black45,
barrierDismissible: true,
opaque: false,
pageBuilder: (context, animation1, _) {
return FadeTransition(
opacity: animation1,
child: ChatDetailView(
channelId: channel.id,
image: image,
name: name,
),
);
}),
);
},
onTap: (channel) => {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) {
return StreamChannel(
child: ChannelPage(),
channel: channel,
);
},
),
)
},
),
);
},
channelWidget: ChannelPage(),
),
),
);
}
}
class ChannelPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: ChannelHeader(),
body: Column(
children: [
Expanded(
child: MessageListView(),
),
MessageInput(),
],
),
);
}
}
class ChatDetailView extends StatelessWidget {
const ChatDetailView({
Key? key,
this.image,
this.name,
this.channelId,
}) : super(key: key);
final String? image;
final String? name;
final String? channelId;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: Navigator.of(context).pop,
child: Material(
color: Colors.transparent,
child: Dialog(
backgroundColor: Colors.transparent,
elevation: 0,
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Hero(
tag: channelId!,
child: ClipOval(
child: Image.network(
image!,
height: 180,
width: 180,
fit: BoxFit.cover,
),
),
),
Text(
name!,
style: TextStyle(
fontWeight: FontWeight.w700,
fontSize: 22,
),
),
],
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib/ui/home/chat | mirrored_repositories/flutter-samples/packages/chatty/lib/ui/home/chat/selection/friends_selection_view.dart | import 'package:stream_chatter/navigator_utils.dart';
import 'package:stream_chatter/ui/home/chat/chat_view.dart';
import 'package:stream_chatter/ui/home/chat/selection/friends_selection_cubit.dart';
import 'package:stream_chatter/ui/home/chat/selection/group_selection_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:stream_chat_flutter/stream_chat_flutter.dart';
class FriendsSelectionView extends StatelessWidget {
void _createFriendChannel(
BuildContext context, ChatUserState chatUserState) async {
final channel = await context
.read<FriendsSelectionCubit>()
.createFriendChannel(chatUserState);
pushAndReplaceToPage(
context,
Scaffold(
body: StreamChannel(
channel: channel,
child: ChannelPage(),
),
),
);
}
@override
Widget build(BuildContext context) {
final textColor = Theme.of(context).appBarTheme.backgroundColor;
final accentColor = Theme.of(context).colorScheme.secondary;
return MultiBlocProvider(
providers: [
BlocProvider(
create: (context) => FriendsSelectionCubit(context.read())..init()),
BlocProvider(create: (_) => FriendsGroupCubit()),
],
child: BlocBuilder<FriendsGroupCubit, bool>(builder: (context, isGroup) {
return BlocBuilder<FriendsSelectionCubit, List<ChatUserState>>(
builder: (context, snapshot) {
final selectedUsers =
context.read<FriendsSelectionCubit>().selectedUsers;
return Scaffold(
floatingActionButton: isGroup && selectedUsers.isNotEmpty
? FloatingActionButton(
child: Icon(Icons.arrow_right_alt_rounded),
onPressed: () {
pushAndReplaceToPage(
context, GroupSelectionView(selectedUsers));
})
: null,
backgroundColor: Theme.of(context).canvasColor,
body: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 10.0,
vertical: 20,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (isGroup)
Row(
children: [
BackButton(
onPressed: () {
context.read<FriendsGroupCubit>().changeToGroup();
},
),
Text(
'New Group',
style: TextStyle(
fontSize: 24,
color: textColor,
fontWeight: FontWeight.w800,
),
),
],
)
else
Row(
children: [
BackButton(
onPressed: Navigator.of(context).pop,
),
Text(
'People',
style: TextStyle(
fontSize: 24,
color: textColor,
fontWeight: FontWeight.w800,
),
),
],
),
if (!isGroup)
ListTile(
onTap: context.read<FriendsGroupCubit>().changeToGroup,
leading: CircleAvatar(
backgroundColor: accentColor,
child: Icon(Icons.group_outlined),
),
title: Text('Create group',
style: TextStyle(fontWeight: FontWeight.w700)),
subtitle: Text('Talk with 2 or more contacts'),
)
else if (isGroup && selectedUsers.isEmpty)
Padding(
padding: const EdgeInsets.only(
top: 15.0, left: 20.0, bottom: 20),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
CircleAvatar(
backgroundColor: Colors.grey[200],
),
Text(
'Add a friend',
style: TextStyle(
fontSize: 12,
color: Colors.grey[500],
),
),
],
),
)
else
SizedBox(
height: 100,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: selectedUsers.length,
itemBuilder: (context, index) {
final chatUserState = selectedUsers[index];
return Padding(
padding: const EdgeInsets.symmetric(
horizontal: 13.0),
child: Stack(
clipBehavior: Clip.none,
children: [
Column(
mainAxisSize: MainAxisSize.min,
children: [
CircleAvatar(
radius: 30,
backgroundImage: NetworkImage(
chatUserState.chatUser.image!),
),
Text(chatUserState.chatUser.name!),
],
),
Positioned(
bottom: 40,
right: -4,
child: InkWell(
onTap: () => context
.read<FriendsSelectionCubit>()
.selectUser(chatUserState),
child: CircleAvatar(
radius: 9,
backgroundColor: accentColor,
child: Icon(Icons.close_rounded,
size: 12),
),
),
),
],
),
);
})),
Expanded(
child: ListView.builder(
itemCount: snapshot.length,
itemBuilder: (context, index) {
final chatUserState = snapshot[index];
return ListTile(
onTap: () {
_createFriendChannel(context, chatUserState);
},
leading: CircleAvatar(
backgroundImage:
NetworkImage(chatUserState.chatUser.image!),
),
title: Text(chatUserState.chatUser.name!),
trailing: isGroup
? Checkbox(
value: chatUserState.selected,
onChanged: (val) {
print('select user for group');
context
.read<FriendsSelectionCubit>()
.selectUser(chatUserState);
},
)
: null,
);
},
),
),
],
),
),
);
});
}),
);
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib/ui/home/chat | mirrored_repositories/flutter-samples/packages/chatty/lib/ui/home/chat/selection/group_selection_view.dart | import 'package:stream_chatter/navigator_utils.dart';
import 'package:stream_chatter/ui/common/avatar_image_view.dart';
import 'package:stream_chatter/ui/common/loading_view.dart';
import 'package:stream_chatter/ui/home/chat/chat_view.dart';
import 'package:stream_chatter/ui/home/chat/selection/friends_selection_cubit.dart';
import 'package:stream_chatter/ui/home/chat/selection/group_selection_cubit.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:stream_chat_flutter/stream_chat_flutter.dart';
class GroupSelectionView extends StatelessWidget {
GroupSelectionView(this.selectedUsers);
final List<ChatUserState> selectedUsers;
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => GroupSelectionCubit(
selectedUsers,
context.read(),
context.read(),
),
child: BlocConsumer<GroupSelectionCubit, GroupSelectionState>(
listener: (context, snapshot) {
if (snapshot.channel != null) {
pushAndReplaceToPage(
context,
Scaffold(
body: StreamChannel(
channel: snapshot.channel!,
child: ChannelPage(),
),
),
);
}
}, builder: (context, snapshot) {
return LoadingView(
isLoading: snapshot.isLoading,
child: Scaffold(
floatingActionButton: FloatingActionButton(
child: Icon(Icons.arrow_right_alt_rounded),
onPressed: context.read<GroupSelectionCubit>().createGroup,
),
backgroundColor: Theme.of(context).canvasColor,
appBar: AppBar(
title: Text(
'New Group',
style: TextStyle(
fontSize: 24,
color: Theme.of(context).appBarTheme.backgroundColor,
fontWeight: FontWeight.w800,
),
),
centerTitle: false,
elevation: 0,
backgroundColor: Theme.of(context).canvasColor,
),
body: Column(
children: [
AvatarImageView(
onTap: context.read<GroupSelectionCubit>().pickImage,
child: snapshot.file != null
? Image.file(
snapshot.file!,
fit: BoxFit.cover,
)
: Icon(
Icons.person_outline,
size: 100,
color: Colors.grey[400],
),
),
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 50.0,
vertical: 20,
),
child: TextField(
controller:
context.read<GroupSelectionCubit>().nameTextController,
decoration: InputDecoration(
fillColor: Theme.of(context)
.bottomNavigationBarTheme
.backgroundColor,
hintText: 'Name of the group',
hintStyle: TextStyle(
fontSize: 13,
color: Colors.grey[400],
),
border: InputBorder.none,
enabledBorder: InputBorder.none,
),
),
),
Wrap(
children: List.generate(selectedUsers.length, (index) {
final chatUserState = selectedUsers[index];
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 10.0),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
CircleAvatar(
radius: 30,
backgroundImage:
NetworkImage(chatUserState.chatUser.image!),
),
Text(chatUserState.chatUser.name!),
],
),
);
}),
),
],
),
),
);
}),
);
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib/ui/home/chat | mirrored_repositories/flutter-samples/packages/chatty/lib/ui/home/chat/selection/friends_selection_cubit.dart | import 'package:stream_chatter/data/stream_api_repository.dart';
import 'package:stream_chatter/domain/models/chat_user.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:stream_chat_flutter/stream_chat_flutter.dart';
class ChatUserState {
const ChatUserState(this.chatUser, {this.selected = false});
final ChatUser chatUser;
final bool selected;
}
class FriendsSelectionCubit extends Cubit<List<ChatUserState>> {
FriendsSelectionCubit(this._streamApiRepository) : super([]);
final StreamApiRepository _streamApiRepository;
List<ChatUserState> get selectedUsers =>
state.where((element) => element.selected).toList();
Future<void> init() async {
final chatUsers = (await _streamApiRepository.getChatUsers())
.map((e) => ChatUserState(e))
.toList();
emit(chatUsers);
}
void selectUser(ChatUserState chatUser) {
final index = state
.indexWhere((element) => element.chatUser.id == chatUser.chatUser.id);
state[index] =
ChatUserState(state[index].chatUser, selected: !chatUser.selected);
emit(List<ChatUserState>.from(state));
}
Future<Channel> createFriendChannel(ChatUserState chatUserState) async {
return await _streamApiRepository
.createSimpleChat(chatUserState.chatUser.id);
}
}
class FriendsGroupCubit extends Cubit<bool> {
FriendsGroupCubit() : super(false);
void changeToGroup() => emit(!state);
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib/ui/home/chat | mirrored_repositories/flutter-samples/packages/chatty/lib/ui/home/chat/selection/group_selection_cubit.dart | import 'dart:io';
import 'package:stream_chatter/data/image_picker_repository.dart';
import 'package:stream_chatter/domain/usecases/create_group_usecase.dart';
import 'package:stream_chatter/ui/home/chat/selection/friends_selection_cubit.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:stream_chat_flutter/stream_chat_flutter.dart';
class GroupSelectionState {
const GroupSelectionState(
this.file, {
this.channel,
this.isLoading = false,
});
final File? file;
final Channel? channel;
final bool isLoading;
}
class GroupSelectionCubit extends Cubit<GroupSelectionState> {
GroupSelectionCubit(
this.members,
this._createGroupUseCase,
this._imagePickerRepository,
) : super(GroupSelectionState(null));
final nameTextController = TextEditingController();
final List<ChatUserState> members;
final CreateGroupUseCase _createGroupUseCase;
final ImagePickerRepository _imagePickerRepository;
void createGroup() async {
emit(GroupSelectionState(state.file, isLoading: true));
final channel = await _createGroupUseCase.createGroup(CreateGroupInput(
imageFile: state.file,
members: members.map((e) => e.chatUser.id).toList(),
name: nameTextController.text,
));
emit(GroupSelectionState(state.file, channel: channel, isLoading: false));
}
void pickImage() async {
final image = await _imagePickerRepository.pickImage();
emit(GroupSelectionState(image));
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib/ui/home | mirrored_repositories/flutter-samples/packages/chatty/lib/ui/home/settings/settings_cubit.dart | import 'package:stream_chatter/domain/usecases/logout_usecase.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class SettingsSwitchCubit extends Cubit<bool> {
SettingsSwitchCubit(bool state) : super(state);
void onChangeDarkMode(bool isDark) => emit(isDark);
}
class SettingsLogoutCubit extends Cubit<void> {
SettingsLogoutCubit(this._logoutUseCase) : super(null);
final LogoutUseCase _logoutUseCase;
void logOut() async {
await _logoutUseCase.logout();
emit(null);
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib/ui/home | mirrored_repositories/flutter-samples/packages/chatty/lib/ui/home/settings/settings_view.dart | import 'package:stream_chatter/navigator_utils.dart';
import 'package:stream_chatter/ui/app_theme_cubit.dart';
import 'package:stream_chatter/ui/common/avatar_image_view.dart';
import 'package:stream_chatter/ui/home/settings/settings_cubit.dart';
import 'package:stream_chatter/ui/sign_in/sign_in_view.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:stream_chat_flutter/stream_chat_flutter.dart';
class SettingsView extends StatelessWidget {
@override
Widget build(BuildContext context) {
final user = StreamChat.of(context).client.state.currentUser!;
final image = user.extraData['image'];
final textColor = Theme.of(context).appBarTheme.backgroundColor;
return MultiBlocProvider(
providers: [
BlocProvider(
create: (_) =>
SettingsSwitchCubit(context.read<AppThemeCubit>().isDark),
),
BlocProvider(
create: (_) => SettingsLogoutCubit(context.read()),
),
],
child: Scaffold(
backgroundColor: Theme.of(context).canvasColor,
appBar: AppBar(
title: Text(
'Settings',
style: TextStyle(
fontSize: 24,
color: textColor,
fontWeight: FontWeight.w800,
),
),
centerTitle: false,
elevation: 0,
backgroundColor: Theme.of(context).canvasColor,
),
body: Center(
child: Padding(
padding: const EdgeInsets.all(15.0),
child: Column(
children: [
AvatarImageView(
onTap: () => null,
child: image != null
? Image.network(
image as String,
fit: BoxFit.cover,
)
: Icon(
Icons.person_outline,
size: 100,
color: Colors.grey[400],
),
),
Text(
user.name,
style: TextStyle(
fontSize: 24,
color: textColor,
fontWeight: FontWeight.w800,
),
),
Row(
children: [
Icon(Icons.nights_stay_outlined),
const SizedBox(width: 10),
Text(
'Dark Mode',
style: TextStyle(
color: textColor,
),
),
Spacer(),
BlocBuilder<SettingsSwitchCubit, bool>(
builder: (context, snapshot) {
return Switch(
value: snapshot,
onChanged: (val) {
context
.read<SettingsSwitchCubit>()
.onChangeDarkMode(val);
context.read<AppThemeCubit>().updateTheme(val);
},
);
}),
],
),
const SizedBox(height: 15),
Builder(builder: (context) {
return GestureDetector(
onTap: context.read<SettingsLogoutCubit>().logOut,
child: BlocListener<SettingsLogoutCubit, void>(
listener: (context, snapshot) {
popAllAndPush(context, SignInView());
},
child: Row(children: [
Icon(Icons.logout),
const SizedBox(width: 10),
Text(
'Logout',
style: TextStyle(
color: textColor,
),
),
Spacer(),
Icon(Icons.arrow_right),
]),
),
);
}),
],
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib/ui | mirrored_repositories/flutter-samples/packages/chatty/lib/ui/splash/splash_view.dart | import 'package:stream_chatter/navigator_utils.dart';
import 'package:stream_chatter/ui/home/home_view.dart';
import 'package:stream_chatter/ui/profile_verify/profile_verify_view.dart';
import 'package:stream_chatter/ui/sign_in/sign_in_view.dart';
import 'package:stream_chatter/ui/common/initial_background_view.dart';
import 'package:stream_chatter/ui/splash/splash_cubit.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class SplashView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (context) => SplashCubit(context.read())..init(),
child: BlocListener<SplashCubit, SplashState>(
listener: (context, snapshot) {
if (snapshot == SplashState.none) {
pushAndReplaceToPage(context, SignInView());
} else if (snapshot == SplashState.existing_user) {
pushAndReplaceToPage(context, HomeView());
} else {
pushAndReplaceToPage(context, ProfileVerifyView());
}
},
child: Scaffold(
body: Stack(
children: [
InitialBackgroundView(),
Center(
child: Hero(
tag: 'logo_hero',
child: Image.asset(
'assets/logo.png',
height: 100,
),
),
),
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/chatty/lib/ui | mirrored_repositories/flutter-samples/packages/chatty/lib/ui/splash/splash_cubit.dart | import 'package:stream_chatter/domain/exceptions/auth_exception.dart';
import 'package:stream_chatter/domain/usecases/login_usecase.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
enum SplashState {
none,
existing_user,
new_user,
}
class SplashCubit extends Cubit<SplashState> {
SplashCubit(
this._loginUseCase,
) : super(SplashState.none);
final LoginUseCase _loginUseCase;
void init() async {
try {
final result = await _loginUseCase.validateLogin();
if (result) {
emit(SplashState.existing_user);
}
} on AuthException catch (ex) {
if (ex.error == AuthErrorCode.not_auth) {
emit(SplashState.none);
} else {
emit(SplashState.new_user);
}
}
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/imessage | mirrored_repositories/flutter-samples/packages/imessage/lib/message_widget.dart | import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:imessage/cutom_painter.dart';
import 'package:stream_chat_flutter_core/stream_chat_flutter_core.dart'
show Message;
class MessageWidget extends StatelessWidget {
final Alignment alignment;
final EdgeInsets margin;
final Message message;
final Color color;
final Color messageColor;
final bool hasTail;
const MessageWidget({
Key? key,
required this.alignment,
required this.margin,
required this.message,
required this.color,
required this.messageColor,
this.hasTail = false,
}) : super(key: key);
@override
Widget build(BuildContext context) {
if (message.attachments.isNotEmpty == true &&
message.attachments.first.type == 'image') {
return MessageImage(
color: color, message: message, messageColor: messageColor);
} else {
return MessageText(
alignment: alignment,
margin: margin,
color: color,
message: message,
messageColor: messageColor,
hasTail: hasTail,
);
}
}
}
class MessageImage extends StatelessWidget {
const MessageImage({
Key? key,
required this.color,
required this.message,
required this.messageColor,
}) : super(key: key);
final Color color;
final Message message;
final Color messageColor;
@override
Widget build(BuildContext context) {
if (message.text != null) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(20),
child: Container(
color: color,
child: Column(
children: [
if (message.attachments.first.file != null)
Image.memory(
message.attachments.first.file!.bytes!,
fit: BoxFit.cover,
)
else
CachedNetworkImage(
imageUrl: message.attachments.first.thumbUrl ??
message.attachments.first.imageUrl ??
message.attachments.first.assetUrl!,
),
if (message.attachments.first.title != null)
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(message.attachments.first.title!,
style: TextStyle(color: messageColor)),
),
message.attachments.first.pretext != null
? Text(message.attachments.first.pretext!)
: Container()
],
),
),
)
],
),
);
} else {
return ClipRRect(
borderRadius: BorderRadius.circular(20),
child: Container(
color: color,
child: CachedNetworkImage(
imageUrl: message.attachments.first.thumbUrl!,
)),
);
}
}
}
class MessageText extends StatelessWidget {
const MessageText({
Key? key,
required this.alignment,
required this.margin,
required this.color,
required this.message,
required this.messageColor,
required this.hasTail,
}) : super(key: key);
final Alignment alignment;
final Color color;
final Message message;
final Color messageColor;
final EdgeInsets margin;
final bool hasTail;
@override
Widget build(BuildContext context) {
if (message.text?.isEmpty ?? true) {
return const SizedBox.shrink();
}
return Padding(
padding: const EdgeInsets.only(top: 1),
child: Align(
alignment:
alignment, //Change this to Alignment.topRight or Alignment.topLeft
child: CustomPaint(
painter:
ChatBubble(color: color, alignment: alignment, hasTail: hasTail),
child: Container(
margin: margin,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
ConstrainedBox(
constraints: BoxConstraints(
maxWidth: MediaQuery.of(context).size.width * 0.65,
),
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 6.0, vertical: 4),
child: Text(
message.text!,
style: TextStyle(color: messageColor),
),
),
),
],
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/imessage | mirrored_repositories/flutter-samples/packages/imessage/lib/channel_preview.dart | import 'package:flutter/cupertino.dart';
import 'package:imessage/channel_image.dart';
import 'package:imessage/channel_name_text.dart';
import 'package:imessage/utils.dart';
import 'package:stream_chat_flutter_core/stream_chat_flutter_core.dart'
show Channel;
class ChannelPreview extends StatelessWidget {
final VoidCallback onTap;
final Channel channel;
const ChannelPreview({
Key? key,
required this.onTap,
required this.channel,
}) : super(key: key);
@override
Widget build(BuildContext context) {
final lastMessage = channel.state!.messages.isNotEmpty
? channel.state!.messages.last
: null;
final prefix = lastMessage?.attachments != null
? lastMessage?.attachments
.map((e) {
if (e.type == 'image') {
return '📷 ';
} else if (e.type == 'video') {
return '🎬 ';
}
return null;
})
.where((e) => e != null)
.join(' ')
: '';
return GestureDetector(
onTap: onTap,
behavior: HitTestBehavior.opaque,
child: SizedBox(
height: 70,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 8.0,
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(left: 16.0, right: 8.0),
child: ChannelImage(
channel: channel,
size: 46,
),
),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 4.0),
child: ChannelNameText(channel: channel),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 4.0),
child: Row(
children: [
Text(
isSameWeek(channel.lastMessageAt!)
? formatDateSameWeek(channel.lastMessageAt!)
: formatDate(channel.lastMessageAt!),
style: const TextStyle(
fontSize: 13,
color: CupertinoColors.systemGrey,
),
),
const Padding(
padding: EdgeInsets.only(left: 4.0),
child: Icon(
CupertinoIcons.chevron_right,
size: 16,
color: CupertinoColors.systemGrey3,
),
),
],
),
)
],
),
Padding(
padding: const EdgeInsets.all(4.0),
child: Text(
'$prefix${lastMessage?.text ?? ''}',
style: const TextStyle(
fontWeight: FontWeight.normal,
color: CupertinoColors.systemGrey,
fontSize: 14,
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
),
const Divider(),
],
),
)
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/imessage | mirrored_repositories/flutter-samples/packages/imessage/lib/cutom_painter.dart | import 'package:flutter/cupertino.dart';
class ChatBubble extends CustomPainter {
final Color color;
final Alignment? alignment;
final bool hasTail;
ChatBubble({
required this.color,
required this.hasTail,
this.alignment,
}) : paintFill = Paint()
..color = color
..style = PaintingStyle.fill;
final Paint paintFill;
@override
void paint(Canvas canvas, Size size) {
final path = Path();
const cornerSize = 18.0;
const buffer = 6.0;
const innerTailWidth = 7.0;
const innerTailHeight = 4.0;
if (alignment == Alignment.topRight) {
path.moveTo(0, cornerSize);
path.lineTo(0, size.height - cornerSize);
path.arcToPoint(Offset(cornerSize, size.height),
radius: const Radius.circular(cornerSize), clockwise: false);
if (hasTail) {
path.lineTo(size.width - cornerSize - innerTailWidth, size.height);
path.arcToPoint(
Offset(size.width - buffer - innerTailWidth,
size.height - innerTailHeight),
radius: const Radius.circular(cornerSize),
clockwise: false);
path.arcToPoint(Offset(size.width, size.height),
radius: const Radius.circular(buffer * 2), clockwise: false);
path.arcToPoint(
Offset(size.width - buffer, size.height - buffer - innerTailHeight),
radius: const Radius.circular(buffer + innerTailHeight),
clockwise: true);
} else {
path.lineTo(size.width - cornerSize, size.height);
path.arcToPoint(Offset(size.width - buffer, size.height - cornerSize),
radius: const Radius.circular(cornerSize), clockwise: false);
}
path.lineTo(size.width - buffer, cornerSize);
path.arcToPoint(Offset(size.width - cornerSize - buffer, 0),
radius: const Radius.circular(cornerSize), clockwise: false);
path.lineTo(cornerSize, 0);
path.arcToPoint(const Offset(0, cornerSize),
radius: const Radius.circular(cornerSize), clockwise: false);
} else {
path.moveTo(size.width, cornerSize);
path.arcToPoint(Offset(size.width - cornerSize, 0),
radius: const Radius.circular(cornerSize), clockwise: false);
path.lineTo(cornerSize + buffer, 0);
path.arcToPoint(const Offset(buffer, cornerSize),
radius: const Radius.circular(cornerSize), clockwise: false);
if (hasTail) {
path.lineTo(buffer, size.height - buffer - innerTailHeight);
path.arcToPoint(Offset(0, size.height),
radius: const Radius.circular(buffer + innerTailHeight),
clockwise: true);
path.arcToPoint(
Offset(buffer + innerTailWidth, size.height - innerTailHeight),
radius: const Radius.circular(buffer * 2),
clockwise: false);
path.arcToPoint(Offset(cornerSize + innerTailWidth, size.height),
radius: const Radius.circular(cornerSize), clockwise: false);
} else {
path.lineTo(buffer, size.height - cornerSize);
path.arcToPoint(Offset(buffer + cornerSize, size.height),
radius: const Radius.circular(cornerSize), clockwise: false);
}
path.lineTo(size.width - cornerSize, size.height);
path.arcToPoint(Offset(size.width, size.height - cornerSize),
radius: const Radius.circular(cornerSize), clockwise: false);
}
canvas.drawPath(
path,
paintFill,
);
}
@override
bool shouldRepaint(ChatBubble oldDelegate) {
if (color != oldDelegate.color ||
alignment != oldDelegate.alignment ||
hasTail != oldDelegate.hasTail) {
return true;
} else {
return false;
}
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/imessage | mirrored_repositories/flutter-samples/packages/imessage/lib/channel_image.dart | import 'package:flutter/cupertino.dart';
import 'package:stream_chat_flutter_core/stream_chat_flutter_core.dart'
show Channel;
import 'package:imessage/utils.dart';
class ChannelImage extends StatelessWidget {
const ChannelImage({
Key? key,
required this.channel,
required this.size,
}) : super(key: key);
final Channel channel;
final double size;
@override
Widget build(BuildContext context) {
final avatarUrl = channel.extraData.containsKey('image') &&
(channel.extraData['image'] as String).isNotEmpty
? channel.extraData['image'] as String?
: 'https://4.bp.blogspot.com/-Jx21kNqFSTU/UXemtqPhZCI/AAAAAAAAh74/BMGSzpU6F48/s1600/funny-cat-pictures-047-001.jpg';
return CupertinoCircleAvatar(
size: size,
url: avatarUrl,
);
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/imessage | mirrored_repositories/flutter-samples/packages/imessage/lib/channel_page_appbar.dart | import 'package:flutter/cupertino.dart';
class ChannelPageAppBar extends StatelessWidget {
const ChannelPageAppBar({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return const CupertinoSliverNavigationBar(
largeTitle: Text(
'Messages',
style: TextStyle(letterSpacing: -1.3),
),
);
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/imessage | mirrored_repositories/flutter-samples/packages/imessage/lib/message_page.dart | import 'package:flutter/cupertino.dart';
import 'package:imessage/message_list_view.dart';
import 'package:stream_chat_flutter_core/stream_chat_flutter_core.dart'
show
LazyLoadScrollView,
MessageListController,
MessageListCore,
StreamChannel,
StreamChatCore;
import 'package:imessage/channel_image.dart';
import 'package:imessage/channel_name_text.dart';
class MessagePage extends StatelessWidget {
const MessagePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
final streamChannel = StreamChannel.of(context);
var messageListController = MessageListController();
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: Column(
children: [
ChannelImage(
size: 32,
channel: streamChannel.channel,
),
ChannelNameText(
channel: streamChannel.channel,
size: 10,
fontWeight: FontWeight.w300,
),
],
),
),
child: StreamChatCore(
client: streamChannel.channel.client,
child: MessageListCore(
messageListController: messageListController,
loadingBuilder: (context) {
return const Center(
child: CupertinoActivityIndicator(),
);
},
errorBuilder: (context, err) {
return const Center(
child: Text('Error'),
);
},
emptyBuilder: (context) {
return const Center(
child: Text('Nothing here...'),
);
},
messageListBuilder: (context, messages) => LazyLoadScrollView(
onStartOfPage: () async {
await messageListController.paginateData!();
},
child: MessageListView(
messages: messages,
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/imessage | mirrored_repositories/flutter-samples/packages/imessage/lib/channel_list_view.dart | import 'package:flutter/cupertino.dart';
import 'package:imessage/channel_preview.dart';
import 'package:imessage/message_page.dart';
import 'package:animations/animations.dart';
import 'package:stream_chat_flutter_core/stream_chat_flutter_core.dart'
show Channel, StreamChannel;
class ChannelListView extends StatelessWidget {
const ChannelListView({Key? key, required this.channels}) : super(key: key);
final List<Channel> channels;
@override
Widget build(BuildContext context) {
channels.removeWhere((channel) => channel.lastMessageAt == null);
return SliverList(
delegate: SliverChildBuilderDelegate(
(
BuildContext context,
int index,
) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 4.0),
child: ChannelPreview(
channel: channels[index],
onTap: () {
Navigator.push(
context,
PageRouteBuilder(
pageBuilder: (_, __, ___) => StreamChannel(
channel: channels[index],
child: const MessagePage(),
),
transitionsBuilder: (
_,
animation,
secondaryAnimation,
child,
) =>
SharedAxisTransition(
animation: animation,
secondaryAnimation: secondaryAnimation,
transitionType: SharedAxisTransitionType.horizontal,
child: child,
),
),
);
},
),
);
},
childCount: channels.length,
),
);
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/imessage | mirrored_repositories/flutter-samples/packages/imessage/lib/message_list_view.dart | import 'package:collection/collection.dart';
import 'package:flutter/cupertino.dart';
import 'package:imessage/message_header.dart';
import 'package:imessage/message_input.dart';
import 'package:imessage/message_widget.dart';
import 'package:stream_chat_flutter_core/stream_chat_flutter_core.dart'
show Message, StreamChatCore;
class MessageListView extends StatelessWidget {
const MessageListView({Key? key, this.messages}) : super(key: key);
final List<Message>? messages;
@override
Widget build(BuildContext context) {
final entries = groupBy(messages!,
(Message message) => message.createdAt.toString().substring(0, 10))
.entries
.toList();
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: Column(
children: [
Expanded(
child: SizedBox(
height: MediaQuery.of(context).size.height * 0.9,
child: Align(
alignment: FractionalOffset.topCenter,
child: ListView.builder(
reverse: true,
itemCount: entries.length,
itemBuilder: (context, index) {
return Column(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(
8.0, 24.0, 8.0, 8.0),
child: MessageHeader(
rawTimeStamp: entries[index].key), //date
),
...entries[index]
.value //messages
.asMap()
.entries
.map(
(entry) {
final message = entry.value;
final isFinalMessage = 0 == entry.key;
final received =
isReceived(message, context);
return (received)
? MessageWidget(
alignment: Alignment.topRight,
margin: const EdgeInsets.fromLTRB(
8.0, 4.0, 16.0, 4.0),
color: const Color(0xFF3CABFA),
messageColor: CupertinoColors.white,
message: message,
hasTail: isFinalMessage,
)
: MessageWidget(
alignment: Alignment.centerLeft,
margin: const EdgeInsets.fromLTRB(
16.0, 4.0, 8.0, 4.0),
color: CupertinoColors.systemGrey5,
messageColor: CupertinoColors.black,
message: message,
hasTail: isFinalMessage,
);
},
)
.toList()
.reversed,
],
);
}),
)),
),
const MessageInput()
],
),
);
}
bool isReceived(Message message, BuildContext context) {
final currentUserId = StreamChatCore.of(context).currentUser!.id;
return message.user!.id == currentUserId;
}
bool isSameDay(Message message) =>
message.createdAt.day == DateTime.now().day;
}
| 0 |
mirrored_repositories/flutter-samples/packages/imessage | mirrored_repositories/flutter-samples/packages/imessage/lib/utils.dart | import 'package:cached_network_image/cached_network_image.dart';
import 'package:intl/intl.dart';
import 'package:flutter/cupertino.dart';
String formatDate(DateTime date) {
final dateFormat = DateFormat.yMd();
return dateFormat.format(date);
}
String formatDateSameWeek(DateTime date) {
DateFormat dateFormat;
if (date.day == DateTime.now().day) {
dateFormat = DateFormat('hh:mm a');
} else {
dateFormat = DateFormat('EEEE');
}
return dateFormat.format(date);
}
String formatDateMessage(DateTime date) {
final dateFormat = DateFormat('EEE. MMM. d ' 'yy' ' hh:mm a');
return dateFormat.format(date);
}
bool isSameWeek(DateTime timestamp) =>
DateTime.now().difference(timestamp).inDays < 7;
class CupertinoCircleAvatar extends StatelessWidget {
final String? url;
final double? size;
const CupertinoCircleAvatar({Key? key, this.url, this.size})
: super(key: key);
@override
Widget build(BuildContext context) {
return ClipRRect(
borderRadius: BorderRadius.circular(size! / 2),
child: CachedNetworkImage(
imageUrl: url!,
height: size,
width: size,
fit: BoxFit.cover,
errorWidget: (context, url, error) {
//TODO: this crash the app when getting 404 and in debug mode, see :https://github.com/Baseflow/flutter_cached_network_image/issues/504
return CachedNetworkImage(
imageUrl:
'https://4.bp.blogspot.com/-Jx21kNqFSTU/UXemtqPhZCI/AAAAAAAAh74/BMGSzpU6F48/s1600/funny-cat-pictures-047-001.jp',
);
}),
);
}
}
class Divider extends StatelessWidget {
const Divider({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Expanded(
child: Align(
alignment: Alignment.bottomCenter,
child: Container(
height: 1,
color: CupertinoColors.systemGrey5,
),
),
);
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/imessage | mirrored_repositories/flutter-samples/packages/imessage/lib/channel_name_text.dart | import 'package:flutter/cupertino.dart';
import 'package:stream_chat_flutter_core/stream_chat_flutter_core.dart'
show Channel;
class ChannelNameText extends StatelessWidget {
const ChannelNameText({
Key? key,
required this.channel,
this.size = 17,
this.fontWeight,
}) : super(key: key);
final Channel channel;
final double size;
final FontWeight? fontWeight;
@override
Widget build(BuildContext context) {
return Text(
channel.extraData['name'] as String? ?? 'No name',
style: TextStyle(
fontSize: size,
fontWeight: fontWeight,
color: CupertinoColors.black,
),
);
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/imessage | mirrored_repositories/flutter-samples/packages/imessage/lib/message_header.dart | import 'package:flutter/cupertino.dart';
import 'package:imessage/utils.dart';
class MessageHeader extends StatelessWidget {
final String rawTimeStamp;
const MessageHeader({Key? key, required this.rawTimeStamp}) : super(key: key);
@override
Widget build(BuildContext context) {
final receivedAt = DateTime.parse(rawTimeStamp);
const textStyle = TextStyle(
color: CupertinoColors.systemGrey,
fontWeight: FontWeight.w400,
fontSize: 11,
);
return isSameWeek(receivedAt)
? Text(
formatDateSameWeek(receivedAt),
style: textStyle,
)
: Text(
formatDate(receivedAt),
style: textStyle,
);
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/imessage | mirrored_repositories/flutter-samples/packages/imessage/lib/message_input.dart | import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:image_picker/image_picker.dart';
import 'package:stream_chat_flutter_core/stream_chat_flutter_core.dart'
show Attachment, AttachmentFile, Message, StreamChannel;
class MessageInput extends StatefulWidget {
const MessageInput({
Key? key,
}) : super(key: key);
@override
_MessageInputState createState() => _MessageInputState();
}
class _MessageInputState extends State<MessageInput> {
final textController = TextEditingController();
final picker = ImagePicker();
@override
void initState() {
super.initState();
textController.addListener(() {
setState(() {});
});
}
@override
Widget build(BuildContext context) {
return Align(
alignment: FractionalOffset.bottomCenter,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 32.0),
child: Row(
children: [
GestureDetector(
onTap: () async {
final pickedFile =
await (picker.pickImage(source: ImageSource.gallery));
if (pickedFile == null) {
return;
}
final bytes = await File(pickedFile.path).readAsBytes();
final channel = StreamChannel.of(context).channel;
final message = Message(
text: textController.value.text,
attachments: [
Attachment(
type: 'image',
file: AttachmentFile(
bytes: bytes,
path: pickedFile.path,
size: bytes.length,
),
),
],
);
await channel.sendMessage(message);
},
child: const Padding(
padding: EdgeInsets.all(8.0),
child: Icon(
CupertinoIcons.camera_fill,
color: CupertinoColors.systemGrey,
size: 32,
),
),
),
Expanded(
child: CupertinoTextField(
controller: textController,
maxLines: 10,
minLines: 1,
onSubmitted: (input) async {
await sendMessage(context, input);
},
placeholder: 'iMessage',
padding:
const EdgeInsets.symmetric(vertical: 8, horizontal: 12),
suffixMode: OverlayVisibilityMode.editing,
suffix: GestureDetector(
onTap: () async {
if (textController.value.text.isNotEmpty) {
await sendMessage(context, textController.value.text);
textController.clear();
}
},
child: const Icon(
CupertinoIcons.arrow_up_circle_fill,
color: CupertinoColors.activeBlue,
size: 35,
),
),
decoration: BoxDecoration(
border: Border.all(color: CupertinoColors.systemGrey),
borderRadius: const BorderRadius.all(Radius.circular(35)),
),
),
),
],
),
),
);
}
Future<void> sendMessage(BuildContext context, String input) async {
final streamChannel = StreamChannel.of(context);
await streamChannel.channel.sendMessage(Message(text: input.trim()));
}
}
| 0 |
mirrored_repositories/flutter-samples/packages/imessage | mirrored_repositories/flutter-samples/packages/imessage/lib/main.dart | import 'package:flutter/cupertino.dart';
import 'package:intl/date_symbol_data_local.dart';
import 'package:imessage/channel_list_view.dart';
import 'package:imessage/channel_page_appbar.dart';
import 'package:stream_chat_flutter_core/stream_chat_flutter_core.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
final client = StreamChatClient('b67pax5b2wdq', logLevel: Level.INFO); //
// For demonstration purposes. Fixed user and token.
await client.connectUser(
User(
id: 'cool-shadow-7',
extraData: const {
'image':
'https://getstream.io/random_png/?id=cool-shadow-7&name=Cool+shadow',
},
),
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiY29vbC1zaGFkb3ctNyJ9.gkOlCRb1qgy4joHPaxFwPOdXcGvSPvp6QY0S4mpRkVo',
);
runApp(IMessage(client: client));
}
class IMessage extends StatelessWidget {
const IMessage({Key? key, required this.client}) : super(key: key);
final StreamChatClient client;
@override
Widget build(BuildContext context) {
initializeDateFormatting('en_US', null);
return CupertinoApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: const CupertinoThemeData(brightness: Brightness.light),
home: StreamChatCore(client: client, child: ChatLoader()),
);
}
}
class ChatLoader extends StatelessWidget {
ChatLoader({
Key? key,
}) : super(key: key);
final channelListController = ChannelListController();
@override
Widget build(BuildContext context) {
final user = StreamChatCore.of(context).currentUser!;
return CupertinoPageScaffold(
child: ChannelsBloc(
child: ChannelListCore(
channelListController: channelListController,
filter: Filter.and([
Filter.in_('members', [user.id]),
Filter.equal('type', 'messaging'),
]),
sort: const [SortOption('last_message_at')],
limit: 20,
emptyBuilder: (BuildContext context) {
return const Center(
child: Text('Looks like you are not in any channels'),
);
},
loadingBuilder: (BuildContext context) {
return const Center(
child: SizedBox(
height: 100.0,
width: 100.0,
child: CupertinoActivityIndicator(),
),
);
},
errorBuilder: (BuildContext context, dynamic error) {
return const Center(
child: Text(
'Oh no, something went wrong. Please check your config.'),
);
},
listBuilder: (
BuildContext context,
List<Channel> channels,
) =>
LazyLoadScrollView(
onEndOfPage: () async {
return channelListController.paginateData!();
},
child: CustomScrollView(
slivers: [
CupertinoSliverRefreshControl(onRefresh: () async {
return channelListController.loadData!();
}),
const ChannelPageAppBar(),
SliverPadding(
sliver: ChannelListView(channels: channels),
padding: const EdgeInsets.only(top: 16),
)
],
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/id_generator | mirrored_repositories/id_generator/lib/constants.dart | const MONGO_URL =
"mongodb+srv://anuragpdsgsoc:[email protected]/studentdb?retryWrites=true&w=majority";
const CRED_COLLECTION = "credentials";
| 0 |
mirrored_repositories/id_generator | mirrored_repositories/id_generator/lib/firebase_options.dart | // File generated by FlutterFire CLI.
// ignore_for_file: lines_longer_than_80_chars, avoid_classes_with_only_static_members
import 'package:firebase_core/firebase_core.dart' show FirebaseOptions;
import 'package:flutter/foundation.dart'
show defaultTargetPlatform, kIsWeb, TargetPlatform;
/// Default [FirebaseOptions] for use with your Firebase apps.
///
/// Example:
/// ```dart
/// import 'firebase_options.dart';
/// // ...
/// await Firebase.initializeApp(
/// options: DefaultFirebaseOptions.currentPlatform,
/// );
/// ```
class DefaultFirebaseOptions {
static FirebaseOptions get currentPlatform {
if (kIsWeb) {
throw UnsupportedError(
'DefaultFirebaseOptions have not been configured for web - '
'you can reconfigure this by running the FlutterFire CLI again.',
);
}
switch (defaultTargetPlatform) {
case TargetPlatform.android:
return android;
case TargetPlatform.iOS:
return ios;
case TargetPlatform.macOS:
throw UnsupportedError(
'DefaultFirebaseOptions have not been configured for macos - '
'you can reconfigure this by running the FlutterFire CLI again.',
);
case TargetPlatform.windows:
throw UnsupportedError(
'DefaultFirebaseOptions have not been configured for windows - '
'you can reconfigure this by running the FlutterFire CLI again.',
);
case TargetPlatform.linux:
throw UnsupportedError(
'DefaultFirebaseOptions have not been configured for linux - '
'you can reconfigure this by running the FlutterFire CLI again.',
);
default:
throw UnsupportedError(
'DefaultFirebaseOptions are not supported for this platform.',
);
}
}
static const FirebaseOptions android = FirebaseOptions(
apiKey: 'AIzaSyBIjyknokmMjjZff7pV58iLq0H_4GyUvKs',
appId: '1:29601348897:android:7eb5901989a0118b13d260',
messagingSenderId: '29601348897',
projectId: 'id-generator-app',
storageBucket: 'id-generator-app.appspot.com',
);
static const FirebaseOptions ios = FirebaseOptions(
apiKey: 'AIzaSyA318rdCaLY6bRGmFLYSsj_SV_LMHofF30',
appId: '1:29601348897:ios:1262dc1d3d5f5bec13d260',
messagingSenderId: '29601348897',
projectId: 'id-generator-app',
storageBucket: 'id-generator-app.appspot.com',
iosBundleId: 'com.example.idGenerator',
);
}
| 0 |
mirrored_repositories/id_generator | mirrored_repositories/id_generator/lib/main.dart | // ignore_for_file: unused_import
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:id_generator/features/admin/createEvent/ui/create_event.dart';
import 'package:id_generator/pages/adminHome.dart';
import 'package:id_generator/pages/createEventScreen.dart';
import 'package:id_generator/pages/login.dart';
import 'package:id_generator/pages/student_qr.dart';
import 'pages/checklocation.dart';
import 'pages/qr_scanner.dart';
import 'pages/authentication_login.dart';
import 'pages/generate_qr_code.dart';
import 'package:mac_address/mac_address.dart';
import './firebase_options.dart';
import './pages/verify_otp.dart';
import './pages/signup.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'pages/otp_screen.dart';
// import './src/repository/authentication_repository/authentication_repository.dart';
import './pages/student_home.dart';
import 'pages/splash.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await GetStorage.init();
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return GetMaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: CreateEvent(),
// home: const AdminHome(),
);
}
}
| 0 |
mirrored_repositories/id_generator/lib/features/admin/createEvent | mirrored_repositories/id_generator/lib/features/admin/createEvent/models/event_model.dart | class CreateEventModel {
final String eventTitle;
final String eventDescription;
final String eventAddress;
final String eventStartDate;
final String eventEndDate;
final String eventStartTime;
final String eventEndTime;
CreateEventModel({
required this.eventTitle,
required this.eventDescription,
required this.eventAddress,
required this.eventStartDate,
required this.eventEndDate,
required this.eventStartTime,
required this.eventEndTime,
});
}
| 0 |
mirrored_repositories/id_generator/lib/features/admin/createEvent | mirrored_repositories/id_generator/lib/features/admin/createEvent/bloc/create_event_state.dart | part of 'create_event_bloc.dart';
@immutable
abstract class CreateEventState {}
abstract class CreateEventActionState extends CreateEventState {}
class CreateEventInitial extends CreateEventState {}
class SelectEventStartDateActionState extends CreateEventActionState {}
class SelectEventEndDateActionState extends CreateEventActionState {}
class SelectEventStartTimeActionState extends CreateEventActionState {}
class SelectEventEndTimeActionState extends CreateEventActionState {}
| 0 |
mirrored_repositories/id_generator/lib/features/admin/createEvent | mirrored_repositories/id_generator/lib/features/admin/createEvent/bloc/create_event_event.dart | part of 'create_event_bloc.dart';
@immutable
abstract class CreateEventEvent {}
class SelectStartDateButtonClickedEvent extends CreateEventEvent {}
class SelectEndDateButtonClickedEvent extends CreateEventEvent {}
class SelectStartTimeButtonClickedEvent extends CreateEventEvent {}
class SelectEndTimeButtonClickedEvent extends CreateEventEvent {}
class CreateEventButtonClickedEvent extends CreateEventEvent {}
| 0 |
mirrored_repositories/id_generator/lib/features/admin/createEvent | mirrored_repositories/id_generator/lib/features/admin/createEvent/bloc/view_event_state.dart | part of 'view_event_bloc.dart';
@immutable
abstract class ViewEventState {}
abstract class ViewEventActionState extends ViewEventState {}
class ViewEventInitial extends ViewEventState {}
class EventLoadingState extends ViewEventState {}
class EventLoadedSuccessState extends ViewEventState {}
class EventErrorState extends ViewEventState {}
class EventEditedState extends ViewEventState {}
class EventDeletedState extends ViewEventState {}
class EventEditActionState extends ViewEventActionState {}
class EventDeleteActionState extends ViewEventActionState {}
| 0 |
mirrored_repositories/id_generator/lib/features/admin/createEvent | mirrored_repositories/id_generator/lib/features/admin/createEvent/bloc/view_event_bloc.dart | import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:flutter/material.dart';
part 'view_event_event.dart';
part 'view_event_state.dart';
class ViewEventBloc extends Bloc<ViewEventEvent, ViewEventState> {
ViewEventBloc() : super(ViewEventInitial()) {}
}
| 0 |
mirrored_repositories/id_generator/lib/features/admin/createEvent | mirrored_repositories/id_generator/lib/features/admin/createEvent/bloc/view_event_event.dart | part of 'view_event_bloc.dart';
@immutable
abstract class ViewEventEvent {}
class EditEventButtonClickedEvent extends ViewEventEvent {}
class DeleteEventButtonClickedEvent extends ViewEventEvent {}
| 0 |
mirrored_repositories/id_generator/lib/features/admin/createEvent | mirrored_repositories/id_generator/lib/features/admin/createEvent/bloc/create_event_bloc.dart | import 'dart:async';
import 'package:bloc/bloc.dart';
import 'package:flutter/material.dart';
part 'create_event_event.dart';
part 'create_event_state.dart';
class CreateEventBloc extends Bloc<CreateEventEvent, CreateEventState> {
CreateEventBloc() : super(CreateEventInitial()) {
on<SelectStartDateButtonClickedEvent>(selectStartDateButtonClickedEvent);
on<SelectEndDateButtonClickedEvent>(selectEndDateButtonClickedEvent);
on<SelectStartTimeButtonClickedEvent>(selectStartTimeButtonClickedEvent);
on<SelectEndTimeButtonClickedEvent>(selectEndTimeButtonClickedEvent);
}
FutureOr<void> selectStartDateButtonClickedEvent(
SelectStartDateButtonClickedEvent event, Emitter<CreateEventState> emit) {
debugPrint("Select Start Date Button Clicked ! ");
emit(SelectEventStartDateActionState());
}
FutureOr<void> selectEndDateButtonClickedEvent(
SelectEndDateButtonClickedEvent event, Emitter<CreateEventState> emit) {
emit(SelectEventEndDateActionState());
debugPrint("Select End Date Button Clicked ! ");
}
FutureOr<void> selectStartTimeButtonClickedEvent(
SelectStartTimeButtonClickedEvent event, Emitter<CreateEventState> emit) {
debugPrint("Select Start Time Button Clicked ! ");
emit(SelectEventStartTimeActionState());
}
FutureOr<void> selectEndTimeButtonClickedEvent(
SelectEndTimeButtonClickedEvent event, Emitter<CreateEventState> emit) {
debugPrint("Select End Button Clicked ! ");
emit(SelectEventEndTimeActionState());
}
}
| 0 |
mirrored_repositories/id_generator/lib/features/admin/createEvent | mirrored_repositories/id_generator/lib/features/admin/createEvent/ui/create_event.dart | import 'package:flutter/material.dart';
import 'package:id_generator/features/admin/createEvent/bloc/create_event_bloc.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
class CreateEvent extends StatefulWidget {
const CreateEvent({super.key});
@override
State<CreateEvent> createState() => _CreateEventState();
}
class _CreateEventState extends State<CreateEvent> {
final CreateEventBloc createEventBloc = CreateEventBloc();
@override
Widget build(BuildContext context) {
return BlocConsumer<CreateEventBloc, CreateEventState>(
bloc: createEventBloc,
listenWhen: (previous, current) => current is CreateEventActionState,
buildWhen: (previous, current) => current is! CreateEventActionState,
listener: (context, state) {
if (state is SelectEventStartDateActionState) {}
},
builder: (context, state) {
return Scaffold(
body: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton(
onPressed: () {
createEventBloc.add(
SelectStartDateButtonClickedEvent(),
);
},
child: const Text("SelectStartDate"),
),
ElevatedButton(
onPressed: () {
createEventBloc.add(
SelectEndDateButtonClickedEvent(),
);
},
child: const Text("SelectEndDate"),
)
],
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton(
onPressed: () {
createEventBloc.add(
SelectStartTimeButtonClickedEvent(),
);
},
child: const Text("SelectStartTime"),
),
ElevatedButton(
onPressed: () {
createEventBloc.add(
SelectEndTimeButtonClickedEvent(),
);
},
child: const Text("SelectEndTime"),
)
],
)
],
),
),
);
},
);
}
}
| 0 |
mirrored_repositories/id_generator/lib/features/admin/createEvent | mirrored_repositories/id_generator/lib/features/admin/createEvent/ui/view_events.dart | import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:id_generator/features/admin/createEvent/bloc/view_event_bloc.dart';
import '../bloc/create_event_bloc.dart';
class ViewEvents extends StatefulWidget {
const ViewEvents({super.key});
@override
State<ViewEvents> createState() => _ViewEventsState();
}
class _ViewEventsState extends State<ViewEvents> {
final ViewEventBloc viewEventBloc = ViewEventBloc();
@override
Widget build(BuildContext context) {
return BlocConsumer<ViewEventBloc, ViewEventState>(
bloc: viewEventBloc,
listener: (context, state) {},
builder: (context, state) {
return Scaffold(
body: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
ElevatedButton.icon(
onPressed: () {},
icon: const Icon(Icons.edit_calendar_outlined),
label: const Text("Edit "),
),
ElevatedButton.icon(
onPressed: () {},
icon: const Icon(Icons.delete),
label: const Text("Edit "),
),
],
)),
);
},
);
}
}
| 0 |
mirrored_repositories/id_generator/lib/features/admin/viewEvents | mirrored_repositories/id_generator/lib/features/admin/viewEvents/bloc/view_events_state.dart | part of 'view_events_bloc.dart';
@immutable
abstract class ViewEventsState {}
abstract class ViewEventsActionState {}
class ViewEventsInitial extends ViewEventsState {}
class ViewEventsLoadingState extends ViewEventsState {}
class ViewEventsLoadedSuccessState extends ViewEventsState {
final List<CreateEventModel> events;
ViewEventsLoadedSuccessState({required this.events});
}
class ViewEventsErrorState extends ViewEventsState {}
| 0 |
mirrored_repositories/id_generator/lib/features/admin/viewEvents | mirrored_repositories/id_generator/lib/features/admin/viewEvents/bloc/view_events_bloc.dart | import 'package:bloc/bloc.dart';
import 'package:id_generator/features/admin/createEvent/models/event_model.dart';
import 'package:id_generator/features/admin/createEvent/ui/create_event.dart';
import 'package:meta/meta.dart';
part 'view_events_event.dart';
part 'view_events_state.dart';
class ViewEventsBloc extends Bloc<ViewEventsEvent, ViewEventsState> {
ViewEventsBloc() : super(ViewEventsInitial()) {
on<ViewEventsEvent>((event, emit) {
// TODO: implement event handler
});
}
}
| 0 |
mirrored_repositories/id_generator/lib/features/admin/viewEvents | mirrored_repositories/id_generator/lib/features/admin/viewEvents/bloc/view_events_event.dart | part of 'view_events_bloc.dart';
@immutable
abstract class ViewEventsEvent {}
| 0 |
mirrored_repositories/id_generator/lib | mirrored_repositories/id_generator/lib/pages/student_qr.dart | // import 'dart:io';
// import 'package:cloud_firestore/cloud_firestore.dart';
// import 'package:firebase_storage/firebase_storage.dart';
// import 'package:flutter/material.dart';
// import 'package:get/get.dart';
// import 'package:id_generator/pages/verify_otp.dart';
// import 'package:qr_flutter/qr_flutter.dart';
// import 'package:shared_preferences/shared_preferences.dart';
// import 'package:uuid/uuid.dart';
// import 'login.dart';
// class StudentQR extends StatelessWidget {
// // final String data;
// // final String phone;
// // final String name;
// // final File file;
// StudentQR({
// Key? key,
// // required this.data,
// // required this.file,
// // required this.name,
// // required this.phone
// }) : super(key: key);
// String uuid = "";
// String phoneNo = "";
// String fullName = "";
// String url = "";
// getData() async {
// final SharedPreferences prefs = await SharedPreferences.getInstance();
// uuid = prefs.getString('uuid')!;
// final ref = FirebaseStorage.instance
// .ref()
// .child("1512e538-d558-4f9d-947c-38a0227b32bc");
// QuerySnapshot snapshot = await FirebaseFirestore.instance
// .collection('credentials')
// .where('uuid', isEqualTo: uuid)
// .get();
// url = await ref.getDownloadURL();
// debugPrint(url);
// if (snapshot.docs.isNotEmpty) {
// for (QueryDocumentSnapshot document in snapshot.docs) {
// Map<String, dynamic> data = document.data() as Map<String, dynamic>;
// fullName = data['fullname'];
// phoneNo = data['phonenumber'];
// }
// } else {
// // ignore: use_build_context_synchronously
// }
// }
// @override
// Widget build(BuildContext context) {
// return Scaffold(
// backgroundColor: Colors.deepPurple[50],
// appBar: AppBar(
// title: const Text("Welcome "),
// ),
// body: SafeArea(
// child: SingleChildScrollView(
// child: SizedBox(
// width: double.infinity,
// child: Column(
// children: [
// const SizedBox(
// height: 30,
// ),
// Container(
// height: 370,
// width: 370,
// decoration: BoxDecoration(color: Colors.deepPurple[100]),
// child: QrImageView(
// data: uuid,
// ),
// ),
// Container(
// width: double.infinity,
// height: 150,
// margin: const EdgeInsets.all(20),
// decoration: BoxDecoration(
// border: Border.all(color: Colors.grey),
// color: Colors.deepPurple[100],
// borderRadius: BorderRadius.circular(10)),
// child: Row(
// mainAxisAlignment: MainAxisAlignment.start,
// crossAxisAlignment: CrossAxisAlignment.center,
// children: [
// Container(
// height: 150,
// width: 150,
// padding: const EdgeInsets.all(20),
// child: ClipRRect(
// borderRadius: BorderRadius.circular(10),
// child: Image.network(
// url,
// scale: 1.0,
// fit: BoxFit.cover,
// ),
// ),
// ),
// SizedBox(
// height: 110,
// child: Column(
// crossAxisAlignment: CrossAxisAlignment.start,
// children: [
// Container(
// child: Text(
// fullName,
// // "Anurag Dandge",
// style: const TextStyle(
// fontSize: 25, fontWeight: FontWeight.bold),
// )),
// Container(child: Text(phoneNo)),
// ],
// ),
// )
// ],
// ),
// ),
// TextButton(
// onPressed: () async {
// Get.to(() => const LoginScreen());
// final SharedPreferences prefs =
// await SharedPreferences.getInstance();
// await prefs.setBool('isLoggedIn', false);
// debugPrint("User Logged Out ");
// },
// child: const Text("Logout"))
// ],
// ),
// ),
// )),
// );
// }
// }
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:id_generator/pages/login.dart';
import 'package:shared_preferences/shared_preferences.dart';
class StudentQR extends StatefulWidget {
const StudentQR({Key? key}) : super(key: key);
@override
State<StudentQR> createState() => _StudentQRState();
}
class _StudentQRState extends State<StudentQR> {
String imgUrl = '';
final storage = FirebaseStorage.instance;
@override
void initState() {
// TODO: implement initState
super.initState();
imgUrl = '';
getImageUrl();
}
Future<void> getImageUrl() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
final uuid = prefs.getString('uuid');
final ref = storage.ref().child(uuid!);
final url = await ref.getDownloadURL();
setState(() {
imgUrl = url;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Welcome "),
actions: [
Padding(
padding: const EdgeInsets.all(8.0),
child: IconButton(
icon: const Icon(Icons.logout),
onPressed: () async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool('isLoggedIn', false);
debugPrint(" Logged Out ");
Navigator.pop(context);
Get.to(() => const LoginScreen());
},
),
)
],
),
body: SafeArea(
child: SingleChildScrollView(
child: Column(
children: [
Image(
image: NetworkImage(imgUrl),
fit: BoxFit.cover,
)
],
),
),
),
);
}
}
| 0 |
mirrored_repositories/id_generator/lib | mirrored_repositories/id_generator/lib/pages/checklocation.dart | import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:geocoding/geocoding.dart';
class CheckLocation extends StatefulWidget {
const CheckLocation({super.key});
@override
State<CheckLocation> createState() => _CheckLocationState();
}
class _CheckLocationState extends State<CheckLocation> {
Position? _currentLocation;
late bool servicePermission = false;
late LocationPermission permission;
String currentAddress = "";
double distance = 0.0;
Future<Position> _getCurrentLocation() async {
servicePermission = await Geolocator.isLocationServiceEnabled();
if (!servicePermission) {
debugPrint("Service Disabled ");
}
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
}
return await Geolocator.getCurrentPosition();
}
_getAddressFromCoOrdinates() async {
try {
List<Placemark> placemarks = await placemarkFromCoordinates(
_currentLocation!.latitude, _currentLocation!.longitude);
Placemark place = placemarks[0];
setState(() {
currentAddress = "${place.locality}";
});
} catch (e) {
print(e);
}
}
_checkDistance() {
double dis = Geolocator.distanceBetween(
_currentLocation!.latitude,
// _currentLocation!.longitude, 18.5050084, 73.8123033);
_currentLocation!.longitude,
18.525713,
73.845745);
setState(() {
distance = dis;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(children: [
Center(
child: Column(
children: [
ElevatedButton(
onPressed: () async {
if (_currentLocation != null) {
debugPrint(" Location is Null");
} else {
_currentLocation = await _getCurrentLocation();
await _getAddressFromCoOrdinates();
_checkDistance();
}
debugPrint("${_currentLocation?.latitude}");
debugPrint("${_currentLocation?.longitude}");
},
child: const Text("Get Location "),
),
Text("Latitude : ${_currentLocation?.latitude}"),
Text("Longitude : ${_currentLocation?.longitude}"),
Text("Address : $currentAddress"),
Text("Distance : ${distance.toInt()} Meters "),
],
)),
]),
),
);
}
}
| 0 |
mirrored_repositories/id_generator/lib | mirrored_repositories/id_generator/lib/pages/adminHome.dart | // ignore_for_file: file_names
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:id_generator/pages/login.dart';
import 'package:id_generator/pages/viewEvents.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../animations/slideRight.dart';
import 'createEventScreen.dart';
class AdminHome extends StatefulWidget {
const AdminHome({super.key});
@override
State<AdminHome> createState() => _AdminHomeState();
}
class _AdminHomeState extends State<AdminHome> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Admin Dashboard"),
actions: [
IconButton(
onPressed: () async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool('isLoggedIn', false);
Navigator.pop(context);
Get.to(() => const LoginScreen());
},
icon: const Padding(
padding: EdgeInsets.all(8),
child: Icon(Icons.logout),
),
)
],
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.center,
// mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child: Container(
padding: const EdgeInsets.all(24.0),
margin: const EdgeInsets.all(16.0),
width: double.infinity,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
boxShadow: const [
BoxShadow(
color: Colors.grey,
blurRadius: 10,
spreadRadius: -2,
offset: Offset(0, 10))
]),
child: Column(
children: [
SvgPicture.asset(
'./assets/images/createEvent.svg',
height: 150,
width: double.infinity,
),
const SizedBox(
height: 24,
),
ElevatedButton(
style: ButtonStyle(
shape: MaterialStatePropertyAll(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
backgroundColor:
const MaterialStatePropertyAll(Colors.white),
minimumSize:
const MaterialStatePropertyAll(Size.fromHeight(50.0)),
),
onPressed: () {
Navigator.push(context,
SlideRightRoute(page: const CreateEventScreen()));
},
child: const Text(
" Create Event ",
style: TextStyle(fontSize: 25),
),
)
],
),
),
),
Center(
child: Container(
padding: const EdgeInsets.all(24.0),
margin: const EdgeInsets.all(16.0),
width: double.infinity,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(10),
boxShadow: const [
BoxShadow(
color: Colors.grey,
blurRadius: 10,
spreadRadius: -2,
offset: Offset(0, 10))
]),
child: Column(
children: [
SvgPicture.asset(
'./assets/images/viewEvents.svg',
height: 150,
width: double.infinity,
),
const SizedBox(
height: 24,
),
ElevatedButton(
style: ButtonStyle(
shape: MaterialStatePropertyAll(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10.0),
),
),
backgroundColor:
const MaterialStatePropertyAll(Colors.white),
minimumSize:
const MaterialStatePropertyAll(Size.fromHeight(50.0)),
),
onPressed: () {
Navigator.push(context,
SlideRightRoute(page: const ViewEventsScreen()));
},
child: const Text(
" View Events ",
style: TextStyle(fontSize: 25),
),
)
],
),
),
),
],
),
//
);
}
}
| 0 |
mirrored_repositories/id_generator/lib | mirrored_repositories/id_generator/lib/pages/qr_scanner.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_barcode_scanner/flutter_barcode_scanner.dart';
import 'package:qr_flutter/qr_flutter.dart';
class ScanQR extends StatefulWidget {
const ScanQR({super.key});
@override
State<ScanQR> createState() => _ScanQRState();
}
class _ScanQRState extends State<ScanQR> {
String _scannedQrResult = "Empty"; // Provide a default empty string
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
centerTitle: true,
title: const Text(
"Scan QR Code ",
style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
),
),
body: SafeArea(
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.start,
children: [
const SizedBox(
height: 30,
),
Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: Colors.deepPurple[100]),
child: QrImageView(
data: _scannedQrResult,
backgroundColor: Colors.white,
size: 300,
),
),
const SizedBox(
height: 30,
),
Center(
child: ElevatedButton(
style:
const ButtonStyle(elevation: MaterialStatePropertyAll(10)),
onPressed: scanQRCode,
child: const Padding(
padding: EdgeInsets.only(left: 50, right: 50),
child: Text(
"Scan",
style: TextStyle(fontSize: 30),
),
))),
const SizedBox(
height: 20,
),
Padding(
padding: const EdgeInsets.all(20.0),
child: Text(
"Scanned Res : \n $_scannedQrResult",
style: const TextStyle(fontSize: 20),
),
),
],
),
),
),
);
}
Future<void> scanQRCode() async {
String qrCodeRes;
try {
qrCodeRes = await FlutterBarcodeScanner.scanBarcode(
'#ff6666', 'Cancel', true, ScanMode.QR);
debugPrint(qrCodeRes);
} on PlatformException {
qrCodeRes = "Failed to get platform version ";
}
if (!mounted) return;
setState(() {
_scannedQrResult = qrCodeRes; // Assign the value directly
});
}
}
| 0 |
mirrored_repositories/id_generator/lib | mirrored_repositories/id_generator/lib/pages/generate_qr_code.dart | import 'package:flutter/material.dart';
import 'package:qr_flutter/qr_flutter.dart';
class GenerateQR extends StatelessWidget {
final String data;
const GenerateQR({Key? key, required this.data}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: const Icon(
Icons.qr_code_2,
size: 40,
),
title: const Text(
" Generated QR Code ",
style: TextStyle(fontSize: 30),
),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Center(
child: QrImageView(
data: data,
backgroundColor: const Color.fromARGB(255, 193, 132, 255),
),
),
Text(" scanned : $data")
],
));
}
}
| 0 |
mirrored_repositories/id_generator/lib | mirrored_repositories/id_generator/lib/pages/otp_screen.dart | import 'package:flutter/material.dart';
import 'package:pinput/pinput.dart';
class OtpScreen extends StatefulWidget {
const OtpScreen({super.key});
@override
State<OtpScreen> createState() => _OtpScreenState();
}
class _OtpScreenState extends State<OtpScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text("Verification"),
Pinput(
length: 6,
showCursor: true,
defaultPinTheme: PinTheme(
width: 60,
height: 60,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
border: Border.all(color: Colors.purple.shade200),
),
textStyle:
const TextStyle(fontSize: 20, fontWeight: FontWeight.w600),
),
onSubmitted: (value) {
setState(() {});
},
)
],
),
);
}
}
| 0 |
mirrored_repositories/id_generator/lib | mirrored_repositories/id_generator/lib/pages/viewEvents.dart | import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:lottie/lottie.dart';
class ViewEventsScreen extends StatefulWidget {
const ViewEventsScreen({super.key});
@override
State<ViewEventsScreen> createState() => _ViewEventsScreenState();
}
class _ViewEventsScreenState extends State<ViewEventsScreen> {
@override
void initState() {
super.initState();
_getEvents();
}
final List<String> roles = [
'Participant',
'Volunteer',
'Co-Ordinator',
'Head Co-Ordinator',
];
String? _selectedRole;
late List<Map<String, dynamic>> events = [];
bool isLoaded = false;
bool isEditing = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(" Events "),
actions: [
IconButton(onPressed: _getEvents, icon: const Icon(Icons.refresh))
],
),
body:
// events.isEmpty
// ? Center(
// child: Column(
// mainAxisAlignment: MainAxisAlignment.center,
// children: [
// LottieBuilder.asset('./assets/lotties/noEvent.json'),
// const Text.rich(TextSpan(
// text: "No Events ",
// style:
// TextStyle(fontSize: 50, fontWeight: FontWeight.w500)))
// ],
// ))
// :
isLoaded
? events.isEmpty
? Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
LottieBuilder.asset('./assets/lotties/noEvent.json'),
const Text.rich(TextSpan(
text: "No Events ",
style: TextStyle(
fontSize: 50, fontWeight: FontWeight.w500)))
],
),
)
: ListView.builder(
itemCount: events.length,
itemBuilder: (context, index) {
return Container(
width: double.infinity,
margin: const EdgeInsets.all(16.0),
padding: const EdgeInsets.all(16.0),
decoration: BoxDecoration(
color: Colors.deepPurple[100],
borderRadius: BorderRadius.circular(20)),
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Text(
events[index]['eventTitle'] ??
" Loading...",
style: const TextStyle(
fontSize: 30,
fontWeight: FontWeight.bold,
),
),
// isEditing
// ? IconButton(
// onPressed: () {
// setState(() {
// isEditing = false;
// });
// },
// icon: const Icon(
// Icons.done,
// size: 32,
// semanticLabel: "Edit Event",
// ),
// style: const ButtonStyle(),
// ):
IconButton(
onPressed: () {
// showDialog(
// context: context,
// builder: (context) => const AlertDialog(
// title: Text("Edit Event "),
// // content: Form(child: Column(
// // )),
// ),
// );
editEvent(events[index]['uuid'], index);
setState(() {
isEditing = true;
});
},
icon: const Icon(
Icons.edit_calendar_outlined,
size: 32,
semanticLabel: "Edit Event",
),
style: const ButtonStyle(),
)
],
),
const Divider(
color: Colors.black,
thickness: 2,
),
Text(
events[index]['eventDescription'],
style: const TextStyle(
fontSize: 17,
fontWeight: FontWeight.w400,
),
),
const SizedBox(
height: 10,
),
const Text(
"Date",
style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.w500,
),
),
SizedBox(
child: Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Text(
events[index]['eventStartDate'] +
" to " +
events[index]['eventEndDate'],
style: const TextStyle(
fontWeight: FontWeight.w400,
fontSize: 20,
color: Colors.black54),
),
],
),
),
const SizedBox(
height: 10,
),
const Text(
"Timing ",
style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.w500,
),
),
SizedBox(
child: Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Text(
events[index]['eventStartTime'] +
" to " +
events[index]['eventEndTime'],
style: const TextStyle(
fontWeight: FontWeight.w400,
fontSize: 20,
color: Colors.black54),
),
],
),
),
const SizedBox(
height: 10,
),
const Text(
"Location ",
style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.w500,
),
),
Text(
events[index]['eventAddress'],
style: const TextStyle(
fontWeight: FontWeight.w400, fontSize: 20),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
IconButton(
onPressed: () => deleteEvent(index),
icon: const Icon(
Icons.delete,
size: 32,
),
),
],
),
// ElevatedButton(
// onPressed: () {
// showDialog(
// context: context,
// builder: (context) => AlertDialog(
// title: Text(
// "Registering for ${events[index]['eventTitle']} event "),
// content: Form(
// child: DropdownMenu<String>(
// initialSelection: "Participant",
// onSelected: (String? value) {
// // This is called when the user selects an item.
// setState(() {
// _selectedRole = value!;
// });
// },
// leadingIcon: const Icon(Icons.person),
// label: const Text(" Select Role "),
// dropdownMenuEntries: roles
// .map<DropdownMenuEntry<String>>(
// (String value) {
// return DropdownMenuEntry<String>(
// value: value,
// label: value,
// );
// }).toList(),
// ),
// ),
// actions: [
// TextButton(
// onPressed: () => Navigator.pop(context),
// child: const Text(" Close "),
// ),
// ElevatedButton(
// onPressed: () => Navigator.pop(context),
// style: ButtonStyle(
// backgroundColor:
// MaterialStatePropertyAll(
// Colors.deepPurple[100])),
// child: const Text(
// " Register",
// style: TextStyle(
// fontWeight: FontWeight.bold),
// ),
// )
// ],
// ),
// );
// },
// child: const Text("Register For Event "),
// )
],
),
);
},
)
: const Center(
child: CircularProgressIndicator.adaptive(
strokeWidth: 10.0,
),
),
);
}
Future<void> _getEvents() async {
var collection = FirebaseFirestore.instance.collection('events');
var data = await collection.get();
late List<Map<String, dynamic>> tempList = [];
for (var element in data.docs) {
tempList.add(element.data());
}
setState(() {
events = tempList;
isLoaded = true;
});
}
void editEvent(String uuid, int index) {
debugPrint(uuid);
debugPrint("$index");
setState(() {});
}
void deleteEvent(int index) async {
debugPrint(" Deleting Event .... ");
showDialog(
context: context,
builder: (context) => AlertDialog(
title: const Text("Are you Sure ? "),
content: Row(
mainAxisSize: MainAxisSize.max,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
ElevatedButton(
onPressed: () {
Navigator.pop(context);
},
child: const Text("Cancel "),
),
ElevatedButton(
onPressed: () async {
QuerySnapshot snapshot = await FirebaseFirestore.instance
.collection('events')
.where('uuid', isEqualTo: events[index]['uuid'])
.get();
var id = snapshot.docs[0].id;
await FirebaseFirestore.instance
.collection('events')
.doc(id)
.delete();
Navigator.pop(context);
debugPrint(" Event Deleted !!! ");
_getEvents();
},
child: const Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Icon(Icons.delete),
Text("Delete "),
],
),
)
],
),
));
}
}
| 0 |
mirrored_repositories/id_generator/lib | mirrored_repositories/id_generator/lib/pages/student_home.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:lottie/lottie.dart';
import 'package:mac_address/mac_address.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'login.dart';
class StudentHome extends StatefulWidget {
const StudentHome({super.key});
@override
State<StudentHome> createState() => _StudentHomeState();
}
class _StudentHomeState extends State<StudentHome> {
String _platformVersion = 'Unknown';
String uuid = '';
String name = '';
String phone = '';
@override
void initState() {
super.initState();
initPlatformState();
}
Future<void> initPlatformState() async {
String platformVersion;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
platformVersion = await GetMac.macAddress;
} on PlatformException {
platformVersion = 'Failed to get Device MAC Address.';
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_platformVersion = platformVersion;
});
}
void getSharedPrefs() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
debugPrint(prefs.getString("uuid"));
debugPrint(prefs.getString("phone"));
debugPrint(prefs.getString("name"));
setState(() {
uuid = prefs.getString("uuid")!;
phone = prefs.getString("phone")!;
name = prefs.getString("name")!;
});
}
@override
Widget build(BuildContext context) {
// return Scaffold(
// backgroundColor: Colors.purpleAccent,
// body: Lottie.asset(
// 'assets/lotties/splash.json',
// ),
// );
return Scaffold(
appBar: AppBar(
actions: [
Padding(
padding: const EdgeInsets.all(8),
child: IconButton(
onPressed: () async {
final SharedPreferences prefs =
await SharedPreferences.getInstance();
await prefs.setBool('isLoggedIn', false);
Navigator.pop(context);
// setState(() {});
debugPrint(" User Logged Out !!!");
Get.to(() => const LoginScreen());
},
icon: const Icon(Icons.logout)),
),
],
title: const Text("Welcome "),
),
body: SingleChildScrollView(
child: Column(
children: [
ElevatedButton(
onPressed: () {},
child: const Text("Get SharedPrefs "),
),
Text("UUID = $uuid"),
Text("Phone = $phone"),
Text("Name = $name"),
],
),
),
);
}
}
| 0 |
mirrored_repositories/id_generator/lib | mirrored_repositories/id_generator/lib/pages/splash.dart | import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:id_generator/pages/adminHome.dart';
import 'package:id_generator/pages/login.dart';
import 'package:id_generator/pages/student_home.dart';
import 'package:lottie/lottie.dart';
import 'package:shared_preferences/shared_preferences.dart';
class SplashScreen extends StatefulWidget {
const SplashScreen({super.key});
@override
State<SplashScreen> createState() => _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> {
@override
void initState() {
super.initState();
startTime();
}
@override
Widget build(BuildContext context) {
return initScreen(context);
}
startTime() async {
var duration = const Duration(seconds: 7);
return Timer(duration, route);
}
route() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
bool isLoggedIn = prefs.getBool('isLoggedIn') ?? false;
print("Is User Already Logged in : $isLoggedIn");
Navigator.pop(context);
Get.to(() => isLoggedIn ? const AdminHome() : const LoginScreen());
}
gotoHome() {}
initScreen(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Lottie.asset('assets/lotties/splash.json', fit: BoxFit.cover),
],
),
);
}
}
| 0 |
mirrored_repositories/id_generator/lib | mirrored_repositories/id_generator/lib/pages/verify_otp.dart | // ignore_for_file: avoid_print
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:id_generator/animations/shake-widget.dart';
import 'package:id_generator/pages/signup.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:get/get.dart';
class VerifyPhoneScreen extends StatefulWidget {
const VerifyPhoneScreen({super.key});
@override
State<VerifyPhoneScreen> createState() => _VerifyPhoneScreenState();
}
class _VerifyPhoneScreenState extends State<VerifyPhoneScreen> {
late Size mediaSize;
late Color myColor;
TextEditingController phoneController = TextEditingController();
final TextEditingController _codeController = TextEditingController();
String smsCode = "";
bool rememberUser = false;
final _formKey = GlobalKey<FormState>();
final shakeKey = GlobalKey<ShakeWidgetState>();
RegExp passValid = RegExp(r"(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*\W)");
RegExp phoneValid = RegExp(r"^\+?[0-9]{10,12}$");
bool validatePassword(String pass) {
String password = pass.trim();
if (passValid.hasMatch(password)) {
return true;
} else {
return false;
}
}
bool validatePhoneNumber(String phone) {
String phoneNumber = phone.trim();
if (phoneValid.hasMatch(phoneNumber)) {
return true;
} else {
return false;
}
}
final FirebaseAuth _auth = FirebaseAuth.instance;
_verifyPhoneNumber(String phone) async {
debugPrint(" Phone Number Entered ");
try {
await _auth.verifyPhoneNumber(
phoneNumber: phone.trim(),
verificationCompleted: (PhoneAuthCredential authCredential) async {
await _auth.signInWithCredential(authCredential).then((value) {
debugPrint("verificationCompleted...");
});
},
verificationFailed: (((error) {
print("Verification Failed $error");
debugPrint("verificationFailed !!! ");
})),
codeSent: (String verificationId, [int? forceResendingToken]) {
debugPrint("CodeSent...");
showDialog(
context: context,
barrierDismissible: false,
builder: (context) => AlertDialog(
title: const Text("Enter OTP"),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextFormField(
controller: _codeController,
keyboardType: TextInputType.number)
],
),
actions: [
ElevatedButton(
onPressed: () {
debugPrint("OTP Entered !!!");
FirebaseAuth auth = FirebaseAuth.instance;
smsCode = _codeController.text;
PhoneAuthCredential credential =
PhoneAuthProvider.credential(
verificationId: verificationId,
smsCode: smsCode);
auth
.signInWithCredential(credential)
.then((value) {
// ignore: unnecessary_null_comparison
if (value != null) {
Navigator.pop((context));
debugPrint("Verification Completed !!!");
Get.to(() => Signup(
phoneNo: phone,
));
}
}).catchError((e) {
print(e);
});
},
child: const Text("Submit "))
],
));
},
codeAutoRetrievalTimeout: (String verificationId) {
verificationId = verificationId;
debugPrint("CodeAutoRetrieval...");
},
timeout: const Duration(seconds: 45));
} catch (e) {
print(e);
}
}
@override
Widget build(BuildContext context) {
mediaSize = MediaQuery.of(context).size;
myColor = Theme.of(context).primaryColor;
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.deepPurple[400],
title: const Text(
"Verify Phone Number",
style: TextStyle(fontSize: 30, color: Colors.white),
),
),
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(32.0),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
ShakeWidget(
key: shakeKey,
shakeOffset: 10,
shakeCount: 3,
shakeDuration: const Duration(milliseconds: 500),
child: Column(
children: [
TextFormField(
keyboardType: TextInputType.phone,
controller: phoneController,
decoration: const InputDecoration(
border: OutlineInputBorder(),
hintText: "9145369970",
labelText: "Phone Number",
prefixIcon: Icon(
Icons.phone,
color: Colors.deepPurple,
),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter Phone Number';
} else {
bool result = validatePhoneNumber(value);
if (result) {
return null;
} else {
return "Enter Number like +91*****";
}
}
},
),
const SizedBox(height: 30),
],
),
),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
ElevatedButton(
onPressed: () async {
if (_formKey.currentState!.validate()) {
QuerySnapshot snapshot = await FirebaseFirestore
.instance
.collection('students')
.where('phonenumber',
isEqualTo: phoneController.text)
.get();
if (snapshot.docs.isNotEmpty) {
for (QueryDocumentSnapshot document
in snapshot.docs) {
Map<String, dynamic> data =
document.data() as Map<String, dynamic>;
// String uuid = data['uuid'];
debugPrint(
"User Already Exists in Database with UUID : ${data['uuid']}");
// ignore: use_build_context_synchronously
showDialog(
context: context,
builder: (context) => const AlertDialog(
title: Text("User Already Exists "),
),
);
// academicyear "2525"
// bloodgroup "O+"
// class "SYMCA"
// dateofbirth "031001"
// division "B"
// emergencynumber "9145369975"
// fullname "Anurag "
// gender "Male "
// localaddress "abc"
// password "Aa@1"
// phonenumber "+919145369970"
// rollnumber "52112"
// uuid "2c763a8b-4b0a-4fc6-a1ef-446c0186fc5b"
// if (passwordController.text != password) {
// // ignore: use_build_context_synchronously
// showDialog(
// context: context,
// builder: (context) => const AlertDialog(
// title: Text("Password Not Matched "),
// ),
// );
// } else {
// final SharedPreferences prefs =
// await SharedPreferences.getInstance();
// await prefs.setBool('isLoggedIn', true);
// debugPrint(" User Logged In !!!");
// // ignore: use_build_context_synchronously
// Navigator.pop(context);
// Get.to(() => const StudentHome());
// }
}
} else {
_verifyPhoneNumber("+91${phoneController.text}");
}
} else {
shakeKey.currentState?.shake();
}
},
style: ElevatedButton.styleFrom(
fixedSize: const Size(110, 30),
backgroundColor: myColor,
shape: const StadiumBorder(),
elevation: 10,
shadowColor: Colors.deepPurple,
),
child: const Row(
children: [
Text(
"Next",
style: TextStyle(color: Colors.white, fontSize: 20),
),
Icon(
Icons.arrow_right_outlined,
color: Colors.white,
),
],
),
),
],
)
],
),
),
),
),
);
}
Widget _buildBottom() {
return SizedBox(
width: mediaSize.width,
child: Padding(
padding: const EdgeInsets.all(32.0),
child: _buildForm(),
),
);
}
Widget _buildForm() {
return Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.end,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
ShakeWidget(
key: shakeKey,
shakeOffset: 10,
shakeCount: 3,
shakeDuration: const Duration(milliseconds: 500),
child: Column(
children: [
TextFormField(
keyboardType: TextInputType.phone,
controller: phoneController,
decoration: const InputDecoration(
border: OutlineInputBorder(),
hintText: "9145369970",
label: Text(" Phone Number "),
prefixIcon: Icon(
Icons.phone,
color: Colors.deepPurple,
)),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter Phone Number ';
} else {
bool result = validatePhoneNumber(value);
if (result) {
return null;
} else {
return "Enter Number like +91*****";
}
}
},
),
const SizedBox(
height: 30,
),
],
)),
Positioned(right: 0, child: _buildLoginButton()),
],
),
);
}
Widget _buildLoginButton() {
return ElevatedButton(
onPressed: () async {
// If the form is valid, display a snackbar. In the real world,
if (_formKey.currentState!.validate()) {
_verifyPhoneNumber("+91${phoneController.text}");
} else {
shakeKey.currentState?.shake();
}
},
style: ElevatedButton.styleFrom(
backgroundColor: myColor,
shape: const StadiumBorder(),
elevation: 10,
shadowColor: Colors.deepPurple,
// minimumSize: const Size.fromHeight(60)
),
child: const SizedBox(
width: 65,
child: Row(
children: [
Text(
"Next ",
style: TextStyle(color: Colors.white, fontSize: 20),
),
Icon(
Icons.arrow_right_outlined,
color: Colors.white,
)
],
),
));
}
}
| 0 |
mirrored_repositories/id_generator/lib | mirrored_repositories/id_generator/lib/pages/login.dart | // import 'package:mongo_dart/mongo_dart.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:id_generator/animations/shake-widget.dart';
import 'package:id_generator/pages/adminHome.dart';
import 'package:id_generator/pages/verify_otp.dart';
import 'package:shared_preferences/shared_preferences.dart';
class LoginScreen extends StatefulWidget {
const LoginScreen({super.key});
@override
State<LoginScreen> createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
late Size mediaSize;
late Color myColor;
TextEditingController phoneController = TextEditingController();
TextEditingController passwordController = TextEditingController();
bool rememberUser = false;
final _formKey = GlobalKey<FormState>();
final shakeKey = GlobalKey<ShakeWidgetState>();
RegExp passValid = RegExp(r"(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*\W)");
RegExp phoneValid = RegExp(r"^\+?[0-9]{10,12}$");
bool validatePassword(String pass) {
String password = pass.trim();
if (passValid.hasMatch(password)) {
return true;
} else {
return false;
}
}
bool validatePhoneNumber(String phone) {
String phoneNumber = phone.trim();
if (phoneValid.hasMatch(phoneNumber)) {
return true;
} else {
return false;
}
}
@override
Widget build(BuildContext context) {
mediaSize = MediaQuery.of(context).size;
myColor = Theme.of(context).primaryColor;
return Scaffold(
appBar: AppBar(
title: Center(
child: Text(
"Login ",
style: TextStyle(
color: myColor, fontSize: 48, fontWeight: FontWeight.w500),
),
),
),
body: SafeArea(
child: _buildForm(),
),
);
}
Widget _buildForm() {
return SingleChildScrollView(
child: Form(
key: _formKey,
child: Padding(
padding: const EdgeInsets.all(24.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SizedBox(
height: 60,
),
ShakeWidget(
key: shakeKey,
shakeOffset: 10,
shakeCount: 3,
shakeDuration: const Duration(milliseconds: 500),
child: Column(
children: [
TextFormField(
maxLength: 10,
keyboardType: TextInputType.phone,
controller: phoneController,
decoration: const InputDecoration(
border: OutlineInputBorder(),
hintText: "9145369999",
label: Text(" Phone Number "),
prefixIcon: Icon(
Icons.phone,
color: Colors.deepPurple,
)),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter Phone Number ';
} else {
bool result = validatePhoneNumber(value);
if (result) {
return null;
} else {
return "Enter Proper Number";
}
}
},
),
const SizedBox(
height: 30,
),
TextFormField(
maxLength: 12,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please Enter Password ';
} else {
bool result = validatePassword(value);
if (result) {
return null;
} else {
return " Password should contain Capital, small letter & Number & Special";
}
}
},
keyboardType: TextInputType.visiblePassword,
controller: passwordController,
decoration: const InputDecoration(
border: OutlineInputBorder(),
hintText: "Abc#123",
label: Text("Password "),
prefixIcon: Icon(
Icons.lock,
color: Colors.deepPurple,
)),
),
],
)),
const SizedBox(
height: 30,
),
// _buildRememberForgot(),
const SizedBox(
height: 30,
),
_buildLoginButton(),
const SizedBox(height: 30),
_buildRegister(),
],
),
),
),
);
}
Widget _buildGreyText(String text) {
return Text(
text,
style: const TextStyle(color: Colors.grey),
);
}
Widget _buildLoginButton() {
return ElevatedButton(
onPressed: () async {
if (_formKey.currentState!.validate()) {
final snapshot = await checkCredentials();
if (snapshot.docs.isNotEmpty) {
for (QueryDocumentSnapshot document in snapshot.docs) {
Map<String, dynamic> data =
document.data() as Map<String, dynamic>;
String password = data['password'];
if (passwordController.text != password) {
// ignore: use_build_context_synchronously
showDialog(
context: context,
builder: (context) => const AlertDialog(
title: Text("Password Not Matched "),
),
);
} else {
final SharedPreferences prefs =
await SharedPreferences.getInstance();
await prefs.setBool('isLoggedIn', true);
debugPrint(" User Logged In !!!");
Navigator.pop(context);
Get.to(() => const AdminHome());
}
}
} else {
// ignore: use_build_context_synchronously
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Phone Number does not exist '),
duration:
Duration(seconds: 2), // Adjust the duration as needed
),
);
}
} else {
shakeKey.currentState?.shake();
}
},
style: ElevatedButton.styleFrom(
backgroundColor: myColor,
shape: const StadiumBorder(),
elevation: 20,
shadowColor: Colors.deepPurple,
minimumSize: const Size.fromHeight(60)),
child: const Text(
"LOGIN",
style: TextStyle(color: Colors.white),
));
}
Widget _buildRegister() {
return Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
_buildGreyText("Don't have an account? "),
TextButton(
style: TextButton.styleFrom(padding: EdgeInsets.zero),
onPressed: () {
setState(() {
Get.to(() => const VerifyPhoneScreen());
});
},
child: const Text(
"Register Here ",
style: TextStyle(color: Colors.deepPurple),
),
)
],
),
);
}
Future<QuerySnapshot> checkCredentials() async {
QuerySnapshot snapshot = await FirebaseFirestore.instance
.collection('credentials')
.where('phonenumber', isEqualTo: phoneController.text)
.get();
return snapshot;
}
}
| 0 |
mirrored_repositories/id_generator/lib | mirrored_repositories/id_generator/lib/pages/signup.dart | // ignore_for_file: avoid_unnecessary_containers, use_build_context_synchronously, non_constant_identifier_names
import 'package:id_generator/pages/student_home.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../Widgets/signUpWidgets.dart';
import 'dart:io';
// import 'package:encrypt/encrypt.dart';
import 'package:flutter/material.dart';
import 'package:id_generator/pages/verify_otp.dart';
import 'package:image_picker/image_picker.dart';
import 'package:uuid/uuid.dart';
import 'package:get/get.dart';
import 'package:connectivity/connectivity.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class Signup extends StatefulWidget {
const Signup({super.key, required this.phoneNo});
final String phoneNo;
@override
State<Signup> createState() => _SignupState();
}
final List<String> bloodGroups = [
'A+',
'A-',
'B+',
'B-',
'AB+',
'AB-',
'O+',
'O-',
];
class _SignupState extends State<Signup> {
late Size mediaSize;
late Color myColor;
// TextEditingController phoneController = TextEditingController();
TextEditingController fullNameController = TextEditingController();
TextEditingController dateOfBirth = TextEditingController();
TextEditingController academicYear = TextEditingController();
TextEditingController emergencyNumber = TextEditingController();
TextEditingController localAddress = TextEditingController();
TextEditingController rollNumber = TextEditingController();
TextEditingController password = TextEditingController();
bool rememberUser = false;
String uuid = const Uuid().v4();
String? _selectedClass;
String? _selectedGender;
String? _selectedDivision;
String? _selectedBloodGroup = bloodGroups.first;
File? _selectedImage;
final _formKey = GlobalKey<FormState>();
RegExp passValid = RegExp(r"(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*\W)");
RegExp fullNameValid =
RegExp(r"^[a-zA-Z]+(([',\.\-\s][a-zA-Z ])?[a-zA-Z]*)*$");
//A function that validate user entered password
bool validatePassword(String pass) {
String password = pass.trim();
if (passValid.hasMatch(password)) {
return true;
} else {
return false;
}
}
//A function that validate user entered Full Name
bool validateFullName(String name) {
String fullName = name.trim();
if (fullNameValid.hasMatch(fullName)) {
return true;
} else {
return false;
}
}
@override
Widget build(BuildContext context) {
mediaSize = MediaQuery.of(context).size;
myColor = Theme.of(context).primaryColor;
return Scaffold(
body: SingleChildScrollView(
child: SafeArea(
child: Column(
children: [
// Padding(
// padding: const EdgeInsets.all(8.0),
// child: SignUpWidgets.buildTop(mediaSize),
// ),
_buildBottom(),
],
),
),
),
);
}
Widget _buildBottom() {
return SizedBox(
width: mediaSize.width,
child: Card(
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(30), topRight: Radius.circular(30)),
),
child: _buildForm(),
),
);
}
Widget _buildForm() {
return SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(32.0),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
"Welcome ",
style: TextStyle(
color: myColor, fontSize: 32, fontWeight: FontWeight.w500),
),
SignUpWidgets.buildGreyText("Signup with your Information"),
const SizedBox(
height: 40,
),
Center(
child: _selectPassportPhoto(),
),
const SizedBox(
height: 40,
),
TextFormField(
maxLength: 30,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter Full Name ';
} else {
bool result = validateFullName(value);
if (result) {
return null;
} else {
return " Name Should Contain Alphabets Only ";
}
}
},
keyboardType: TextInputType.name,
controller: fullNameController,
decoration: const InputDecoration(
border: OutlineInputBorder(),
label: Text(" Full Name "),
hintText: "Baburao Ganpatrao Aapte ",
prefixIcon: Icon(
Icons.person,
color: Colors.deepPurple,
)),
),
const SizedBox(height: 10),
TextFormField(
maxLength: 10,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please Enter Date of Birth ';
}
return null;
},
keyboardType: TextInputType.datetime,
controller: dateOfBirth,
decoration: const InputDecoration(
border: OutlineInputBorder(),
hintText: "dd/mm/yyyy",
label: Text(" Date OF Birth "),
prefixIcon: Icon(
Icons.date_range,
color: Colors.deepPurple,
)),
),
const SizedBox(height: 10),
TextFormField(
maxLength: 4,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter Academic Year ';
}
return null;
},
keyboardType: TextInputType.datetime,
controller: academicYear,
decoration: const InputDecoration(
border: OutlineInputBorder(),
hintText: "2024",
label: Text(" Academic Year "),
prefixIcon: Icon(
Icons.school_outlined,
color: Colors.deepPurple,
)),
),
const SizedBox(height: 10),
// TextFormField(
// maxLength: 10,
// validator: (value) {
// if (value == null || value.isEmpty) {
// return 'Please enter Phone Number ';
// }
// return null;
// },
// keyboardType: TextInputType.phone,
// controller: phoneController,
// decoration: const InputDecoration(
// border: OutlineInputBorder(),
// hintText: "9145369999",
// label: Text(" Phone Number "),
// prefixIcon: Icon(
// Icons.phone,
// color: Colors.deepPurple,
// )),
// ),
const SizedBox(height: 10),
TextFormField(
maxLength: 10,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter Emergency Number ';
}
return null;
},
keyboardType: TextInputType.phone,
controller: emergencyNumber,
decoration: const InputDecoration(
border: OutlineInputBorder(),
hintText: "9145369999",
label: Text(" Emergency Phone Number "),
prefixIcon: Icon(
Icons.contact_emergency,
color: Colors.deepPurple,
)),
),
const SizedBox(height: 10),
TextFormField(
maxLength: 50,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter Address ';
}
return null;
},
keyboardType: TextInputType.streetAddress,
controller: localAddress,
decoration: const InputDecoration(
border: OutlineInputBorder(),
hintText: "Karve Nagar ,2nd Floor , Flat no. 30 ",
label: Text(" Local Address "),
prefixIcon: Icon(
Icons.location_city,
color: Colors.deepPurple,
)),
),
const SizedBox(height: 10),
TextFormField(
maxLength: 5,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter Roll Number ';
}
return null;
},
keyboardType: TextInputType.number,
controller: rollNumber,
decoration: const InputDecoration(
border: OutlineInputBorder(),
hintText: "51112",
label: Text("Roll Number "),
prefixIcon: Icon(
Icons.pin,
color: Colors.deepPurple,
)),
),
const SizedBox(height: 10),
_buildClassChoiceChip(),
const SizedBox(height: 10),
_buildDivChoiceChip(),
const SizedBox(height: 10),
_buildBloodGroupDropDown(),
const SizedBox(height: 10),
_buildGenderChoiceChip(),
const SizedBox(height: 10),
TextFormField(
maxLength: 12,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please Enter Password ';
} else {
bool result = validatePassword(value);
if (result) {
return null;
} else {
return " Password should contain Capital, small letter & Number & Special";
}
}
},
keyboardType: TextInputType.visiblePassword,
controller: password,
decoration: const InputDecoration(
border: OutlineInputBorder(),
hintText: "Abc#123",
label: Text("Password "),
prefixIcon: Icon(
Icons.lock,
color: Colors.deepPurple,
)),
),
const SizedBox(height: 30),
_buildSignupButton(),
const SizedBox(height: 30),
_buildLogin(),
const SizedBox(height: 60),
],
),
),
),
);
}
Widget _selectPassportPhoto() {
if (_selectedImage != null) {
return Container(
decoration: BoxDecoration(
borderRadius: const BorderRadius.all(Radius.circular(12)),
border: Border.all(color: Colors.grey, width: 2),
),
child: Stack(
children: [
ClipRRect(
borderRadius: BorderRadius.circular(10),
child: Image.file(
_selectedImage!,
fit: BoxFit.cover,
width: 116,
height: 116,
),
),
Positioned(
right: 0,
bottom: 0,
child: Container(
height: 30,
width: 30,
decoration: BoxDecoration(
border: Border.all(color: Colors.white, width: 1),
color: Colors.deepPurpleAccent,
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(10),
bottomRight: Radius.circular(10))),
child: IconButton(
padding: const EdgeInsets.all(0),
onPressed: () {
setState(() {
_selectedImage = null;
});
},
icon: const Icon(
Icons.close,
color: Colors.white,
size: 30,
)),
),
)
],
),
);
} else {
return Container(
decoration: BoxDecoration(
borderRadius: const BorderRadius.all(Radius.circular(10)),
border: Border.all(color: Colors.grey, width: 1),
),
height: 120,
width: 120,
child: IconButton(
// splashColor: null,
icon: const Icon(
Icons.add_a_photo,
size: 60,
color: Colors.deepPurple,
),
onPressed: () {
showDialog(
context: context,
builder: (context) {
return _buildAlertDialog();
});
},
),
);
// return GestureDetector(
// onTap: () => showDialog(
// context: context,
// builder: (context) {
// return _buildAlertDialog();
// }),
// child: SvgPicture.asset(
// './assets/images/emptyProfile.svg',
// ));
// return FilledButton(
// onPressed: () => showDialog(
// context: context,
// builder: (context) {
// return _buildAlertDialog();
// }),
// child: Image.asset('./assets/images/emptyProfile.png'));
// return Container(
// child: Image.asset('./assets/images/emptyProfile.png'),
// );
}
}
Widget _buildAlertDialog() {
return AlertDialog(
title: const Text("Select Image "),
actions: [
Row(
children: [
Expanded(
child: TextButton(
style: ButtonStyle(
iconColor:
MaterialStatePropertyAll(Colors.deepPurple[400])),
onPressed: () {
_pickImageFromCamera();
Navigator.pop(context);
},
child: Row(
children: [
const Icon(Icons.camera_alt),
const SizedBox(width: 20),
Text("Camera ",
style: TextStyle(color: Colors.deepPurple[400])),
],
),
),
),
],
),
Row(
children: [
Expanded(
child: TextButton(
style: ButtonStyle(
iconColor:
MaterialStatePropertyAll(Colors.deepPurple[400])),
onPressed: () {
_pickImageFromGallery();
Navigator.pop(context);
},
child: Row(
children: [
const Icon(Icons.upload_file),
const SizedBox(width: 20),
Text("Gallery ",
style: TextStyle(color: Colors.deepPurple[400]))
],
),
),
),
],
),
Positioned(
child: TextButton(
onPressed: () {
Navigator.pop(context);
},
child: const Text(
"Close",
style: TextStyle(fontWeight: FontWeight.bold),
)),
)
],
);
}
Widget _buildSignupButton() {
return ElevatedButton(
onPressed: () async {
var connectivityResult = await Connectivity().checkConnectivity();
if (connectivityResult == ConnectivityResult.none) {
showDialog(
context: context,
builder: (context) {
return SignUpWidgets().alertDialogForNoConnectivity();
});
} else {
if (_formKey.currentState!.validate()) {
debugPrint("UUID : ${uuid.toString()}");
debugPrint("Entered Full Name : ${fullNameController.text}");
debugPrint("DOB : ${dateOfBirth.text}");
debugPrint("AY : ${academicYear.text}");
debugPrint("Phone Number : ${widget.phoneNo}");
debugPrint("Emergency Phone Number : ${emergencyNumber.text}");
debugPrint("local Address : ${localAddress.text}");
debugPrint("Roll Number : ${rollNumber.text}");
debugPrint("Selected Class : $_selectedClass");
debugPrint("Selected Gender: $_selectedGender");
debugPrint("Selected Blood Group : $_selectedBloodGroup");
debugPrint("Passport Photo Location: $_selectedImage");
_generateNewUuid();
CollectionReference collRef =
FirebaseFirestore.instance.collection('students');
// var hashedPass = EncryptData.encryptAES(password.text, uuid);
// debugPrint("Password: ${hashedPass?.base64}");
collRef.add({
'fullname': fullNameController.text,
'uuid': uuid,
'phonenumber': widget.phoneNo,
'password': password.text,
// 'password': hashedPass?.base64,
'emergencynumber': emergencyNumber.text,
'division': _selectedDivision,
'bloodgroup': _selectedBloodGroup,
'class': _selectedClass,
'gender': _selectedGender,
'dateofbirth': dateOfBirth.text,
'academicyear': academicYear.text,
'localaddress': localAddress.text,
'rollnumber': rollNumber.text,
});
CollectionReference credRef =
FirebaseFirestore.instance.collection('credentials');
credRef.add({
'phonenumber': widget.phoneNo.substring(3),
'password': password.text,
// 'password': hashedPass?.base64,
'uuid': uuid,
});
}
// _signup();
final SharedPreferences prefs =
await SharedPreferences.getInstance();
await prefs.setBool('isLoggedIn', true);
await prefs.setString("uuid", uuid);
await prefs.setString("phone", widget.phoneNo);
await prefs.setString("name", fullNameController.text);
setState(() {
// Navigator.pop(context);
if (_selectedImage == null) {
showDialog(
context: context,
builder: ((context) => AlertDialog(
title: const Text("Select Profile Photo "),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text("Close"))
],
)));
} else {
uploadImage();
Navigator.pop(context);
Get.to(() => const StudentHome());
// Get.to(() => StudentQR(
// data: uuid,
// file: _selectedImage!,
// name: fullNameController.text,
// phone: widget.phoneNo,
// ));
}
});
}
},
style: ElevatedButton.styleFrom(
backgroundColor: myColor,
shape: const StadiumBorder(),
elevation: 20,
shadowColor: Colors.deepPurple,
minimumSize: const Size.fromHeight(60)),
child: const Text(
"Signup",
style: TextStyle(color: Colors.white),
));
}
Widget _buildLogin() {
return Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SignUpWidgets.buildGreyText("Already have an account ? "),
ElevatedButton(
style: TextButton.styleFrom(
padding: EdgeInsets.zero,
backgroundColor: Colors.transparent,
elevation: 0.0),
onPressed: () {
setState(() {
Get.to(() => const VerifyPhoneScreen());
});
},
child: const Text(
"Login Here ",
style: TextStyle(color: Colors.deepPurple),
)),
],
),
);
}
Widget _buildClassChoiceChip() {
return Container(
child: Wrap(spacing: 5.0, children: <Widget>[
_buildChoiceChip_Class("FYMCA"),
const SizedBox(width: 10),
_buildChoiceChip_Class("SYMCA")
]),
);
}
Widget _buildGenderChoiceChip() {
return Wrap(spacing: 5.0, children: <Widget>[
_buildChoiceChip_Gender("Male "),
const SizedBox(width: 10),
_buildChoiceChip_Gender("Female ")
]);
}
Widget _buildDivChoiceChip() {
return Wrap(spacing: 5.0, children: <Widget>[
_buildChoiceChip_Div("A"),
const SizedBox(width: 10),
_buildChoiceChip_Div("B")
]);
}
Widget _buildChoiceChip_Class(String label) {
return ChoiceChip(
label: Text(label),
selected: _selectedClass == label,
onSelected: (bool selected) {
setState(() {
_selectedClass = selected ? label : null;
});
},
);
}
Widget _buildChoiceChip_Gender(String label) {
return ChoiceChip(
label: Text(label),
selected: _selectedGender == label,
onSelected: (bool selected) {
setState(() {
_selectedGender = selected ? label : null;
});
},
);
}
Widget _buildChoiceChip_Div(String label) {
return ChoiceChip(
label: Text(label),
selected: _selectedDivision == label,
onSelected: (bool selected) {
setState(() {
_selectedDivision = selected ? label : null;
});
},
);
}
Widget _buildBloodGroupDropDown() {
return DropdownMenu<String>(
initialSelection: bloodGroups.first,
onSelected: (String? value) {
// This is called when the user selects an item.
setState(() {
_selectedBloodGroup = value!;
});
},
leadingIcon: const Icon(Icons.bloodtype),
label: const Text(" Blood Type "),
dropdownMenuEntries:
bloodGroups.map<DropdownMenuEntry<String>>((String value) {
return DropdownMenuEntry<String>(
value: value,
label: value,
);
}).toList(),
);
}
Future _pickImageFromGallery() async {
final returnedImage =
await ImagePicker().pickImage(source: ImageSource.gallery);
if (returnedImage == null) return;
setState(() {
_selectedImage = File(returnedImage.path);
});
}
Future _pickImageFromCamera() async {
final returnedImage =
await ImagePicker().pickImage(source: ImageSource.camera);
if (returnedImage == null) return;
setState(() {
_selectedImage = File(returnedImage.path);
});
}
void _generateNewUuid() {
setState(() {
uuid = const Uuid().v4(); // Generate a new random UUID
});
}
uploadImage() async {
if (_selectedImage == null) {
showDialog(
context: context,
builder: ((context) => AlertDialog(
title: const Text("Select Profile Photo "),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text("Close"))
],
)));
} else {
var firebaseStorage = FirebaseStorage.instance.ref(uuid);
await firebaseStorage.putFile(_selectedImage!);
}
}
}
| 0 |
mirrored_repositories/id_generator/lib | mirrored_repositories/id_generator/lib/pages/authentication_login.dart | import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:id_generator/constants.dart';
import 'package:mongo_dart/mongo_dart.dart';
class MongoDatabase {
static var db, credsCollection;
// static var credentialCollection = "credentials";
static connect() async {
db = await Db.create(MONGO_URL);
await db.open();
inspect(db);
credsCollection = db.collection(CRED_COLLECTION);
}
void checkCreds(String u, String p) async {
final user = await credsCollection
.find(where.eq('phonenumber', u).eq('password', p));
if (await user.isEmpty) {
debugPrint("No User Found ");
} else {
debugPrint("Success ");
}
}
}
| 0 |
mirrored_repositories/id_generator/lib | mirrored_repositories/id_generator/lib/pages/createEventScreen.dart | import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:id_generator/pages/viewEvents.dart';
import 'package:intl/intl.dart';
import 'package:uuid/uuid.dart';
class CreateEventScreen extends StatefulWidget {
const CreateEventScreen({super.key});
@override
State<CreateEventScreen> createState() => _CreateEventScreenState();
}
class _CreateEventScreenState extends State<CreateEventScreen> {
TextEditingController eventTitle = TextEditingController();
TextEditingController eventDescription = TextEditingController();
TextEditingController startDate = TextEditingController();
TextEditingController endDate = TextEditingController();
TextEditingController startTime = TextEditingController();
TextEditingController endTime = TextEditingController();
DateTime _selectedStartTime = DateTime.now();
DateTime _selectedEndTime = DateTime.now().add(const Duration(hours: 1));
TextEditingController address = TextEditingController();
final _formKey = GlobalKey<FormState>();
@override
void initState() {
startDate.text = "";
endDate.text = "";
super.initState();
}
Future<void> _selectTime(BuildContext context, String time, String startOrEnd,
TimeOfDay initTime) async {
TimeOfDay? selectedTime = await showTimePicker(
helpText: startOrEnd, context: context, initialTime: initTime);
if (selectedTime != null) {
final newTime = DateTime(
_selectedStartTime.year,
_selectedStartTime.month,
_selectedStartTime.day,
selectedTime.hour,
selectedTime.minute,
);
if (time == "startTime") {
startTime.text = DateFormat.jm().format(newTime);
// setState(() {
// });
} else if (time == "endTime") {
setState(() {
endTime.text = DateFormat.jm().format(newTime);
_selectedEndTime = newTime;
// DateTime sixHoursFromNow =
// _selectedEndTime.add(const Duration(hours: 6));
if (_selectedEndTime.isBefore(_selectedStartTime)) {
showDialog(
context: context,
builder: (context) => AlertDialog(
backgroundColor: Colors.red[100],
title: const Row(
children: [
Icon(Icons.warning_amber_rounded),
Text("Warning !!!"),
],
),
content:
const Text(" End Time Should be Greater than 6 hours "),
),
);
}
});
}
// setState(() {
// _selectedTime = newTime;
// if (time == "startTime") {
// startTime.text = DateFormat.jm().format(newTime);
// } else if (time == "endTime") {
// endTime.text = DateFormat.jm().format(newTime);
// }
// });
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: const Color.fromARGB(255, 211, 186, 255),
title: const Text(
" Create Event ",
style: TextStyle(
fontSize: 30,
color: Colors.deepPurple,
fontWeight: FontWeight.w600,
),
),
),
body: SingleChildScrollView(
child: Form(
key: _formKey,
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const SizedBox(height: 10),
TextFormField(
controller: eventTitle,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please Enter Title ';
}
return null;
},
keyboardType: TextInputType.text,
decoration: const InputDecoration(
prefixIcon: Icon(Icons.title),
border: OutlineInputBorder(),
label: Text(
"Event Title",
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w400,
color: Color.fromARGB(255, 62, 22, 131),
),
),
),
),
const SizedBox(height: 20),
TextFormField(
controller: address,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please Enter Address ';
}
return null;
},
keyboardType: TextInputType.text,
decoration: const InputDecoration(
prefixIcon: Icon(Icons.location_on_outlined),
border: OutlineInputBorder(),
label: Text(
"Event Address ",
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w400,
color: Color.fromARGB(255, 62, 22, 131),
),
),
),
),
const SizedBox(height: 20),
TextFormField(
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter Description ';
}
return null;
},
controller: eventDescription,
keyboardType: TextInputType.text,
decoration: const InputDecoration(
prefixIcon: Icon(Icons.description),
border: OutlineInputBorder(),
label: Text(
"Event Description",
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w400,
color: Color.fromARGB(255, 62, 22, 131),
),
textAlign: TextAlign.start,
),
),
),
const SizedBox(height: 20),
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: const Color.fromARGB(255, 241, 226, 255),
borderRadius: BorderRadius.circular(10),
border: Border.all(
style: BorderStyle.solid, width: 1, color: Colors.grey),
),
child: Column(
children: [
const Padding(
padding: EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
"Select Dates",
style: TextStyle(
fontSize: 30,
),
),
Icon(
Icons.calendar_month,
size: 30,
)
],
),
),
const Divider(
thickness: 2,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
SizedBox(
width: 140,
child: TextFormField(
controller: startDate,
validator: (value) {
if (value == null || value.isEmpty) {
return ' Event Start Time ';
}
return null;
},
keyboardType: TextInputType.text,
readOnly: true,
onTap: () async {
DateTime? pickedDate = await showDatePicker(
helpText: "Event Starting Date ",
context: context,
initialDate: DateTime.now(),
firstDate: DateTime.now(),
lastDate: DateTime(2100),
);
if (pickedDate != null) {
print(
"$pickedDate.month.toString() $pickedDate.day $pickedDate.year");
String formattedDate =
DateFormat('dd-MM-yyyy')
.format(pickedDate);
print(formattedDate);
setState(() {
startDate.text =
formattedDate; //set output date to TextField value.
});
}
},
decoration: const InputDecoration(
border: OutlineInputBorder(),
hintText: "Start Date "),
),
),
const Icon(Icons.sync_alt),
SizedBox(
width: 140,
child: TextFormField(
controller: endDate,
validator: (value) {
if (value == null || value.isEmpty) {
return ' Event End Date ';
}
return null;
},
keyboardType: TextInputType.text,
readOnly: true,
onTap: () async {
DateTime? pickedDate = await showDatePicker(
helpText: "Event Ending Date ",
context: context,
initialDate: DateTime.now(),
firstDate: DateTime.now(),
lastDate: DateTime(2100));
if (pickedDate != null) {
print(pickedDate);
String formattedDate =
DateFormat('dd-MM-yyyy')
.format(pickedDate);
print(formattedDate);
setState(() {
endDate.text =
formattedDate; //set output date to TextField value.
});
}
},
decoration: const InputDecoration(
border: OutlineInputBorder(),
hintText: "End Date "),
),
),
],
),
),
],
),
),
const SizedBox(height: 20),
// -------------------------------------------------------------------------------------------------------------
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
// boxShadow: const <BoxShadow>[
// BoxShadow(
// color: Colors.grey,
// offset: Offset(2, 8),
// spreadRadius: -2,
// blurRadius: 10)
// ],
color: const Color.fromARGB(255, 241, 226, 255),
borderRadius: BorderRadius.circular(10),
border: Border.all(
style: BorderStyle.solid, width: 1, color: Colors.grey),
),
child: Column(
children: [
const Padding(
padding: EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
"Select Timings ",
style: TextStyle(
fontSize: 30,
),
),
Icon(
Icons.access_time,
size: 30,
)
],
),
),
const Divider(
thickness: 2,
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
SizedBox(
width: 140,
child: TextFormField(
controller: startTime,
validator: (value) {
if (value == null || value.isEmpty) {
return ' Event Start Time';
}
return null;
},
readOnly: true,
onTap: () => _selectTime(
context,
"startTime",
" Event Starting Time ",
TimeOfDay.now(),
),
decoration: const InputDecoration(
border: OutlineInputBorder(),
hintText: "Start Time"),
),
),
const Icon(Icons.sync_alt),
SizedBox(
width: 140,
child: TextFormField(
controller: endTime,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Event End Time';
}
return null;
},
readOnly: true,
onTap: () => _selectTime(
context,
"endTime",
"Event Ending Time ",
TimeOfDay.fromDateTime(
DateTime.now().add(
const Duration(hours: 3),
),
),
),
decoration: const InputDecoration(
border: OutlineInputBorder(),
hintText: "End Time "),
),
),
],
),
),
],
),
),
const SizedBox(
height: 20,
),
],
),
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
// showDialog(
// // barrierDismissible: false,
// context: context,
// builder: (context) => AlertDialog(
// title: const Text("Event Added "),
// content: Column(
// mainAxisSize: MainAxisSize.min,
// children: [
// Image.asset(
// 'assets/images/eventAdded.png',
// ),
// Row(
// children: [
// ElevatedButton(
// onPressed: () {}, child: const Text("View Events "))
// ],
// )
// ],
// ),
// ),
// );
if (_formKey.currentState!.validate()) {
CollectionReference collRef =
FirebaseFirestore.instance.collection('events');
collRef.add({
'uuid': const Uuid().v4(),
'eventTitle': eventTitle.text,
'eventDescription': eventDescription.text,
'eventStartDate': startDate.text,
'eventEndDate': endDate.text,
'eventStartTime': startTime.text,
'eventEndTime': endTime.text,
'eventAddress': address.text,
});
Navigator.pop(context);
Get.to(
() => const ViewEventsScreen(),
);
}
},
backgroundColor: Colors.deepPurple,
foregroundColor: Colors.white,
child: const Icon(
Icons.add,
size: 48,
),
),
);
}
// Future<void> _selectTime(
// BuildContext context, String time, String startOrEnd) async {
// TimeOfDay initialTime = TimeOfDay.fromDateTime(_selectedTime);
// TimeOfDay? selectedTime = await showTimePicker(
// helpText: startOrEnd,
// context: context,
// initialTime: initialTime,
// );
// if (selectedTime != null) {
// final newTime = DateTime(
// _selectedTime.year,
// _selectedTime.month,
// _selectedTime.day,
// selectedTime.hour,
// selectedTime.minute,
// );
// setState(() {
// _selectedTime = newTime;
// if (time == "startTime") {
// startTime.text = DateFormat.jm().format(newTime);
// } else if (time == "endTime") {
// endTime.text = DateFormat.jm().format(newTime);
// }
// });
// }
// }
}
| 0 |
mirrored_repositories/id_generator/lib | mirrored_repositories/id_generator/lib/pages/getStarted.dart | import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:id_generator/pages/login.dart';
import 'package:shared_preferences/shared_preferences.dart';
class GetStarted extends StatelessWidget {
const GetStarted({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
actions: [
Padding(
padding: const EdgeInsets.all(8),
child: IconButton(
onPressed: () async {
final SharedPreferences prefs =
await SharedPreferences.getInstance();
await prefs.setBool('isLoggedIn', false);
Navigator.pop(context);
debugPrint(" User Logged Out !!!");
Get.to(() => const LoginScreen());
},
icon: const Icon(Icons.logout)),
),
],
title: const Text("Welcome "),
),
);
}
}
| 0 |
mirrored_repositories/id_generator/lib | mirrored_repositories/id_generator/lib/bloc/event_bloc.dart | import 'package:bloc/bloc.dart';
import 'package:meta/meta.dart';
part 'event_event.dart';
part 'event_state.dart';
class EventBloc extends Bloc<EventEvent, EventState> {
EventBloc() : super(EventInitial()) {
on<EventEvent>((event, emit) {});
}
}
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.