repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/blaze/blaze/lib
mirrored_repositories/blaze/blaze/lib/components/default_app_bar.dart
import 'package:blaze/components/styles/icon_broken.dart'; import 'package:flutter/material.dart'; PreferredSizeWidget defaultAppBar({ required BuildContext context, String? title, List<Widget>? actions, required function, }) => AppBar( leading: IconButton( icon: const Icon(IconBroken.Arrow___Left_2), onPressed: function, ), titleSpacing: 5.0, title: title != null ? Text(title, style: Theme.of(context).textTheme.bodyText1) : null, actions: actions, );
0
mirrored_repositories/blaze/blaze/lib
mirrored_repositories/blaze/blaze/lib/components/themes.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:google_fonts/google_fonts.dart'; import 'const.dart'; ThemeData lightTheme() => ThemeData( appBarTheme: AppBarTheme( backgroundColor: Colors.white, elevation: 0, actionsIconTheme: const IconThemeData(color: Colors.black), titleTextStyle: GoogleFonts.quicksand().copyWith( fontWeight: FontWeight.bold, color: Colors.black, fontSize: 28.0), iconTheme: const IconThemeData(color: Colors.black), systemOverlayStyle: const SystemUiOverlayStyle( statusBarBrightness: Brightness.dark, statusBarColor: Colors.white, statusBarIconBrightness: Brightness.dark, ), ), primarySwatch: defaultColor1, scaffoldBackgroundColor: Colors.white, inputDecorationTheme: InputDecorationTheme( border: OutlineInputBorder( borderRadius: BorderRadius.circular(15), ), contentPadding: const EdgeInsetsDirectional.only(top: 5, start: 20), hintStyle: const TextStyle(color: Colors.black), ), textTheme: GoogleFonts.lailaTextTheme().copyWith( caption: const TextStyle( fontSize: 12.0, fontWeight: FontWeight.w100, color: Colors.black, height: 1.3, ), bodyText1: const TextStyle(color: Colors.black, fontWeight: FontWeight.w400, fontSize: 16), subtitle1: const TextStyle( fontSize: 14.0, fontWeight: FontWeight.w400, color: Colors.black, height: 1.3, ), ), bottomNavigationBarTheme: const BottomNavigationBarThemeData( backgroundColor: Colors.white, selectedItemColor: defaultColor1, unselectedItemColor: Colors.grey, showUnselectedLabels: true, type: BottomNavigationBarType.fixed)); ThemeData darkTheme() => ThemeData( appBarTheme: AppBarTheme( backgroundColor: const Color(0xFF202A44), elevation: 0, actionsIconTheme: const IconThemeData(color: Colors.white), titleTextStyle: GoogleFonts.quicksand().copyWith( fontWeight: FontWeight.bold, color: Colors.white, fontSize: 28.0), iconTheme: const IconThemeData(color: Colors.white), systemOverlayStyle: const SystemUiOverlayStyle( statusBarBrightness: Brightness.light, statusBarColor: Color(0xFF202A44), statusBarIconBrightness: Brightness.light, ), ), primarySwatch: defaultColor1, scaffoldBackgroundColor: const Color(0xFF202A44), inputDecorationTheme: InputDecorationTheme( border: OutlineInputBorder(borderRadius: BorderRadius.circular(15)), contentPadding: const EdgeInsetsDirectional.only(top: 5, start: 30), hintStyle: const TextStyle(color: Colors.white), ), textTheme: GoogleFonts.lailaTextTheme().copyWith( caption: const TextStyle( fontSize: 12.0, fontWeight: FontWeight.w100, color: Colors.white, height: 1.3, ), bodyText1: GoogleFonts.laila().copyWith( color: Colors.white, fontWeight: FontWeight.w400, fontSize: 16), subtitle1: const TextStyle( fontSize: 14.0, fontWeight: FontWeight.w600, color: Colors.white, height: 1.3, ), ), bottomNavigationBarTheme: const BottomNavigationBarThemeData( backgroundColor: Color(0xFF202A44), selectedItemColor: defaultColor1, unselectedItemColor: Colors.white, type: BottomNavigationBarType.fixed), iconTheme: const IconThemeData(color: Colors.white), primaryIconTheme: const IconThemeData(color: Colors.white), );
0
mirrored_repositories/blaze/blaze/lib
mirrored_repositories/blaze/blaze/lib/components/default_post.dart
import 'package:blaze/components/const.dart'; import 'package:blaze/components/styles/icon_broken.dart'; import 'package:blaze/helpers/cubits/social_cubit.dart'; import 'package:blaze/models/post.dart'; import 'package:blaze/translations/locale_keys.g.dart'; import 'package:blaze/views/comment_screen/comment_screen.dart'; import 'package:blaze/views/full_image/full_image_screen.dart'; import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'package:iconsax/iconsax.dart'; import 'package:easy_localization/easy_localization.dart'; Widget buildPostItem(SocialPost post, context, index) { TextEditingController commentController = TextEditingController(); return Padding( padding: const EdgeInsets.all(10.0), child: Container( color: SocialCubit.get(context).isDark ? Color(0xFF202A44) : Colors.white, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ CircleAvatar( radius: 25.0, backgroundImage: NetworkImage(post.image), ), const SizedBox(width: 15.0), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Text( post.name, style: Theme.of(context) .textTheme .bodyText1!.copyWith(fontSize: 15.0), ), const SizedBox(width: 5.0), const Icon( Icons.check_circle, color: Colors.lightBlue, size: 16.0, ) ], ), Text( DateFormat("h:mm a d/M/y") .format(DateTime.parse(post.dateTime)) .toString(), style: Theme.of(context) .textTheme .caption! .copyWith(height: 1.4), ), ], ), ), const SizedBox(width: 15.0), PopupMenuButton( child: const Icon(Iconsax.more_square), itemBuilder: (context) { return <PopupMenuItem<String>>[ PopupMenuItem<String>( child: TextButton( onPressed: () { SocialCubit.get(context).deletePost(post); }, child: Text(LocaleKeys.delelte_post.tr()))), ]; }, ) ], ), Padding( padding: const EdgeInsets.symmetric(vertical: 15.0), child: Container( width: double.infinity, height: 1.0, color: Colors.grey[300]), ), Text(post.text, style: Theme.of(context).textTheme.subtitle1), if (post.postImage != '') InkWell( onTap: (){ Navigator.push(context,MaterialPageRoute(builder: (contaxt) => FullImageScreen(index: index, post: post))); }, child: Padding( padding: const EdgeInsets.only(top: 8.0), child: ClipRRect( borderRadius: BorderRadius.circular(10), child: FadeInImage( placeholder: const AssetImage('assets/images/3.png'), image: NetworkImage(post.postImage!), ), ), ), ), Padding( padding: const EdgeInsets.symmetric(vertical: 5.0), child: Row( children: [ Expanded( child: InkWell( child: Padding( padding: const EdgeInsets.symmetric(vertical: 5.0), child: Row( children: [ const Icon(IconBroken.Heart, size: 16.0, color: defaultColor1), const SizedBox(width: 5.0), Text( post.likes.toString(), style: Theme.of(context).textTheme.caption, ) ], ), ), onTap: () {}, ), ), Expanded( child: InkWell( child: Padding( padding: const EdgeInsets.symmetric(vertical: 5.0), child: Row( mainAxisAlignment: MainAxisAlignment.end, children: [ const Icon(Icons.comment_outlined, size: 16.0, color: defaultColor2), const SizedBox(width: 5.0), Text(LocaleKeys.comments.tr(), style: Theme.of(context).textTheme.caption, ) ], ), ), onTap: () { SocialCubit.get(context).getCommetns(postId: post.pId!); Navigator.push( context, MaterialPageRoute( builder: (context) => CommentScreen(postId: post.pId!))); }, ), ) ], ), ), Padding( padding: const EdgeInsets.only(bottom: 10.0), child: Container( width: double.infinity, height: 1.0, color: Colors.grey[300], ), ), if (SocialCubit.get(context).commentImage != null) Stack( alignment: AlignmentDirectional.topEnd, children: [ Container( height: 100.0, width: double.infinity, decoration: BoxDecoration( borderRadius: const BorderRadius.only( topLeft: Radius.circular(10.0), topRight: Radius.circular(10.0), ), image: DecorationImage( image: FileImage(SocialCubit.get(context).commentImage!), fit: BoxFit.contain, ), ), ), IconButton( onPressed: () { SocialCubit.get(context).removeCommentImage(); }, icon: const CircleAvatar( radius: 20.0, backgroundColor: Colors.lightBlue, child: Icon( Icons.close, color: Colors.white, ), ), ), ], ), Row( children: [ CircleAvatar( radius: 18.0, backgroundImage: NetworkImage(SocialCubit.get(context).user.image), ), const SizedBox(width: 5.0), Expanded( child: TextFormField( onFieldSubmitted: (value) { if (value.isNotEmpty) { SocialCubit.get(context).addComment( text: value, postId: post.pId!, dateTime: DateTime.now().toString()); commentController.clear(); } }, controller: commentController, style: Theme.of(context).textTheme.caption, decoration: InputDecoration( hintText: LocaleKeys.write_comment.tr(), hintStyle: Theme.of(context).textTheme.caption, focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(25.0), borderSide: const BorderSide( color: defaultColor1, ), ), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(25.0), borderSide: const BorderSide( color: Colors.grey, width: 1.0, ), ), suffixIcon: IconButton( onPressed: () { SocialCubit.get(context).getCommentImage(); }, icon: const Icon( IconBroken.Image, color: defaultColor1, size: 20, ), ), ), ), ), const SizedBox(width: 5.0), InkWell( child: Row( children: [ const Icon(IconBroken.Heart, size: 16.0, color: defaultColor1), const SizedBox(width: 5.0), Text( LocaleKeys.like.tr(), style: Theme.of(context).textTheme.caption, ) ], ), onTap: () { SocialCubit.get(context).likePost(post.pId!, SocialCubit.get(context).posts[index].likes!, index); }, ), ], ), ], ), ), ); }
0
mirrored_repositories/blaze/blaze/lib
mirrored_repositories/blaze/blaze/lib/components/default_format_field.dart
import 'package:blaze/helpers/cubits/social_cubit.dart'; import 'package:flutter/material.dart'; Widget defaultFormField({ required context, TextEditingController? controller, dynamic label, IconData? prefix, String? initialValue, TextInputType? keyboardType, Function(String)? onSubmit, onChange, onTap, required String? Function(String?) validate, bool isPassword = false, bool enabled = true, IconData? suffix, suffixPressed, }) => TextFormField( controller: controller, keyboardType: keyboardType, obscureText: isPassword, textAlign: TextAlign.start, onFieldSubmitted: onSubmit, enabled: enabled, onChanged: onChange, onTap: onTap, validator: validate, textCapitalization: TextCapitalization.words, textAlignVertical: TextAlignVertical.center, style: Theme.of(context).textTheme.subtitle1, initialValue: initialValue, decoration: InputDecoration( hintText: label, border: OutlineInputBorder( borderRadius: BorderRadius.circular(10.0), ), prefixIcon: Icon( prefix, color: SocialCubit.get(context).isDark ? Colors.white : Colors.black, ), suffixIcon: suffix != null ? IconButton(onPressed: suffixPressed, icon: Icon(suffix, color: SocialCubit.get(context).isDark ? Colors.white : Colors.black,)) : null, ), );
0
mirrored_repositories/blaze/blaze/lib
mirrored_repositories/blaze/blaze/lib/components/default_text_button.dart
import 'package:flutter/material.dart'; Widget defaultTextButton({ required Function() function, required String text, }) => TextButton( onPressed: function, child: Text( text.toUpperCase(), style: const TextStyle( fontSize: 15.0, fontWeight: FontWeight.w600 ), ), );
0
mirrored_repositories/blaze/blaze/lib
mirrored_repositories/blaze/blaze/lib/components/default_button.dart
import 'package:flutter/material.dart'; import 'package:blaze/components/const.dart'; Widget defaultButton({ double width = double.infinity, Color background = defaultColor1, bool isUpperCase = true, double radius = 10.0, Gradient? gradient, required Function() function, required String text, }) => Container( width: width, height: 50.0, child: MaterialButton( onPressed: function, child: Text( isUpperCase ? text.toUpperCase() : text, style: const TextStyle( color: Colors.white, fontWeight: FontWeight.bold, ), ), ), decoration: BoxDecoration( borderRadius: BorderRadius.circular( radius, ), gradient: gradient, color: background, ), );
0
mirrored_repositories/blaze/blaze/lib
mirrored_repositories/blaze/blaze/lib/components/const.dart
import 'package:flutter/material.dart'; const defaultColor1 = Colors.pink; const defaultColor3 = Color(0xFF000957); const defaultColor2 = Color(0xFF292C6D); const defaultColor4 = Color(0xFFFAEDF0); String? uId = ''; String? lang = '';
0
mirrored_repositories/blaze/blaze/lib/components
mirrored_repositories/blaze/blaze/lib/components/styles/icon_broken.dart
// Place fonts/icons.ttf in your fonts/ directory and // add the following to your pubspec.yaml // flutter: // fonts: // - family: Iconly-Broken // fonts: // - asset: fonts/icons.ttf // ignore_for_file: constant_identifier_names import 'package:flutter/widgets.dart'; class IconBroken { IconBroken._(); static const String _fontFamily = 'IconBroken'; static const IconData User = IconData(0xe900, fontFamily: _fontFamily); static const IconData User1 = IconData(0xe901, fontFamily: _fontFamily); static const IconData Activity = IconData(0xe902, fontFamily: _fontFamily); static const IconData Add_User = IconData(0xe903, fontFamily: _fontFamily); static const IconData Arrow___Down_2 = IconData(0xe904, fontFamily: _fontFamily); static const IconData Arrow___Down_3 = IconData(0xe905, fontFamily: _fontFamily); static const IconData Arrow___Down_Circle = IconData(0xe906, fontFamily: _fontFamily); static const IconData Arrow___Down_Square = IconData(0xe907, fontFamily: _fontFamily); static const IconData Arrow___Down = IconData(0xe908, fontFamily: _fontFamily); static const IconData Arrow___Left_2 = IconData(0xe909, fontFamily: _fontFamily); static const IconData Arrow___Left_3 = IconData(0xe90a, fontFamily: _fontFamily); static const IconData Arrow___Left_Circle = IconData(0xe90b, fontFamily: _fontFamily); static const IconData Arrow___Left_Square = IconData(0xe90c, fontFamily: _fontFamily); static const IconData Arrow___Left = IconData(0xe90d, fontFamily: _fontFamily); static const IconData Arrow___Right_2 = IconData(0xe90e, fontFamily: _fontFamily); static const IconData Arrow___Right_3 = IconData(0xe90f, fontFamily: _fontFamily); static const IconData Arrow___Right_Circle = IconData(0xe910, fontFamily: _fontFamily); static const IconData Arrow___Right_Square = IconData(0xe911, fontFamily: _fontFamily); static const IconData Arrow___Right = IconData(0xe912, fontFamily: _fontFamily); static const IconData Arrow___Up_2 = IconData(0xe913, fontFamily: _fontFamily); static const IconData Arrow___Up_3 = IconData(0xe914, fontFamily: _fontFamily); static const IconData Arrow___Up_Circle = IconData(0xe915, fontFamily: _fontFamily); static const IconData Arrow___Up_Square = IconData(0xe916, fontFamily: _fontFamily); static const IconData Arrow___Up = IconData(0xe917, fontFamily: _fontFamily); static const IconData Bag_2 = IconData(0xe918, fontFamily: _fontFamily); static const IconData Bag = IconData(0xe919, fontFamily: _fontFamily); static const IconData Bookmark = IconData(0xe91a, fontFamily: _fontFamily); static const IconData Buy = IconData(0xe91b, fontFamily: _fontFamily); static const IconData Calendar = IconData(0xe91c, fontFamily: _fontFamily); static const IconData Call_Missed = IconData(0xe91d, fontFamily: _fontFamily); static const IconData Call_Silent = IconData(0xe91e, fontFamily: _fontFamily); static const IconData Call = IconData(0xe91f, fontFamily: _fontFamily); static const IconData Calling = IconData(0xe920, fontFamily: _fontFamily); static const IconData Camera = IconData(0xe921, fontFamily: _fontFamily); static const IconData Category = IconData(0xe922, fontFamily: _fontFamily); static const IconData Chart = IconData(0xe923, fontFamily: _fontFamily); static const IconData Chat = IconData(0xe924, fontFamily: _fontFamily); static const IconData Close_Square = IconData(0xe925, fontFamily: _fontFamily); static const IconData Danger = IconData(0xe926, fontFamily: _fontFamily); static const IconData Delete = IconData(0xe927, fontFamily: _fontFamily); static const IconData Discount = IconData(0xe928, fontFamily: _fontFamily); static const IconData Discovery = IconData(0xe929, fontFamily: _fontFamily); static const IconData Document = IconData(0xe92a, fontFamily: _fontFamily); static const IconData Download = IconData(0xe92b, fontFamily: _fontFamily); static const IconData Edit_Square = IconData(0xe92c, fontFamily: _fontFamily); static const IconData Edit = IconData(0xe92d, fontFamily: _fontFamily); static const IconData Filter_2 = IconData(0xe92e, fontFamily: _fontFamily); static const IconData Filter = IconData(0xe92f, fontFamily: _fontFamily); static const IconData Folder = IconData(0xe930, fontFamily: _fontFamily); static const IconData Game = IconData(0xe931, fontFamily: _fontFamily); static const IconData Graph = IconData(0xe932, fontFamily: _fontFamily); static const IconData Heart = IconData(0xe933, fontFamily: _fontFamily); static const IconData Hide = IconData(0xe934, fontFamily: _fontFamily); static const IconData Home = IconData(0xe935, fontFamily: _fontFamily); static const IconData Image_2 = IconData(0xe936, fontFamily: _fontFamily); static const IconData Image = IconData(0xe937, fontFamily: _fontFamily); static const IconData Info_Circle = IconData(0xe938, fontFamily: _fontFamily); static const IconData Info_Square = IconData(0xe939, fontFamily: _fontFamily); static const IconData Location = IconData(0xe93a, fontFamily: _fontFamily); static const IconData Lock = IconData(0xe93b, fontFamily: _fontFamily); static const IconData Login = IconData(0xe93c, fontFamily: _fontFamily); static const IconData Logout = IconData(0xe93d, fontFamily: _fontFamily); static const IconData Message = IconData(0xe93e, fontFamily: _fontFamily); static const IconData More_Circle = IconData(0xe93f, fontFamily: _fontFamily); static const IconData More_Square = IconData(0xe940, fontFamily: _fontFamily); static const IconData Notification = IconData(0xe941, fontFamily: _fontFamily); static const IconData Paper_Download = IconData(0xe942, fontFamily: _fontFamily); static const IconData Paper_Fail = IconData(0xe943, fontFamily: _fontFamily); static const IconData Paper_Negative = IconData(0xe944, fontFamily: _fontFamily); static const IconData Paper_Plus = IconData(0xe945, fontFamily: _fontFamily); static const IconData Paper_Upload = IconData(0xe946, fontFamily: _fontFamily); static const IconData Paper = IconData(0xe947, fontFamily: _fontFamily); static const IconData Password = IconData(0xe948, fontFamily: _fontFamily); static const IconData Play = IconData(0xe949, fontFamily: _fontFamily); static const IconData Plus = IconData(0xe94a, fontFamily: _fontFamily); static const IconData Profile = IconData(0xe94b, fontFamily: _fontFamily); static const IconData Scan = IconData(0xe94c, fontFamily: _fontFamily); static const IconData Search = IconData(0xe94d, fontFamily: _fontFamily); static const IconData Send = IconData(0xe94e, fontFamily: _fontFamily); static const IconData Setting = IconData(0xe94f, fontFamily: _fontFamily); static const IconData Shield_Done = IconData(0xe950, fontFamily: _fontFamily); static const IconData Shield_Fail = IconData(0xe951, fontFamily: _fontFamily); static const IconData Show = IconData(0xe952, fontFamily: _fontFamily); static const IconData Star = IconData(0xe953, fontFamily: _fontFamily); static const IconData Swap = IconData(0xe954, fontFamily: _fontFamily); static const IconData Tick_Square = IconData(0xe955, fontFamily: _fontFamily); static const IconData Ticket_Star = IconData(0xe956, fontFamily: _fontFamily); static const IconData Ticket = IconData(0xe957, fontFamily: _fontFamily); static const IconData Time_Circle = IconData(0xe958, fontFamily: _fontFamily); static const IconData Time_Square = IconData(0xe959, fontFamily: _fontFamily); static const IconData Unlock = IconData(0xe95a, fontFamily: _fontFamily); static const IconData Upload = IconData(0xe95b, fontFamily: _fontFamily); static const IconData Video = IconData(0xe95c, fontFamily: _fontFamily); static const IconData Voice_2 = IconData(0xe95d, fontFamily: _fontFamily); static const IconData Voice = IconData(0xe95e, fontFamily: _fontFamily); static const IconData Volume_Down = IconData(0xe95f, fontFamily: _fontFamily); static const IconData Volume_Off = IconData(0xe960, fontFamily: _fontFamily); static const IconData Volume_Up = IconData(0xe961, fontFamily: _fontFamily); static const IconData Wallet = IconData(0xe962, fontFamily: _fontFamily); static const IconData Work = IconData(0xe963, fontFamily: _fontFamily); }
0
mirrored_repositories/blaze/blaze/lib
mirrored_repositories/blaze/blaze/lib/models/comments.dart
class SocialComment{ late String dateTime; late String uId; late String? cId; late String name; late String image; late String text; late String? commentImage; SocialComment({this.cId, required this.uId, required this.dateTime, required this.name, required this.image, this.commentImage, required this.text}); SocialComment.fromJson(Map<String, dynamic> json){ uId = json['uId']; name = json['name']; image = json['image']; dateTime = json['dateTime']; text = json['text']; commentImage = json['commentImage']; cId = json['cId']; } Map<String, dynamic> toJson(){ return { 'uId': uId, 'dateTime': dateTime, 'text': text, 'name': name, 'image': image, 'commentImage': commentImage, 'cId': cId, }; } }
0
mirrored_repositories/blaze/blaze/lib
mirrored_repositories/blaze/blaze/lib/models/on_barding.dart
class BoardingModel { BoardingModel({required this.image, required this.body, required this.title}); final String image; final String title; final String body; }
0
mirrored_repositories/blaze/blaze/lib
mirrored_repositories/blaze/blaze/lib/models/message.dart
class SocialMessage{ late String reciverId; late String senderId; late String text; late String dateTime; String? image; SocialMessage({ required this.reciverId, required this.dateTime, required this.senderId, this.image, required this.text}); SocialMessage.fromJson(Map<String, dynamic> json){ senderId = json['senderId']; reciverId = json['reciverId']; dateTime = json['dateTime']; text = json['text']; image = json['image']; } Map<String, dynamic> toJson(){ return { 'reciverId' : reciverId, 'dateTime' : dateTime, 'text' : text, 'senderId' : senderId, 'image': image, }; } }
0
mirrored_repositories/blaze/blaze/lib
mirrored_repositories/blaze/blaze/lib/models/user.dart
class SocialUser{ late String name; late String email; late String uId; late String phone; late String image; late String cover; late String bio; late int followers; SocialUser({required this.followers, required this.email, required this.name, required this.phone, required this.uId, required this.image, required this.bio, required this.cover}); SocialUser.fromJson(Map<String, dynamic> json){ uId = json['uId']; name = json['name']; email = json['email']; phone = json['phone']; image = json['image']; cover = json['cover']; bio = json['bio']; followers = json['followers']; } Map<String, dynamic> toJson(){ return { 'name' : name, 'email' : email, 'phone' : phone, 'uId' : uId, 'image': image, 'cover': cover, 'bio': bio, 'followers': followers, }; } SocialUser.empty(){ uId = '-1'; name = ''; email = ''; phone = ''; image = ''; bio = ''; cover = ''; } }
0
mirrored_repositories/blaze/blaze/lib
mirrored_repositories/blaze/blaze/lib/models/post.dart
class SocialPost{ late String name; late String dateTime; late String uId; late String text; late String image; late String? pId; String? postImage; int? likes; int? comments; SocialPost({this.pId, required this.name, required this.dateTime, required this.uId, this.postImage, required this.image, required this.text, this.comments, this.likes}); SocialPost.fromJson(Map<String, dynamic> json){ uId = json['uId']; name = json['name']; dateTime = json['dateTime']; text = json['text']; image = json['image']; postImage = json['postImage']; likes = json['likes']; comments = json['comments']; pId = json['pId']; } Map<String, dynamic> toJson(){ return { 'name' : name, 'dateTime' : dateTime, 'text' : text, 'uId' : uId, 'image': image, 'postImage': postImage, 'likes': likes, 'comments': comments, 'pId': pId, }; } }
0
mirrored_repositories/blaze/blaze/lib
mirrored_repositories/blaze/blaze/lib/helpers/bloc_observer.dart
import 'package:bloc/bloc.dart'; class MyBlocObserver extends BlocObserver { @override void onCreate(BlocBase bloc) { super.onCreate(bloc); print('onCreate -- ${bloc.runtimeType}'); } @override void onChange(BlocBase bloc, Change change) { super.onChange(bloc, change); print('onChange -- ${bloc.runtimeType}, $change'); } @override void onError(BlocBase bloc, Object error, StackTrace stackTrace) { print('onError -- ${bloc.runtimeType}, $error'); super.onError(bloc, error, stackTrace); } @override void onClose(BlocBase bloc) { super.onClose(bloc); print('onClose -- ${bloc.runtimeType}'); } }
0
mirrored_repositories/blaze/blaze/lib/helpers
mirrored_repositories/blaze/blaze/lib/helpers/cubits/social_cubit.dart
import 'dart:io'; import 'package:blaze/components/toast.dart'; import 'package:blaze/helpers/local/chache_helper.dart'; import 'package:blaze/models/comments.dart'; import 'package:blaze/models/message.dart'; import 'package:blaze/models/post.dart'; import 'package:blaze/translations/locale_keys.g.dart'; import 'package:blaze/views/chats/chats_screen.dart'; import 'package:blaze/views/profile/profile_screen.dart'; import 'package:blaze/views/users/users_screen.dart'; import 'package:image_picker/image_picker.dart'; import 'package:blaze/components/const.dart'; import 'package:blaze/models/user.dart'; import 'package:blaze/views/home/home_screen.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'social_state.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_storage/firebase_storage.dart' as firebase_storage; import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:easy_localization/easy_localization.dart'; class SocialCubit extends Cubit<SocialStates> { SocialCubit() : super(InitialState()); static SocialCubit get(context) => BlocProvider.of(context); SocialUser user = SocialUser.empty(); bool isDark = false; void getUserData() { emit(SocialLoadingUserState()); print(uId); FirebaseFirestore.instance.collection('users').doc(uId).get().then((value) { //print(value.data()); user = SocialUser.fromJson(value.data()!); emit(SocialSuccessUserState()); print(user.uId); getUserPosts(id: user.uId); }).catchError((error) { print(error); emit(SocialErrorUserState(error.toString())); }); } int currentIndex = 0; List<Widget> screens = [ const HomeScreen(), const UsersScreen(), const ChatsScreen(), const ProfileScreen(), ]; List<String> titles = [LocaleKeys.home.tr(), LocaleKeys.chats.tr(), LocaleKeys.users.tr(), LocaleKeys.settings.tr()]; void changeNav(int index) { currentIndex = index; print(currentIndex); if (currentIndex == 3) { getUserData(); } if (currentIndex == 1) { getAllUsers(); } emit(SocialChangeNavState()); } bool isFabVisible = true; void changeHomeFab(bool change) { isFabVisible = change; emit(SocialHomeFabShowState()); } File? profileImage; var picker = ImagePicker(); Future<void> getProfileImage() async { final pickedFile = await picker.pickImage(source: ImageSource.gallery); if (pickedFile != null) { profileImage = File(pickedFile.path); print(pickedFile.path); emit(SocialImagePickedSuccessState()); } else { print('No image selected.'); emit(SocialImagePickedErrorState()); } } File? coverImage; Future<void> getCoverImage() async { final pickedFile = await picker.pickImage(source: ImageSource.gallery); if (pickedFile != null) { coverImage = File(pickedFile.path); print(pickedFile.path); emit(SocialImagePickedSuccessState()); } else { print('No image selected.'); emit(SocialImagePickedErrorState()); } } void uploadProfileImage({ required String name, required String phone, required String bio, }) { emit(SocialUserUpdateLoadingState()); firebase_storage.FirebaseStorage.instance .ref() .child('users/${Uri.file(profileImage!.path).pathSegments.last}') .putFile(profileImage!) .then((value) { value.ref.getDownloadURL().then((value) { //print(value); updateUser(name: name, phone: phone, bio: bio, profileImage: value); profileImage = null; }).catchError((error) { emit(SocialUploadImageErrorState()); }); }).catchError((error) { emit(SocialUploadImageErrorState()); }); } void uploadCoverImage({ required String name, required String phone, required String bio, }) { emit(SocialUserUpdateLoadingState()); firebase_storage.FirebaseStorage.instance .ref() .child('users/${Uri.file(coverImage!.path).pathSegments.last}') .putFile(coverImage!) .then((value) { value.ref.getDownloadURL().then((value) { //print(value); updateUser(name: name, phone: phone, bio: bio, coverImage: value); coverImage = null; }).catchError((error) { emit(SocialUploadImageErrorState()); //print(error.toString()); }); }).catchError((error) { emit(SocialUploadImageErrorState()); //print(error.toString()); }); } void updateUser({ required String name, required String phone, required String bio, String? coverImage, String? profileImage, }) { emit(SocialUserUpdateLoadingState()); SocialUser model = SocialUser( email: user.email, name: name, phone: phone, uId: user.uId, image: profileImage ?? user.image, bio: bio, followers: user.followers, cover: coverImage ?? user.cover); FirebaseFirestore.instance .collection('users') .doc(user.uId) .update(model.toJson()) .then((value) { getUserData(); }).catchError((error) { emit(SocialUserUpdateErrorState()); }); } File? postImage; Future<void> getPostImage() async { final pickedFile = await picker.pickImage(source: ImageSource.gallery); if (pickedFile != null) { postImage = File(pickedFile.path); print(pickedFile.path); emit(SocialPostImagePickedSuccessState()); } else { print('No image selected.'); emit(SocialPostImagePickedErrorState()); } } void uploadPostImage({ required String text, required String dateTime, }) { emit(SocialCreatePostLoadingState()); firebase_storage.FirebaseStorage.instance .ref() .child('posts/${Uri.file(postImage!.path).pathSegments.last}') .putFile(postImage!) .then((value) { value.ref.getDownloadURL().then((value) { createPost(text: text, dateTime: dateTime, postImage: value); //print(value); postImage = null; }).catchError((error) { emit(SocialCreatePostErrorState()); }); }).catchError((error) { emit(SocialCreatePostErrorState()); }); } void removePostImage() { postImage = null; emit(SocialPostImageRemovedSuccessState()); } void createPost({ required String text, required String dateTime, String? postImage, }) { emit(SocialUserUpdateLoadingState()); SocialPost model = SocialPost( name: user.name, uId: user.uId, image: user.image, postImage: postImage ?? '', text: text, dateTime: dateTime, likes: 0, comments: 0, ); var newPost = FirebaseFirestore.instance.collection('posts').doc(); newPost.set(model.toJson()).then((value) { emit(SocialCreatePostSuccessState()); }).catchError((error) { emit(SocialCreatePostErrorState()); }); newPost.update({'pId': newPost.id}).then((value) { emit(SocialCreatePostSuccessState()); }).catchError((error) { emit(SocialCreatePostErrorState()); }); } void deletePost(SocialPost post) { if (post.uId == user.uId) { FirebaseFirestore.instance .collection('posts') .doc(post.pId) .delete() .then((value) { emit(SocialDeletePostSuccessState()); showToast( text: 'posts deleted successfully', state: ToastState.SUCCESS); }).catchError((error) { emit(SocialDeletePostErrorState()); }); } else { showToast(text: 'you can\'t delete this post', state: ToastState.ERROR); } } List<SocialPost> posts = []; void getPosts() async { // FirebaseFirestore.instance.collection('users').doc(user.uId).collection('friends').get().then((value) { // value.docs.forEach((element) { // FirebaseFirestore.instance.collection('posts').where('uId', isEqualTo: element.id).get().then((value) => null); // }); // }); await FirebaseFirestore.instance.collection('posts').get().then((value) { int i = 0; if (value.docs.isNotEmpty) posts = []; for (var element in value.docs) { posts.add(SocialPost.fromJson(element.data())); element.reference.collection('likes').get().then((value) { posts[i].likes = value.docs.length; }).catchError((error) {}); i++; } print(posts.length); emit(SocialGetPostsSuccessState()); }).catchError((error) { print(error.toString()); emit(SocialGetPostsErrorState(error.toString())); }); } void likePost(String postId, int likes, int index) async { final snapShot = await FirebaseFirestore.instance .collection('posts') .doc(postId) .collection('likes') .doc(user.uId) .get(); if (snapShot.exists) { FirebaseFirestore.instance .collection('posts') .doc(postId) .collection('likes') .doc(user.uId) .delete() .then((value) { FirebaseFirestore.instance .collection('posts') .doc(postId) .update({'likes': likes - 1}); posts[index].likes = posts[index].likes! - 1; emit(SocialLikePostsSuccessState()); }).catchError((error) { emit(SocialLikePostsErrorState(error)); }); } else { FirebaseFirestore.instance .collection('posts') .doc(postId) .collection('likes') .doc(user.uId) .set({ 'like': true, }).then((value) { FirebaseFirestore.instance .collection('posts') .doc(postId) .update({'likes': likes + 1}); posts[index].likes = posts[index].likes! + 1; emit(SocialLikePostsSuccessState()); }).catchError((error) { emit(SocialLikePostsErrorState(error)); }); } } File? commentImage; Future<void> getCommentImage() async { final pickedFile = await picker.pickImage(source: ImageSource.gallery); if (pickedFile != null) { commentImage = File(pickedFile.path); print(pickedFile.path); emit(SocialCommentImagePickedSuccessState()); } else { print('No image selected.'); emit(SocialCommentImagePickedErrorState()); } } void removeCommentImage() { commentImage = null; emit(SocialPostImageRemovedSuccessState()); } void addComment({ required String text, required String postId, required dateTime, }) { if (commentImage != null) { firebase_storage.FirebaseStorage.instance .ref() .child('posts/${Uri.file(commentImage!.path).pathSegments.last}') .putFile(commentImage!) .then((value) { value.ref.getDownloadURL().then((value) { SocialComment comment = SocialComment( uId: user.uId, dateTime: dateTime, name: user.name, image: user.image, text: text, commentImage: value, ); var newComment = FirebaseFirestore.instance .collection('posts') .doc(postId) .collection('comments') .doc(); newComment.set(comment.toJson()).then((value) { emit(SocialCommentPostsSuccessState()); }).catchError((error) { emit(SocialCommentPostsErrorState(error)); }); newComment.update({'cId': newComment.id}); commentImage = null; }).catchError((error) { emit(SocialCommentPostsErrorState(error)); }); }).catchError((error) { emit(SocialCommentPostsErrorState(error)); }); } else { SocialComment comment = SocialComment( uId: user.uId, dateTime: dateTime, name: user.name, image: user.image, text: text, ); var newComment = FirebaseFirestore.instance .collection('posts') .doc(postId) .collection('comments') .doc(); newComment.set(comment.toJson()).then((value) { emit(SocialCommentPostsSuccessState()); }).catchError((error) { emit(SocialCommentPostsErrorState(error)); }); print(newComment.id); newComment.update({'cId': newComment.id}); } } void deleteComment(SocialComment comment, String postId) { if (comment.uId == user.uId) { FirebaseFirestore.instance .collection('posts') .doc(postId) .collection('comments') .doc(comment.cId) .delete() .then((value) { emit(SocialDeleteCommentPostsSuccessState()); }).catchError((error) { emit(SocialDeleteCommentPostsErrorState(error)); }); } } List<SocialComment> comments = []; void getCommetns({required String postId}) { comments = []; emit(SocialGetCommentsLoadingState()); FirebaseFirestore.instance .collection('posts') .doc(postId) .collection('comments') .get() .then((value) { value.docs.forEach((element) { comments.add(SocialComment.fromJson(element.data())); }); emit(SocialGetCommentsSuccessState()); }).catchError((error) { print(error.toString()); emit(SocialGetCommentsErrorState(error)); }); } List<SocialUser> allUsers = []; void getAllUsers() async { allUsers = []; emit(SocialGetAllUsersLoadingState()); await FirebaseFirestore.instance.collection('users').get().then((value) { for (var element in value.docs) { if (element.data()['uId'] == user.uId) { continue; } else { allUsers.add(SocialUser.fromJson(element.data())); } } emit(SocialGetAllUsersSuccessState()); }).catchError((error) { print(error.toString()); emit(SocialGetAllUsersErrorState(error.toString())); }); } void sendMessage(String receiverId, String dateTime, String text) { SocialMessage message = SocialMessage( reciverId: receiverId, dateTime: dateTime, senderId: user.uId, text: text); FirebaseFirestore.instance .collection('users') .doc(user.uId) .collection('chats') .doc(receiverId) .collection('messages') .add(message.toJson()) .then((value) { emit(SocialSendMessageSuccessState()); }).catchError((error) { emit(SocialSendMessageErrorState(error)); }); FirebaseFirestore.instance .collection('users') .doc(receiverId) .collection('chats') .doc(user.uId) .collection('messages') .add(message.toJson()) .then((value) { emit(SocialSendMessageSuccessState()); }).catchError((error) { emit(SocialSendMessageErrorState(error)); }); } List<SocialMessage> messages = []; void getMessages({required String receiverId}) { FirebaseFirestore.instance .collection('users') .doc(user.uId) .collection('chats') .doc(receiverId) .collection('messages') .orderBy('dateTime') .snapshots() .listen((event) { messages = []; for (var element in event.docs) { messages.add(SocialMessage.fromJson(element.data())); } }); emit(SocialGetMessageSuccessState()); } void refershPage(int index) { emit(Loading()); if (index == 1) { getAllUsers(); } else if (index == 2) { getFollowers(); } else if (index == 0) { getPosts(); } else if (index == 3) { getUserData(); } emit(Loaded()); } void follow(String followId) { FirebaseFirestore.instance .collection('users') .doc(user.uId) .collection('friends') .doc(followId) .set({'follow': true}).then((value) { emit(SocialFollowSuccessState()); getFollowers(); FirebaseFirestore.instance .collection('users') .doc(followId) .get() .then((value) { FirebaseFirestore.instance .collection('users') .doc(followId) .update({'followers': value.data()!['followers'] + 1}); }); }).catchError((error) { emit(SocialFollowErrorState(error)); }); } void unfollow(String followId) { FirebaseFirestore.instance .collection('users') .doc(user.uId) .collection('friends') .doc(followId) .delete() .then((value) { emit(SocialUnfollowSuccessState()); FirebaseFirestore.instance .collection('users') .doc(followId) .get() .then((value) { FirebaseFirestore.instance .collection('users') .doc(followId) .update({'followers': value.data()!['followers'] - 1}); }); getFollowers(); }).catchError((error) { emit(SocialUnFollowErrorState(error)); }); } List<SocialUser> followers = []; void getFollowers() async { followers = []; emit(SocialGetFollowersLoadingState()); user.uId = uId!; await FirebaseFirestore.instance .collection("users") .doc(user.uId) .collection("friends") .get() .then((value) { for (var element in value.docs) { FirebaseFirestore.instance .collection('users') .doc(element.id) .get() .then((value) { followers.add(SocialUser.fromJson(value.data()!)); }); } emit(SocialGetFollowersSuccessState()); }).catchError((error) { emit(SocialGetFollowersErrorState(error)); }); } List<SocialPost> userPosts = []; void getUserPosts({required id}) async { userPosts = []; emit(SocialGetUserPostsLoadingState()); //print(id); int i = 0; FirebaseFirestore.instance .collection('posts') .where('uId', isEqualTo: id) .get() .then((value) { for (var element in value.docs) { userPosts.add(SocialPost.fromJson(element.data())); element.reference.collection('likes').get().then((value) { posts[i].likes = value.docs.length; }).catchError((error) {}); i++; } }).then((value) { print(userPosts); emit(SocialGetUserPostsSuccessState()); }).catchError((error) { emit(SocialGetUserPostsErrorState(error)); }); } List<SocialUser> searchResualt = []; void search({required String s}) { emit(SocialSearchLoadingState()); for (var element in allUsers) { //print(element.name.toLowerCase()); //print(s.toLowerCase()); if (element.name.toLowerCase().contains(s.toLowerCase())) { searchResualt.add(element); } } emit(SocialSearchSuccessState()); } void saveImage(String imageUrl) async { // Uri imgeUri = Uri(scheme: 'https', path: imageUrl, host: 'firebasestorage.googleapis.com'); // var response = await http.get(imgeUri); // Directory documentDirectory = await getApplicationDocumentsDirectory(); // File file = File(join(documentDirectory.path, 'imagetest.png')); // file.writeAsBytesSync(response.bodyBytes); } void logOut(context) { emit(SignOutLoadingState()); FirebaseAuth.instance.signOut().then((value) async { CacheHelper.removeData(key: 'uId'); await FirebaseMessaging.instance.deleteToken(); // await FirebaseFirestore.instance.collection('users').get().then((value) { // value.docs.forEach((element) async { // if (element.id == user.uId) // element.reference.update({'token': null}); // }); // }); Navigator.pushNamedAndRemoveUntil(context, '/login', (route) => false); emit(SignOutSuccessState()); }).catchError((error) { emit(SignOutErrorState(error)); }); } void changeAppMode({bool? fromShared}) { isDark = !isDark; CacheHelper.saveData(key: 'isDark', value: isDark).then((value) { emit(SocialAppChangeModeState()); }); print(isDark); } List<bool> isSelected = [lang == 'ar' ? true : false ,lang == 'en' ? true : false ]; void changeLanguage(String lang1){ lang = lang1; CacheHelper.saveData(key: 'lang', value: lang1 ); emit(ChangeLanguageState()); } }
0
mirrored_repositories/blaze/blaze/lib/helpers
mirrored_repositories/blaze/blaze/lib/helpers/cubits/social_state.dart
abstract class SocialStates {} ///General States class InitialState extends SocialStates {} class ChangeModeState extends SocialStates {} class SocialChangeNavState extends SocialStates {} //user class SocialLoadingUserState extends SocialStates {} class SocialSuccessUserState extends SocialStates {} class SocialErrorUserState extends SocialStates { final String error; SocialErrorUserState(this.error); } //profile class SocialImagePickedSuccessState extends SocialStates {} class SocialImagePickedErrorState extends SocialStates {} class SocialUserUpdateLoadingState extends SocialStates {} class SocialUserUpdateErrorState extends SocialStates {} class SocialUserUpdateSuccessState extends SocialStates {} class SocialUploadImageErrorState extends SocialStates {} //post class SocialPostImagePickedSuccessState extends SocialStates {} class SocialPostImageRemovedSuccessState extends SocialStates {} class SocialPostImagePickedErrorState extends SocialStates {} class SocialCreatePostLoadingState extends SocialStates {} class SocialCreatePostErrorState extends SocialStates {} class SocialCreatePostSuccessState extends SocialStates {} class SocialDeletePostErrorState extends SocialStates {} class SocialDeletePostSuccessState extends SocialStates {} //posts class SocialGetPostsLoadingState extends SocialStates {} class SocialGetPostsSuccessState extends SocialStates {} class SocialGetPostsErrorState extends SocialStates { final String error; SocialGetPostsErrorState(this.error); } //like post class SocialLikePostsSuccessState extends SocialStates {} class SocialLikePostsErrorState extends SocialStates { final String error; SocialLikePostsErrorState(this.error); } //comment post class SocialCommentPostsSuccessState extends SocialStates {} class SocialCommentPostsErrorState extends SocialStates { final String error; SocialCommentPostsErrorState(this.error); } class SocialDeleteCommentPostsSuccessState extends SocialStates {} class SocialDeleteCommentPostsErrorState extends SocialStates { final String error; SocialDeleteCommentPostsErrorState(this.error); } class SocialCommentImagePickedSuccessState extends SocialStates {} class SocialCommentImageRemovedSuccessState extends SocialStates {} class SocialCommentImagePickedErrorState extends SocialStates {} class SocialGetCommentsLoadingState extends SocialStates {} class SocialGetCommentsSuccessState extends SocialStates {} class SocialGetCommentsErrorState extends SocialStates { final String error; SocialGetCommentsErrorState(this.error); } //users class SocialGetAllUsersLoadingState extends SocialStates {} class SocialGetAllUsersSuccessState extends SocialStates {} class SocialGetAllUsersErrorState extends SocialStates { final String error; SocialGetAllUsersErrorState(this.error); } // message class SocialGetMessageSuccessState extends SocialStates {} class SocialSendMessageSuccessState extends SocialStates {} class SocialSendMessageErrorState extends SocialStates { final String error; SocialSendMessageErrorState(this.error); } //FAB visibilit class SocialHomeFabShowState extends SocialStates {} //refersh class Loaded extends SocialStates {} class Loading extends SocialStates{} //follow class SocialFollowSuccessState extends SocialStates {} class SocialFollowErrorState extends SocialStates { final String error; SocialFollowErrorState(this.error); } class SocialUnfollowSuccessState extends SocialStates {} class SocialUnFollowErrorState extends SocialStates { final String error; SocialUnFollowErrorState(this.error); } class SocialGetFollowersLoadingState extends SocialStates {} class SocialGetFollowersSuccessState extends SocialStates {} class SocialGetFollowersErrorState extends SocialStates { final String error; SocialGetFollowersErrorState(this.error); } //user post class SocialGetUserPostsLoadingState extends SocialStates {} class SocialGetUserPostsSuccessState extends SocialStates {} class SocialGetUserPostsErrorState extends SocialStates { final String error; SocialGetUserPostsErrorState(this.error); } //search class SocialSearchLoadingState extends SocialStates {} class SocialSearchSuccessState extends SocialStates {} class SocialSearchErrorState extends SocialStates { final String error; SocialSearchErrorState(this.error); } //logout class SignOutLoadingState extends SocialStates {} class SignOutSuccessState extends SocialStates {} class SignOutErrorState extends SocialStates { final String error; SignOutErrorState(this.error); } //theme class SocialAppChangeModeState extends SocialStates {} //lang class ChangeLanguageState extends SocialStates {}
0
mirrored_repositories/blaze/blaze/lib/helpers
mirrored_repositories/blaze/blaze/lib/helpers/local/chache_helper.dart
import 'package:shared_preferences/shared_preferences.dart'; class CacheHelper { static SharedPreferences? sharedPreferences; static init() async { sharedPreferences = await SharedPreferences.getInstance(); } static Future<bool> saveBoolean({ required String key, required bool value, }) async { return await sharedPreferences!.setBool(key, value); } static dynamic getData({ required String key, }) { return sharedPreferences!.get(key); } static Future<bool> saveData({ required String key, required dynamic value, }) async { if (value is String) return await sharedPreferences!.setString(key, value); if (value is int) return await sharedPreferences!.setInt(key, value); if (value is bool) return await sharedPreferences!.setBool(key, value); return await sharedPreferences!.setDouble(key, value); } static Future<bool> removeData({ required String key, }) async { return await sharedPreferences!.remove(key); } }
0
mirrored_repositories/blaze/blaze
mirrored_repositories/blaze/blaze/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:blaze/views/login/login_screen.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:blaze/main.dart'; void main() { Widget startWidget = SocialLogin(); bool isDark = false; testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget( MyApp(startWidget: startWidget, isDark: isDark)); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/Flutter_AppLoginScreen
mirrored_repositories/Flutter_AppLoginScreen/lib/main.dart
import 'package:flutter/material.dart'; void main() => runApp(new MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( debugShowCheckedModeBanner: false, home:new LoginPage(), theme:new ThemeData(primarySwatch:Colors.blue), ); } } class LoginPage extends StatefulWidget { @override State createState() => new LoginPageState(); } class LoginPageState extends State < LoginPage > with SingleTickerProviderStateMixin { AnimationController _iconAnimationController; Animation < double > _iconAnimation; @override void initState() { super.initState(); _iconAnimationController = new AnimationController( vsync:this, duration:new Duration(milliseconds:500)); _iconAnimation = new CurvedAnimation( parent:_iconAnimationController, curve:Curves.easeOut); _iconAnimation.addListener(() => this.setState(() {})); _iconAnimationController.forward(); } @override Widget build(BuildContext context) { return new Scaffold( resizeToAvoidBottomPadding: false, backgroundColor:Colors.pinkAccent, body:new Stack( fit:StackFit.expand, children: < Widget > [ new Image( image:new AssetImage("assets/login_back.jpg"), fit:BoxFit.cover, color:Colors.black54, colorBlendMode:BlendMode.darken, ), new Column( mainAxisAlignment:MainAxisAlignment.center, children: < Widget > [ new Image( image:new AssetImage("assets/3d.png"), height:150.0, width:150.0, ), new Form( child:new Theme( data:new ThemeData( brightness:Brightness.dark, primarySwatch:Colors.pink, inputDecorationTheme:InputDecorationTheme( labelStyle:new TextStyle( color:Colors.pink, fontSize:20.0, ))), child:new Container( padding:const EdgeInsets.all(40.0), child:new Column( crossAxisAlignment:CrossAxisAlignment.center, children: < Widget > [ new TextFormField( decoration: new InputDecoration(labelText:"Enter Email"), keyboardType:TextInputType.emailAddress, ), new TextFormField( decoration: new InputDecoration(labelText:"Enter Password"), keyboardType:TextInputType.text, obscureText:true, ), new Padding( padding:const EdgeInsets.only(top:40.0), ), new MaterialButton( height:50.0, minWidth:120.0, color:Colors.pink, textColor:Colors.white, child:new Icon(Icons.input, size:30), onPressed:() => {}, ) ], ), ), ), ) ], ) ], ), ); } }
0
mirrored_repositories/Flutter_AppLoginScreen
mirrored_repositories/Flutter_AppLoginScreen/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_login_app/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/module17_google_map_assignment
mirrored_repositories/module17_google_map_assignment/lib/main.dart
import 'package:flutter/material.dart'; import 'package:module17_google_map_assignment/map_screen.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: MapScreen(), ); } }
0
mirrored_repositories/module17_google_map_assignment
mirrored_repositories/module17_google_map_assignment/lib/map_screen.dart
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'package:location/location.dart'; class MapScreen extends StatefulWidget { const MapScreen({super.key}); @override _MapScreenState createState() => _MapScreenState(); } class _MapScreenState extends State<MapScreen> { GoogleMapController? _mapController; final Location _location = Location(); Marker? _marker; Polyline? _polyline; final List<LatLng> _polylineCoordinates = []; _initLocation() async { bool serviceEnabled; PermissionStatus permissionGranted; serviceEnabled = await _location.serviceEnabled(); if (!serviceEnabled) { serviceEnabled = await _location.requestService(); if (!serviceEnabled) { return; } } permissionGranted = await _location.hasPermission(); if (permissionGranted == PermissionStatus.denied) { permissionGranted = await _location.requestPermission(); if (permissionGranted != PermissionStatus.granted) { return; } } _location.onLocationChanged.listen((LocationData result) { if (_mapController != null) { _updateMarker(result); _updatePolyline(result); _animateToLocation(result); } }); Timer.periodic(const Duration(seconds: 10), (Timer timer) async { LocationData locationData = await _location.getLocation(); if (_mapController != null) { _updateMarker(locationData); _updatePolyline(locationData); _animateToLocation(locationData); } }); } _showInfoWindow(LocationData locationData) { _mapController!.showMarkerInfoWindow(const MarkerId('myLocation')); } _updateMarker(LocationData locationData) { setState(() { _marker = Marker( infoWindow: InfoWindow( title: "My Current Location", snippet: "${locationData.latitude!}, ${locationData.longitude!}", ), markerId: const MarkerId('myLocation'), position: LatLng(locationData.latitude!, locationData.longitude!), onTap: () { _showInfoWindow(locationData); }, ); }); } _updatePolyline(LocationData locationData) { if (_polylineCoordinates.isNotEmpty) { _polylineCoordinates .add(LatLng(locationData.latitude!, locationData.longitude!)); setState(() { _polyline = Polyline( polylineId: const PolylineId('trackingPath'), color: Colors.blue, points: _polylineCoordinates, visible: true, width: 6, ); }); } } _animateToLocation(LocationData locationData) { _mapController?.animateCamera( CameraUpdate.newCameraPosition( CameraPosition( target: LatLng(locationData.latitude!, locationData.longitude!), zoom: 15.0, ), ), ); } @override void initState() { super.initState(); _initLocation(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text( 'Real-Time Location Tracker', style: TextStyle(color: Colors.white), ), backgroundColor: Colors.blue, ), body: GoogleMap( myLocationEnabled: true, compassEnabled: true, onMapCreated: (GoogleMapController controller) { _mapController = controller; }, initialCameraPosition: const CameraPosition( target: LatLng(0.0, 0.0), zoom: 17, ), markers: _marker != null ? <Marker>{_marker!} : <Marker>{}, polylines: _polyline != null ? <Polyline>{_polyline!} : <Polyline>{}, ), ); } }
0
mirrored_repositories/module17_google_map_assignment
mirrored_repositories/module17_google_map_assignment/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility in the flutter_test package. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:module17_google_map_assignment/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/sticker-chat
mirrored_repositories/sticker-chat/lib/main.dart
import 'package:flutter/material.dart'; import 'package:sticker_chat/app/app.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; void main() async { const STREAM_KEY = String.fromEnvironment('api'); const USER_TOKEN = String.fromEnvironment('token'); final client = StreamChatClient( STREAM_KEY, logLevel: Level.OFF, ); await client.connectUser( User( id: 'neevash', extraData: { 'image': 'https://local.getstream.io:9000/random_png/?id=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiZGVsaWNhdGUtZmlyZS02In0.Yfdnsfkt48g1xv3I77mBjlVISnLwMyVUFobBynTf6Jc&amp;name=nash', }, ), USER_TOKEN, ); runApp(StickerChat(client: client)); }
0
mirrored_repositories/sticker-chat/lib
mirrored_repositories/sticker-chat/lib/app/app.dart
import 'package:flutter/material.dart'; import 'package:sticker_chat/screens/mobile/channel_page.dart'; import 'package:sticker_chat/screens/desktop/desktop_layout.dart'; import 'package:sticker_chat/widgets/widgets.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; class StickerChat extends StatelessWidget { const StickerChat({Key? key, required this.client}) : super(key: key); final StreamChatClient client; @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Sticker Chat 😎', builder: (context, widget) { return StreamChat( child: widget!, client: client, ); }, home: ResponsiveBuilder( smallScreen: (context) => ChannelListPage(), largeScreen: (context) => Material(child: DesktopLayout()), ), ); } }
0
mirrored_repositories/sticker-chat/lib
mirrored_repositories/sticker-chat/lib/widgets/widgets.dart
export './animated_attachment.dart'; export './chat_sticker_dialog.dart'; export './responsive_builder.dart';
0
mirrored_repositories/sticker-chat/lib
mirrored_repositories/sticker-chat/lib/widgets/responsive_builder.dart
import 'package:flutter/material.dart'; class ResponsiveBuilder extends StatelessWidget { const ResponsiveBuilder({ Key? key, required this.smallScreen, this.largeScreen, }) : super(key: key); final WidgetBuilder smallScreen; final WidgetBuilder? largeScreen; @override Widget build(BuildContext context) { final shortestSide = MediaQuery.of(context).size.shortestSide; if (shortestSide <= 768) { return smallScreen(context); } else if (shortestSide > 768 && largeScreen != null) { return largeScreen!(context); } else { return smallScreen(context); } } }
0
mirrored_repositories/sticker-chat/lib
mirrored_repositories/sticker-chat/lib/widgets/chat_sticker_dialog.dart
import 'package:flutter/material.dart'; import 'package:sticker_chat/models/models.dart'; import 'package:sticker_chat/utils/extensions.dart'; import 'animated_attachment.dart'; class ChatStickerDialog extends StatelessWidget { @override Widget build(BuildContext context) { return Dialog( insetPadding: EdgeInsets.symmetric( horizontal: context.isMobile ? 40.0 : 400.0, vertical:context.isMobile ? 80.0 : 150.0, ), child: Padding( padding: const EdgeInsets.all(12.0), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Align( alignment: Alignment.centerRight, child: Padding( padding: const EdgeInsets.only(bottom: 12.0), child: IconButton( icon: Icon(Icons.close), onPressed: () => Navigator.of(context).pop(), ), ), ), Expanded( child: GridView.builder( gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, crossAxisSpacing: 12.0, mainAxisSpacing: 12.0, ), itemCount: kAssets.length, itemBuilder: (context, index) { return AnimatedAttachment( sticker: kAssets[index].assetPath, onItemTap: (item) { Navigator.of(context).pop(item); }, ); }, ), ), ], ), ), ); } }
0
mirrored_repositories/sticker-chat/lib
mirrored_repositories/sticker-chat/lib/widgets/animated_attachment.dart
import 'package:flutter/material.dart'; import 'package:rive/rive.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; class AnimatedAttachment extends StatelessWidget { const AnimatedAttachment({ Key? key, required this.sticker, this.onItemTap, }) : super(key: key); final String sticker; final ValueChanged<String>? onItemTap; @override Widget build(BuildContext context) { return wrapAttachmentWidget( context, InkWell( onTap: onItemTap != null ? () => onItemTap!(sticker) : null, child: RiveAnimation.asset( sticker, fit: BoxFit.fill, ), ), RoundedRectangleBorder( borderRadius: BorderRadius.circular(12.0), ), false, ); } }
0
mirrored_repositories/sticker-chat/lib
mirrored_repositories/sticker-chat/lib/models/animated_sticker_model.dart
class AnimatedStickers { const AnimatedStickers(this.assetPath); final String assetPath; } const kAssets = <AnimatedStickers>[ AnimatedStickers( "assets/478-978-message-icon.riv", ), AnimatedStickers( "assets/471-892-boo-the-ghost.riv", ), AnimatedStickers( "assets/412-781-mad-scientist-login.riv", ), AnimatedStickers( "assets/440-811-helix-loader.riv", ), AnimatedStickers( "assets/262-518-eggard-is-a-gud-boi.riv", ), AnimatedStickers( "assets/274-540-dolphin-swimming.riv", ), AnimatedStickers( "assets/479-941-clean-the-car.riv", ), AnimatedStickers( "assets/437-807-document-icon.riv", ), AnimatedStickers( "assets/340-656-like-button.riv", ), AnimatedStickers( "assets/299-648-the-balloonist.riv", ), ];
0
mirrored_repositories/sticker-chat/lib
mirrored_repositories/sticker-chat/lib/models/models.dart
export './animated_sticker_model.dart';
0
mirrored_repositories/sticker-chat/lib
mirrored_repositories/sticker-chat/lib/utils/extensions.dart
import 'package:flutter/material.dart'; extension ISMobileExtension on BuildContext{ bool get isMobile => MediaQuery.of(this).size.shortestSide <= 768; }
0
mirrored_repositories/sticker-chat/lib/screens
mirrored_repositories/sticker-chat/lib/screens/mobile/message_page.dart
import 'package:flutter/material.dart'; import 'package:sticker_chat/widgets/widgets.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; class MessagePage extends StatefulWidget { const MessagePage({ Key? key, this.showBackButton = true, }) : super(key: key); final bool showBackButton; @override _MessagePageState createState() => _MessagePageState(); } class _MessagePageState extends State<MessagePage> { GlobalKey<MessageInputState> _messageInputKey = GlobalKey(); Future<void> _showStickerModal() async { final result = await showDialog<String>( context: context, builder: (context) => ChatStickerDialog(), ); _addAttachment(result); } void _addAttachment(String? selectedSticker) { if (selectedSticker != null) { _messageInputKey.currentState?.addAttachment( Attachment( type: 'animated.sticker', uploadState: UploadState.success(), extraData: { 'sticker_url': selectedSticker, }, ), ); } } Widget _buildAnimatedMessage( BuildContext context, Message details, List<Attachment> _, ) { final url = details.attachments.first.extraData['sticker_url'] as String; return SizedBox( height: 250.0, width: 250.0, child: AnimatedAttachment( sticker: url, ), ); } @override Widget build(BuildContext context) { return Scaffold( appBar: ChannelHeader( showBackButton: widget.showBackButton, ), body: Column( children: <Widget>[ Expanded( child: MessageListView( messageBuilder: ( BuildContext context, MessageDetails _, List<Message> messages, MessageWidget defaultMessageWidget, ) { return defaultMessageWidget.copyWith( customAttachmentBuilders: { 'animated.sticker': _buildAnimatedMessage }, ); }, ), ), MessageInput( key: _messageInputKey, attachmentThumbnailBuilders: { 'animated.sticker': (context, attachment) => AnimatedAttachment( sticker: attachment.extraData['sticker_url'] as String, ), }, actions: [ IconButton( onPressed: _showStickerModal, icon: Icon(Icons.add_box_rounded), ) ], ), ], ), ); } }
0
mirrored_repositories/sticker-chat/lib/screens
mirrored_repositories/sticker-chat/lib/screens/mobile/channel_page.dart
import 'package:flutter/material.dart'; import 'package:sticker_chat/screens/mobile/message_page.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; class ChannelListPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Sticker Chat 😎'), ), body: ChannelsBloc( child: ChannelListView( filter: Filter.in_('members', [StreamChat.of(context).currentUser!.id]), sort: [SortOption('last_message_at')], limit: 30, channelWidget: Builder(builder: (context) => MessagePage()), ), ), ); } }
0
mirrored_repositories/sticker-chat/lib/screens
mirrored_repositories/sticker-chat/lib/screens/desktop/desktop_layout.dart
import 'package:flutter/material.dart'; import 'package:sticker_chat/screens/mobile/message_page.dart'; import 'package:stream_chat_flutter/stream_chat_flutter.dart'; class DesktopLayout extends StatefulWidget { @override _DesktopLayoutState createState() => _DesktopLayoutState(); } class _DesktopLayoutState extends State<DesktopLayout> { Channel? selectedChannel; @override Widget build(BuildContext context) { return Row( children: [ _DesktopChannelList(onChannelTap: (channel) { setState(() { selectedChannel = channel; }); }), if (selectedChannel == null) _GettingStartedPlaceholder(), if (selectedChannel != null) _DesktopChatView( selectedChannel: selectedChannel!, ) ], ); } } class _DesktopChannelList extends StatelessWidget { const _DesktopChannelList({ Key? key, required this.onChannelTap, }) : super(key: key); final ValueChanged<Channel> onChannelTap; @override Widget build(BuildContext context) { return Expanded( flex: 1, child: Column( children: [ Container( height: 150.0, color: Colors.blueAccent.withOpacity(0.34), child: Center( child: Text( "Sticker Chat 😎", style: TextStyle( fontSize: 32.0, fontWeight: FontWeight.bold, ), ), ), ), Expanded( child: ChannelsBloc( child: ChannelListView( onChannelTap: (channel, _) => onChannelTap(channel), filter: Filter.in_( 'members', [StreamChat.of(context).currentUser!.id]), sort: [SortOption('last_message_at')], limit: 30, ), ), ), ], ), ); } } class _DesktopChatView extends StatelessWidget { const _DesktopChatView({Key? key, required this.selectedChannel}) : super(key: key); final Channel selectedChannel; @override Widget build(BuildContext context) { return Expanded( flex: 2, child: StreamChannel( channel: selectedChannel, child: MessagePage(showBackButton: false), ), ); } } class _GettingStartedPlaceholder extends StatelessWidget { @override Widget build(BuildContext context) { return Expanded( flex: 2, child: Container( child: Center( child: Column( mainAxisSize: MainAxisSize.min, children: [ Icon( Icons.chat, size: 32.0, ), const SizedBox(height: 12.0), Text( 'Select a chat to get the conversation going...', style: TextStyle( fontSize: 16.0, fontWeight: FontWeight.w700, ), ), ], ), ), ), ); } }
0
mirrored_repositories/flutter-notes
mirrored_repositories/flutter-notes/lib/main.dart
import 'package:blog/config/router.dart'; import 'package:blog/cubit/Note.cubit.dart'; import 'package:blog/cubit/Group.cubit.dart'; // Import your TagCubit import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; void main() async { // Ensure proper initialization of Flutter bindings WidgetsFlutterBinding.ensureInitialized(); // Initialize cubits final NoteCubit noteCubit = NoteCubit(); final GroupCubit groupCubit = GroupCubit(); runApp( MultiBlocProvider( providers: [ BlocProvider<NoteCubit>.value( value: noteCubit, ), BlocProvider<GroupCubit>.value( value: groupCubit, ), ], child: const MyApp(), ), ); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp.router( debugShowCheckedModeBanner: false, title: 'Notes', routerConfig: router, ); } }
0
mirrored_repositories/flutter-notes/lib
mirrored_repositories/flutter-notes/lib/models/Note.model.dart
import 'package:blog/models/Group.model.dart'; import 'package:flutter/material.dart'; const int MAX_PREVIEW_LENGTH = 250; const int MAX_TITLE_LENGTH = 20; const int MAXIMUM_PREVIEW_NEW_LINE = 5; class Note { final String id = UniqueKey().toString(); String title; String description; String content; final DateTime? createdAt = DateTime.now(); List<Group> groups = []; Color color = Colors.black; Note({ String title = 'New Note', this.description = 'Basic Note', this.content = '', this.color = Colors.black, }) : groups = [], title = title.length > MAX_TITLE_LENGTH ? '${title.substring(0, MAX_TITLE_LENGTH)}...' : title; String get preview { // check if the content has new line character and count it int newLineCount = 0; for (int i = 0; i < content.length; i++) { if (content[i] == '\n') { newLineCount++; } } // if the content has new line character, we will only show the first 3 lines if (newLineCount > MAXIMUM_PREVIEW_NEW_LINE) { String preview = ''; int newLineCount = 0; for (int i = 0; i < content.length; i++) { if (content[i] == '\n') { newLineCount++; } if (newLineCount == MAXIMUM_PREVIEW_NEW_LINE) { break; } preview += content[i]; } return '$preview...'; } if (content.length > MAX_PREVIEW_LENGTH) { return '${content.substring(0, MAX_PREVIEW_LENGTH)}...'; } return content; } void addGroup(Group group) { groups.add(group); } void removeGroup(Group group) { groups.remove(group); } void setGroup(List<Group> groups) { this.groups = groups; } factory Note.fromJson(Map<String, dynamic> json) { Note note = Note( title: json['title'] ?? 'New Note', description: json['description'] ?? '', content: json['content'] ?? '', color: Color(json['color'] ?? Colors.black.value), ); if (json['groups'] != null) { final List<dynamic> jsonData = json['groups']; final List<Group> loadedGroups = jsonData.map((jsonItem) => Group.fromJson(jsonItem)).toList(); note.setGroup(loadedGroups); } return note; } Map<String, dynamic> toJson() { return { 'title': title, 'description': description, 'content': content, 'color': color.value, // Convert the Color object to an integer 'groups': groups.map((group) => group.toJson()).toList(), }; } }
0
mirrored_repositories/flutter-notes/lib
mirrored_repositories/flutter-notes/lib/models/Group.model.dart
import 'package:flutter/material.dart'; class Group { String id = UniqueKey().toString(); String name; String description; Color color; IconData icon; DateTime? createdAt = DateTime.now(); Group({ required String id, this.name = "New Group", this.description = "New Group Description", this.color = Colors.black, this.icon = Icons.group, }) : id = id.isNotEmpty ? id : UniqueKey().toString(); factory Group.fromJson(Map<String, dynamic> json) { return Group( id: json['id'] as String, name: json['name'], description: json['description'], color: Color(json['color'] as int), icon: IconData(json['icon'] as int, fontFamily: 'MaterialIcons'), ); } Map<String, dynamic> toJson() { return { 'id': id != '' ? id : UniqueKey().toString(), 'name': name, 'description': description, 'color': color.value, // Storing color as integer 'icon': icon.codePoint, // Storing icon as integer }; } }
0
mirrored_repositories/flutter-notes/lib
mirrored_repositories/flutter-notes/lib/delegates/NoteSearchDelegate.dart
import 'package:blog/ui/list/NoteListView.dart'; import 'package:flutter/material.dart'; class NoteSearchDelegate extends SearchDelegate<String> { @override List<Widget> buildActions(BuildContext context) { // Actions for the AppBar, like a clear button return [ IconButton( icon: Icon(Icons.clear), onPressed: () { query = ''; // Clears the search query }, ), ]; } @override Widget buildLeading(BuildContext context) { // A leading icon on the left of the AppBar return IconButton( icon: Icon(Icons.arrow_back), onPressed: () { close(context, ''); // Closes the search delegate }, ); } @override Widget buildResults(BuildContext context) { // Show some result based on the selection return Padding( padding: const EdgeInsets.all(8.0), child: NoteListView( query: query, ), ); } @override Widget buildSuggestions(BuildContext context) { // Show suggestions while the user types // Implement your logic to show suggestions based on the query return Container(); } }
0
mirrored_repositories/flutter-notes/lib
mirrored_repositories/flutter-notes/lib/config/quill_configurations.dart
import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter_quill/flutter_quill.dart'; class QuillConfigurations { static QuillController getController({required String jsonContent}) { return QuillController( document: Document.fromJson(jsonDecode(jsonContent)), selection: TextSelection.collapsed(offset: 0), ); } static QuillEditorConfigurations getEditorConfigurations({required QuillController controller}) { return QuillEditorConfigurations( controller: controller, readOnly: false, sharedConfigurations: const QuillSharedConfigurations( locale: Locale('fr'), ), ); } static QuillSimpleToolbarConfigurations getToolbarConfigurations({required QuillController controller}) { return QuillSimpleToolbarConfigurations( toolbarSize: 40, controller: controller, multiRowsDisplay: false, showColorButton: false, showBackgroundColorButton: false, showUnderLineButton: true, showStrikeThrough: true, showDividers: false, showFontFamily: false, showDirection: false, showInlineCode: false, showListCheck: true, showClearFormat: true, showSubscript: false, showSuperscript: false, showSearchButton: false, showSmallButton: false, ); } }
0
mirrored_repositories/flutter-notes/lib
mirrored_repositories/flutter-notes/lib/config/font.dart
// enum of text styles import 'package:flutter/material.dart'; enum TextStyles { h1, h2, h3, h4, h5, h6, bodyText1, bodyText2, subtitle1, subtitle2, caption, button, overline, } // enum of text styles enum FontWeights { thin, extraLight, light, regular, medium, semiBold, bold, extraBold, black, } const commonFontFamily = 'Roboto'; // define map of text styles based on base font style and enum of text styles const Map<TextStyles, TextStyle> textStyles = { TextStyles.h1: TextStyle( fontFamily: commonFontFamily, fontSize: 32, fontWeight: FontWeight.w300, letterSpacing: -1.5, ), TextStyles.h2: TextStyle( fontFamily: commonFontFamily, fontSize: 28, fontWeight: FontWeight.w300, letterSpacing: -0.5, ), TextStyles.h3: TextStyle( fontFamily: commonFontFamily, fontSize: 20, fontWeight: FontWeight.w400, ), TextStyles.h4: TextStyle( fontFamily: commonFontFamily, fontSize: 18, fontWeight: FontWeight.w400, letterSpacing: 0.25, ), TextStyles.h5: TextStyle( fontFamily: commonFontFamily, fontSize: 16, fontWeight: FontWeight.w400, ), TextStyles.h6: TextStyle( fontFamily: commonFontFamily, fontSize: 12, fontWeight: FontWeight.w500, letterSpacing: 0.15, ), TextStyles.bodyText1: TextStyle( fontFamily: commonFontFamily, fontSize: 11, fontWeight: FontWeight.w400, letterSpacing: 0.3, ), TextStyles.bodyText2: TextStyle( fontFamily: commonFontFamily, fontSize: 10, fontWeight: FontWeight.w400, letterSpacing: 0.25, ), TextStyles.subtitle1: TextStyle( fontFamily: commonFontFamily, fontSize: 16, fontWeight: FontWeight.w400, letterSpacing: 0.15, ), TextStyles.subtitle2: TextStyle( fontFamily: commonFontFamily, fontSize: 14, fontWeight: FontWeight.w500, letterSpacing: 0.1, ), TextStyles.caption: TextStyle( fontFamily: commonFontFamily, fontSize: 12, fontWeight: FontWeight.w400, letterSpacing: 0.4, ), TextStyles.button: TextStyle( fontFamily: commonFontFamily, fontSize: 14, fontWeight: FontWeight.w500, letterSpacing: 1.25, ), TextStyles.overline: TextStyle( fontFamily: commonFontFamily, fontSize: 10, fontWeight: FontWeight.w400, letterSpacing: 1.5, ), }; TextStyle getTextStyleWithColor(TextStyles textStyle, Color color) { return textStyles[textStyle]!.copyWith(color: color); }
0
mirrored_repositories/flutter-notes/lib
mirrored_repositories/flutter-notes/lib/config/router.dart
import 'package:blog/models/Group.model.dart'; import 'package:blog/models/Note.model.dart'; import 'package:blog/ui/views/GroupCreationPage.dart'; import 'package:blog/ui/views/GroupNotePage.dart'; import 'package:blog/ui/views/HomePage.dart'; import 'package:blog/ui/views/NoteCreationPage.dart'; import 'package:blog/ui/views/GroupsPage.dart'; import 'package:blog/ui/views/SettingsPage.dart'; import 'package:blog/ui/widget/ScaffoldWithNavbar.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; final List<Map<String, dynamic>> navBarItems = [ { 'label': 'Home', 'icon': Icons.home, 'route': '/home', 'onTap': (BuildContext context) { GoRouter.of(context).replace('/home'); }, }, { 'label': 'Groups', 'icon': Icons.tag, 'route': '/groups', 'onTap': (BuildContext context) { GoRouter.of(context).replace('/groups'); }, }, { 'label': 'Settings', 'icon': Icons.settings, 'route': '/settings', 'onTap': (BuildContext context) { GoRouter.of(context).replace('/settings'); }, }, ]; final router = GoRouter( initialLocation: '/home', routes: [ ShellRoute( builder: (context, state, child) { return ScaffoldWithNavBar(child: child); }, routes: [ GoRoute( path: '/home', builder: (context, state) => const HomePage(), ), GoRoute( path: '/groups', builder: (context, state) => const GroupsPage(), ), GoRoute( path: '/add', builder: (context, state) => const NoteCreationPage(), ), GoRoute( path: '/note', builder: (context, state) { final note = state.extra as Note?; return NoteCreationPage(note: note); } ), GoRoute( path: '/group', builder: (context, state) { final group = state.extra as Group?; return GroupNotePage(group: group!); } ), GoRoute( path: '/add-group', builder: (context, state) { final group = state.extra as Group?; return GroupCreationPage(group: group); } ), GoRoute( path: '/settings', builder: (context, state) { return SettingsPage(); } ) ], ), ], );
0
mirrored_repositories/flutter-notes/lib
mirrored_repositories/flutter-notes/lib/service/Snackbar.service.dart
import 'package:flutter/material.dart'; class SnackbarService { static void showSnackbar( BuildContext context, { required String message, Color backgroundColor = Colors.green, int durationInSeconds = 1, }) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text(message), backgroundColor: backgroundColor, duration: Duration(seconds: durationInSeconds), ), ); } static void showErrorSnackbar( BuildContext context, { required String message, int durationInSeconds = 1, }) { showSnackbar( context, message: message, backgroundColor: Colors.red, durationInSeconds: durationInSeconds, ); } static void showSuccessSnackbar( BuildContext context, { required String message, int durationInSeconds = 1, }) { showSnackbar( context, message: message, backgroundColor: Colors.green, durationInSeconds: durationInSeconds, ); } static void showInfoSnackbar( BuildContext context, { required String message, int durationInSeconds = 1, }) { showSnackbar( context, message: message, backgroundColor: Colors.blue, durationInSeconds: durationInSeconds, ); } }
0
mirrored_repositories/flutter-notes/lib
mirrored_repositories/flutter-notes/lib/cubit/Group.cubit.dart
import 'dart:convert'; import 'package:bloc/bloc.dart'; import 'package:blog/models/Group.model.dart'; import 'package:shared_preferences/shared_preferences.dart'; // Import your Group model class GroupCubit extends Cubit<List<Group>> { SharedPreferences? prefs; GroupCubit() : super([]) { init(); } void init() async { prefs = await SharedPreferences.getInstance(); getGroups(); } void clear() async { emit([]); } void getGroups() { final List<String> groupsString = prefs!.getStringList('groups') ?? []; final List<Group> groups = groupsString.map((groupString) { return Group.fromJson(jsonDecode(groupString)); }).toList(); emit(groups); } void add(Group group) { final currentState = List<Group>.from(state); currentState.add(group); emit(currentState); _saveToPrefs(currentState); } void update(Group updatedGroup) { final currentState = List<Group>.from(state); final index = currentState.indexWhere((_group) => _group.id == updatedGroup.id); if (index != -1) { currentState[index] = updatedGroup; emit(currentState); _saveToPrefs(currentState); } } void delete(Group group) { final currentState = List<Group>.from(state); currentState.removeWhere((_group) => _group.id == group.id); emit(currentState); _saveToPrefs(currentState); } void _saveToPrefs(List<Group> groups) { final List<String> groupsString = groups.map((group) { return jsonEncode(group.toJson()); }).toList(); prefs!.setStringList('groups', groupsString); } }
0
mirrored_repositories/flutter-notes/lib
mirrored_repositories/flutter-notes/lib/cubit/Note.cubit.dart
import 'package:bloc/bloc.dart'; import 'package:blog/models/Group.model.dart'; import 'package:blog/models/Note.model.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'dart:convert'; // For json encode & decode class NoteCubit extends Cubit<List<Note>> { SharedPreferences? prefs; NoteCubit() : super([]) { init(); } void init() async { prefs = await SharedPreferences.getInstance(); getNotes(); // Load notes from SharedPreferences } void clear() async { emit([]); } void getNotes() { final String storedData = prefs!.getString('notes') ?? '[]'; final List<dynamic> jsonData = json.decode(storedData); final List<Note> loadedNotes = jsonData.map((jsonItem) => Note.fromJson(jsonItem)).toList(); emit(loadedNotes); } void add(Note note) { final currentState = List<Note>.from(state); currentState.add(note); emit(currentState); _saveToPrefs(); } void update(Note note) { final currentState = List<Note>.from(state); final index = currentState.indexWhere((element) => element.id == note.id); if (index != -1) { currentState[index] = note; emit(currentState); _saveToPrefs(); } } void delete(Note note) { final currentState = List<Note>.from(state); currentState.removeWhere((element) => element.id == note.id); emit(currentState); _saveToPrefs(); } void removeFromGroup(Note note, Group group) { final currentState = List<Note>.from(state); final index = currentState.indexWhere((element) => element.id == note.id); if (index != -1) { currentState[index].removeGroup(group); emit(currentState); _saveToPrefs(); } } void removeGroup(Group group) { final currentState = List<Note>.from(state); for (var note in currentState) { note.removeGroup(group); } emit(currentState); _saveToPrefs(); } void _saveToPrefs() { final String jsonData = json.encode(state.map((note) => note.toJson()).toList()); prefs!.setString('notes', jsonData); } }
0
mirrored_repositories/flutter-notes/lib/ui
mirrored_repositories/flutter-notes/lib/ui/cards/BaseCard.dart
import 'package:flutter/material.dart'; class BaseCard extends StatelessWidget { const BaseCard({ super.key, required this.child, this.onTap, this.onLongPress, this.elevation = 4, this.color = Colors.white, }); final Widget child; final VoidCallback? onTap; final VoidCallback? onLongPress; final double elevation; final Color color; @override Widget build(BuildContext context) { // Create a gradient from the provided color final List<Color> gradientColors = [ color, _getVariantColor(color), ]; return SizedBox( width: double.infinity, child: Card( elevation: elevation, child: InkWell( onTap: onTap, onLongPress: onLongPress, child: Container( decoration: BoxDecoration( borderRadius: const BorderRadius.all(Radius.circular(10)), backgroundBlendMode: BlendMode.multiply, gradient: LinearGradient( colors: gradientColors, begin: Alignment.topLeft, end: Alignment.bottomRight, ), ), child: child, ), ), ), ); } Color _getVariantColor(Color baseColor) { // Adjust these values to change the gradient variation const double factor = 0.12; return Color.fromRGBO( (baseColor.red - (255 * factor)).clamp(0, 255).toInt(), (baseColor.green - (255 * factor)).clamp(0, 255).toInt(), (baseColor.blue - (255 * factor)).clamp(0, 255).toInt(), 1, ); } }
0
mirrored_repositories/flutter-notes/lib/ui
mirrored_repositories/flutter-notes/lib/ui/cards/NoteCard.dart
import 'package:blog/config/font.dart'; import 'package:blog/models/Note.model.dart'; import 'package:blog/ui/cards/BaseCard.dart'; import 'package:flutter/material.dart'; class NoteCard extends StatelessWidget { final Note note; final VoidCallback? onTap; final VoidCallback? onLongPress; final Color color; NoteCard({ super.key, required this.note, this.onTap, this.onLongPress, this.color = Colors.black, }); Widget _buildGroupBadge() { // if only one group, show the group icon if (note.groups.length == 1) { return Icon(note.groups.first.icon, color: Colors.black, size: 11); } // if more than one group, show the number of groups return Text( note.groups.length.toString(), style: getTextStyleWithColor(TextStyles.h6, Colors.black), ); } @override Widget build(BuildContext context) { return Stack( clipBehavior: Clip.none, children: [ BaseCard( onTap: onTap, color: color, onLongPress: onLongPress, child: Padding( padding: const EdgeInsets.all(16), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(note.title, style: getTextStyleWithColor(TextStyles.h4, Colors.white)), const SizedBox(height: 8), if (note.description.isNotEmpty) Text(note.description, style: getTextStyleWithColor(TextStyles.bodyText1, Colors.white70)), ], ), ), ), if (note.groups.isNotEmpty) Positioned( top: -4, right: -2, child: Container( padding: const EdgeInsets.all(6), decoration: const BoxDecoration( color: Colors.white, // Choose a suitable color for the badge shape: BoxShape.circle, ), child: _buildGroupBadge(), ), ), ], ); } }
0
mirrored_repositories/flutter-notes/lib/ui
mirrored_repositories/flutter-notes/lib/ui/cards/GroupCard.dart
import 'package:blog/config/font.dart'; import 'package:blog/models/Group.model.dart'; import 'package:blog/ui/cards/BaseCard.dart'; import 'package:flutter/material.dart'; // ignore: must_be_immutable class GroupCard extends StatelessWidget { final Group group; final VoidCallback? onTap; final VoidCallback? onLongPress; final Color color; bool isSelected; GroupCard({ super.key, required this.group, this.onTap, this.onLongPress, this.color = Colors.black, this.isSelected = false, }); @override Widget build(BuildContext context) { return BaseCard( onTap: onTap, onLongPress: onLongPress, color: color, child: Stack( children: [ Padding( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 28), child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, // Center children vertically children: [ Icon(group.icon, color: Colors.white), const SizedBox(height: 8), Text(group.name, style: getTextStyleWithColor(TextStyles.h5, Colors.white)), if (group.description.isNotEmpty) Text(group.description, style: getTextStyleWithColor(TextStyles.bodyText1, Colors.white70)), ], ), ), ), if (isSelected) _buildSelectedIcon(), ], ), ); } Widget _buildSelectedIcon() => const Positioned( top: 12, right: 12, child: Icon(Icons.check_circle, color: Colors.white), ); }
0
mirrored_repositories/flutter-notes/lib/ui
mirrored_repositories/flutter-notes/lib/ui/views/NoteCreationPage.dart
import 'dart:convert'; import 'package:blog/config/quill_configurations.dart'; import 'package:blog/cubit/Note.cubit.dart'; import 'package:blog/models/Group.model.dart'; import 'package:blog/service/Snackbar.service.dart'; import 'package:blog/ui/list/ColorPickerListView.dart'; import 'package:blog/ui/list/GroupListVIew.dart'; import 'package:flutter/material.dart'; import 'package:blog/models/Note.model.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_quill/flutter_quill.dart' show QuillController, QuillEditor, QuillToolbar; class NoteCreationPage extends StatefulWidget { final Note? note; final bool isEditing; const NoteCreationPage({ super.key, this.note, }) : isEditing = note != null; @override _NoteCreationPageState createState() => _NoteCreationPageState(); } class _NoteCreationPageState extends State<NoteCreationPage> { final TextEditingController _titleController = TextEditingController(); final TextEditingController _descriptionController = TextEditingController(); late QuillController _contentController; Color _selectedColor = Colors.black; List<Group> selectedGroups = []; Note? get note => widget.note; @override void initState() { super.initState(); String initialContent = widget.isEditing && widget.note != null ? widget.note!.content : '[{"insert":"This is a new note\\n"}]'; _contentController = QuillConfigurations.getController(jsonContent: initialContent); if (widget.isEditing && widget.note != null) { _selectedColor = widget.note!.color; _titleController.text = widget.note!.title; _descriptionController.text = widget.note!.description; selectedGroups = List<Group>.from(widget.note!.groups); } } @override void dispose() { _titleController.dispose(); _descriptionController.dispose(); _contentController.dispose(); super.dispose(); } void _saveNote(BuildContext context) async { final String title = _titleController.text; final String description = _descriptionController.text; // get the content as a json string final String content = jsonEncode(_contentController.document.toDelta().toJson()); if (title.isNotEmpty && content.isNotEmpty) { // is title too long if (title.length > MAX_TITLE_LENGTH) { SnackbarService.showErrorSnackbar(context, message: 'Title is too long'); return; } Note note = Note( title: title, description: description, content: content, color: _selectedColor, ); note.setGroup(selectedGroups); context.read<NoteCubit>().add( note ); // After saving the note, you may want to navigate back to the note list view Navigator.of(context).pop(); SnackbarService.showSuccessSnackbar(context, message: 'Note created successfully'); return; } SnackbarService.showErrorSnackbar(context, message: 'Please fill all the fields'); } void _updateNote(BuildContext context) { String title = _titleController.text; String content = _contentController.document.toDelta().toJson().toString(); if (title.isNotEmpty && content.isNotEmpty) { // is title too long if (title.length > MAX_TITLE_LENGTH) { SnackbarService.showErrorSnackbar(context, message: 'Title is too long'); return; } note!.title = _titleController.text; note!.description = _descriptionController.text; note!.content = jsonEncode(_contentController.document.toDelta().toJson()); note!.color = _selectedColor; note!.setGroup(selectedGroups); // Assuming you have a method in your NoteService to update a note context.read<NoteCubit>().update(note!); // After saving the note, you may want to navigate back to the note list view Navigator.of(context).pop(); SnackbarService.showSuccessSnackbar(context, message: 'Note updated successfully'); return; } SnackbarService.showErrorSnackbar(context, message: 'Please fill all the fields'); } void _pickColor() { showModalBottomSheet( context: context, builder: (BuildContext context) { return ColorPickerWidget( onSelectColor: (Color color) { setState(() { _selectedColor = color; }); }, ); }, ); } void _pickTags() { showModalBottomSheet( context: context, builder: (BuildContext context) { // Assuming you have a list of all groups return StatefulBuilder( builder: (BuildContext context, StateSetter setModalState) { return GroupListVIew( selectedGroupsId: selectedGroups.map((group) => group.id).toList(), onTap: (group) { if (selectedGroups.contains(group)) { setState(() { selectedGroups.remove(group); }); } else { setState(() { selectedGroups.add(group); }); } // force rebuild of the bottom sheet setModalState(() {}); }, ); }, ); }, ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.isEditing ? 'Edit note' : 'New note'), actions: [ IconButton( icon: const Icon(Icons.label), onPressed: _pickTags, // Tag picker ), // number of selected tags Text(selectedGroups.length.toString()), IconButton( icon: const Icon(Icons.color_lens), onPressed: _pickColor, // Color picker ), // circle avatar to show the selected color CircleAvatar( backgroundColor: _selectedColor, radius: 5, ), IconButton( icon: const Icon(Icons.save), color: Colors.green, onPressed: () => widget.isEditing ? _updateNote(context) : _saveNote(context), ), ], ), body: Padding( padding: const EdgeInsets.all(16.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ TextField( controller: _titleController, decoration: const InputDecoration( border: InputBorder.none, hintText: 'Title', ), style: Theme.of(context).textTheme.headline5, ), TextField( controller: _descriptionController, decoration: const InputDecoration( border: InputBorder.none, hintText: 'Description', ), style: Theme.of(context).textTheme.bodyMedium, ), const SizedBox(height: 16), QuillToolbar.simple( configurations: QuillConfigurations.getToolbarConfigurations(controller: _contentController), ), const SizedBox(height: 16), Expanded( child: QuillEditor.basic( configurations: QuillConfigurations.getEditorConfigurations(controller: _contentController), ), ), ], ), ), ); } }
0
mirrored_repositories/flutter-notes/lib/ui
mirrored_repositories/flutter-notes/lib/ui/views/GroupCreationPage.dart
import 'package:blog/cubit/Group.cubit.dart'; import 'package:blog/models/Group.model.dart'; import 'package:blog/service/Snackbar.service.dart'; import 'package:blog/ui/list/ColorPickerListView.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; // list of icons final List<IconData> icons = [ Icons.group, Icons.group_add, Icons.work, Icons.schedule, Icons.favorite, Icons.school, Icons.sports, Icons.music_note, Icons.movie, Icons.book, Icons.shopping_cart, Icons.local_pizza, Icons.local_drink, Icons.local_cafe, Icons.local_bar, Icons.local_dining, Icons.local_activity, Icons.local_airport, Icons.local_atm, Icons.local_car_wash, Icons.local_convenience_store, Icons.local_florist, Icons.local_gas_station, Icons.local_hospital, Icons.local_laundry_service, Icons.local_library, Icons.local_mall, Icons.local_movies, Icons.local_offer, Icons.local_parking, Icons.local_pharmacy, Icons.local_phone, Icons.local_play, Icons.local_post_office, Icons.local_printshop, Icons.money ]; class GroupCreationPage extends StatefulWidget { final Group? group; final bool isEditing; const GroupCreationPage({ super.key, this.group, }) : isEditing = group != null; @override _GroupCreationPageState createState() => _GroupCreationPageState(); } class _GroupCreationPageState extends State<GroupCreationPage> { final TextEditingController _nameController = TextEditingController(); final TextEditingController _descriptionController = TextEditingController(); Color _selectedColor = Colors.black; IconData _selectedIcon = Icons.group; Group? get group => widget.group; @override void initState() { super.initState(); if (widget.isEditing && widget.group != null) { _nameController.text = widget.group!.name; _descriptionController.text = widget.group!.description; _selectedColor = widget.group!.color; _selectedIcon = widget.group!.icon; } } @override void dispose() { _nameController.dispose(); _descriptionController.dispose(); super.dispose(); } void _saveGroup(BuildContext context) { final String name = _nameController.text; final String description = _descriptionController.text; if (name.isNotEmpty) { // Create a new Group object Group newGroup = Group( id : UniqueKey().toString(), name: name, description: description, color: _selectedColor, icon: _selectedIcon, ); context.read<GroupCubit>().add(newGroup); Navigator.pop(context); SnackbarService.showSuccessSnackbar(context, message: 'Group created successfully'); return; } SnackbarService.showErrorSnackbar(context, message: 'Please fill all the fields'); } void _updateGroup(BuildContext context) { final String name = _nameController.text; final String description = _descriptionController.text; if (name.isNotEmpty) { // Create a new Group object group!.name = name; group!.description = description; group!.color = _selectedColor; group!.icon = _selectedIcon; context.read<GroupCubit>().update(group!); Navigator.pop(context); SnackbarService.showSuccessSnackbar(context, message: 'Group updated successfully'); return; } SnackbarService.showErrorSnackbar(context, message: 'Please fill all the fields'); } void _pickColor() { showModalBottomSheet( context: context, builder: (BuildContext context) { return ColorPickerWidget( onSelectColor: (Color color) { setState(() { _selectedColor = color; }); }, ); }, ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.isEditing ? 'Edit Group' : 'Add Group'), actions: [ IconButton( icon: const Icon(Icons.color_lens), onPressed: _pickColor, // Color picker ), // circle avatar to show the selected color CircleAvatar( backgroundColor: _selectedColor, radius: 5, ), IconButton( icon: const Icon(Icons.save), color: Colors.green, onPressed: () { if (widget.isEditing) { _updateGroup(context); } else { _saveGroup(context); } }, ), ], ), body: Padding( padding: const EdgeInsets.all(16.0), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ TextField( controller: _nameController, decoration: const InputDecoration( border: InputBorder.none, hintText: 'Name', ), style: Theme.of(context).textTheme.headline5, ), TextField( controller: _descriptionController, decoration: const InputDecoration( border: InputBorder.none, hintText: 'Description', ), style: Theme.of(context).textTheme.bodyText1, ), const SizedBox(height: 16), // icon picker const Text('Icon'), const SizedBox(height: 8), Wrap( spacing: 8, children: [ for (int i = 0; i < icons.length; i++) InkWell( onTap: () { setState(() { _selectedIcon = icons[i]; }); }, child: Container( padding: const EdgeInsets.all(8), child: Icon(icons[i], color: _selectedIcon == icons[i] ? Colors.black : Colors.grey), ), ), ], ), ], ), ), ); } }
0
mirrored_repositories/flutter-notes/lib/ui
mirrored_repositories/flutter-notes/lib/ui/views/GroupsPage.dart
import 'package:blog/ui/list/GroupListVIew.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; class GroupsPage extends StatelessWidget { const GroupsPage({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( centerTitle: false, forceMaterialTransparency: true, leading: const Icon( Icons.tag, color: Colors.black, ), title: Text('Groups'), ), body: Container( color: Colors.white, child: GroupListVIew( onTap: (group) { GoRouter.of(context).push('/group', extra: group); }, ), ), floatingActionButton: FloatingActionButton( backgroundColor: Colors.black, foregroundColor: Colors.white, onPressed: () { // Go to the create group page GoRouter.of(context).push('/add-group'); }, child: Icon(Icons.add), ), ); } }
0
mirrored_repositories/flutter-notes/lib/ui
mirrored_repositories/flutter-notes/lib/ui/views/SettingsPage.dart
import 'package:blog/cubit/Group.cubit.dart'; import 'package:blog/cubit/Note.cubit.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:shared_preferences/shared_preferences.dart'; class SettingsPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Settings'), ), body: Center( child: ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: Colors.red, foregroundColor: Colors.white ), onPressed: () async { final prefs = await SharedPreferences.getInstance(); await prefs.clear(); // clear cubit data context.read<NoteCubit>().clear(); context.read<GroupCubit>().clear(); ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('All data cleared'), ), ); }, child: const Text('Clear All Data'), ), ), ); } }
0
mirrored_repositories/flutter-notes/lib/ui
mirrored_repositories/flutter-notes/lib/ui/views/HomePage.dart
import 'package:blog/delegates/NoteSearchDelegate.dart'; import 'package:blog/ui/list/NoteListView.dart'; import 'package:blog/ui/widget/BottomNoteModal.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; class HomePage extends StatelessWidget { const HomePage({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( forceMaterialTransparency: true, title: const Text('Notes'), leading: const Icon( Icons.notes, color: Colors.black, ), centerTitle: false, actions: [ IconButton( icon: const Icon(Icons.search), onPressed: () { // show search bar showSearch( context: context, delegate: NoteSearchDelegate(), ); }, ) ], ), body: Container( color: Colors.white, child: Stack( children: [ NoteListView( onLongPress: (note) { // Go to the edit note page showModalBottomSheet( context: context, builder: (context) { return BottomNoteModal( note: note, ); }, ); } ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: () { // Go to the create note page GoRouter.of(context).push('/add'); }, backgroundColor: Colors.black, foregroundColor: Colors.white, child: const Icon(Icons.add), ) ); } }
0
mirrored_repositories/flutter-notes/lib/ui
mirrored_repositories/flutter-notes/lib/ui/views/GroupNotePage.dart
import 'package:blog/cubit/Note.cubit.dart'; import 'package:blog/models/Group.model.dart'; import 'package:blog/ui/list/NoteListView.dart'; import 'package:blog/ui/widget/BottomNoteModal.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; class GroupNotePage extends StatelessWidget { final Group group; const GroupNotePage({ super.key, required this.group, }); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( forceMaterialTransparency: true, centerTitle: false, title: Text(group.name), // You can customize this title leading: IconButton( icon: Icon(Icons.arrow_back), onPressed: () => Navigator.of(context).pop(), ), // edit actions: [ IconButton( icon: Icon(Icons.edit), onPressed: () { // Go to the edit group page GoRouter.of(context).push('/add-group', extra: group); }, ) ], ), body: Container( color: Colors.white, child: Stack( children: [ NoteListView( groupQuery: group, onLongPress: (note) { // Go to the edit note page showModalBottomSheet( context: context, builder: (context) { return BottomNoteModal( note: note, children: [ ListTile( leading: const Icon(Icons.group, color: Colors.black), title: const Text('Remove from group', style: TextStyle(color: Colors.black)), onTap: () { // cubit remove note from group context.read<NoteCubit>().removeFromGroup(note, group); Navigator.of(context).pop(); }, ), ], ); }, ); } ), Positioned( left: 0, right: 0, bottom: 0, child: Container( height: 100, // Adjust the height as needed decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.bottomCenter, end: Alignment.topCenter, colors: [ Colors.white.withOpacity(0.3), Colors.white.withOpacity(0), // Fade out effect ], ), ), ), ), ], ), ), ); } }
0
mirrored_repositories/flutter-notes/lib/ui
mirrored_repositories/flutter-notes/lib/ui/list/NoteListView.dart
import 'package:blog/cubit/Note.cubit.dart'; import 'package:blog/models/Group.model.dart'; import 'package:blog/models/Note.model.dart'; import 'package:blog/ui/cards/NoteCard.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart'; import 'package:go_router/go_router.dart'; // ignore: must_be_immutable class NoteListView extends StatefulWidget { String query = ''; Group? groupQuery; final Function(Note)? onLongPress; NoteListView({ Key? key, this.query = '', this.groupQuery, this.onLongPress, }) : super(key: key); @override _NoteListViewState createState() => _NoteListViewState(); } class _NoteListViewState extends State<NoteListView> { @override Widget build(BuildContext context) { return BlocBuilder<NoteCubit, List<Note>>( builder: (context, notes) { notes = notes.reversed.toList(); if (widget.query.isNotEmpty) { notes = notes.where((note) { return note.title.toLowerCase().contains(widget.query.toLowerCase()) || note.description.toLowerCase().contains(widget.query.toLowerCase()) || note.content.toLowerCase().contains(widget.query.toLowerCase()); }).toList(); } // look at id of group in the list of groups if (widget.groupQuery != null) { // ignore: unnecessary_null_comparison List<String> groupIds = widget.groupQuery!.id != null ? [widget.groupQuery!.id] : []; notes = notes.where((note) { List<String> noteGroupIds = note.groups.map((group) => group.id).toList(); return noteGroupIds.any((noteGroupId) => groupIds.contains(noteGroupId)); }).toList(); } return Padding( padding: const EdgeInsets.all(8.0), child: notes.isEmpty ? const Center(child: Text('No notes available')) : MasonryGridView.count( crossAxisCount: 2, itemCount: notes.length, itemBuilder: (context, index) { final note = notes[index]; return NoteCard( note: note, onTap: () { GoRouter.of(context).push('/note', extra: note); }, onLongPress: widget.onLongPress != null ? () { widget.onLongPress!(note); } : null, color: note.color, ); }, ), ); }, ); } }
0
mirrored_repositories/flutter-notes/lib/ui
mirrored_repositories/flutter-notes/lib/ui/list/ColorPickerListView.dart
import 'package:flutter/material.dart'; class ColorPickerWidget extends StatelessWidget { final void Function(Color) onSelectColor; const ColorPickerWidget({Key? key, required this.onSelectColor}) : super(key: key); @override Widget build(BuildContext context) { return Container( padding: const EdgeInsets.all(1), height: MediaQuery.of(context).size.height / 2, child: GridView.count( crossAxisCount: 5, crossAxisSpacing: 5, mainAxisSpacing: 5, children: List.generate(Colors.primaries.length, (index) { return GestureDetector( onTap: () { onSelectColor(Colors.primaries[index]); Navigator.of(context).pop(); }, child: Padding( padding: const EdgeInsets.all(8.0), child: Container( decoration: BoxDecoration( color: Colors.primaries[index], shape: BoxShape.circle, ), ), ), ); }), ), ); } }
0
mirrored_repositories/flutter-notes/lib/ui
mirrored_repositories/flutter-notes/lib/ui/list/GroupListVIew.dart
import 'package:blog/cubit/Group.cubit.dart'; import 'package:blog/models/Group.model.dart'; import 'package:blog/ui/cards/GroupCard.dart'; import 'package:blog/ui/widget/BottomModalGroup.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart'; // Import your TagCubit // ignore: must_be_immutable class GroupListVIew extends StatefulWidget { final Function(Group)? onTap; List<String> selectedGroupsId; GroupListVIew({ Key? key, this.onTap, this.selectedGroupsId = const [], }) : super(key: key); @override _GroupListViewState createState() => _GroupListViewState(); } class _GroupListViewState extends State<GroupListVIew> { @override Widget build(BuildContext context) { return BlocBuilder<GroupCubit, List<Group>>( builder: (context, Groups) { return Padding( padding: const EdgeInsets.all(8.0), child: Groups.isEmpty ? const Center(child: Text('No Groups available')) : MasonryGridView.count( crossAxisCount: 2, itemCount: Groups.length, itemBuilder: (context, index) { final group = Groups[index]; return GroupCard( group: group, onLongPress: () { showModalBottomSheet( context: context, builder: (context) { return BottomGroupModal( group: group, ); }, ); }, onTap: () { if (widget.onTap != null) { widget.onTap!(group); } }, color: group.color, isSelected: widget.selectedGroupsId.contains(group.id), ); }, ), ); }, ); } }
0
mirrored_repositories/flutter-notes/lib/ui
mirrored_repositories/flutter-notes/lib/ui/widget/BottomNoteModal.dart
import 'package:blog/cubit/Note.cubit.dart'; import 'package:blog/models/Note.model.dart'; import 'package:blog/ui/widget/BottomModal.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; class BottomNoteModal extends StatelessWidget { final Note note; final List<Widget> children; const BottomNoteModal({ super.key, required this.note, this.children = const [], }); @override Widget build(BuildContext context) { return BottomModal( createdAt: note.createdAt!, onDelete: () { Navigator.of(context).pop(); // cubit delete note context.read<NoteCubit>().delete(note); }, onEdit: () { Navigator.of(context).pop(); // Go to the edit note page GoRouter.of(context).push('/note', extra: note); }, children: children, ); } }
0
mirrored_repositories/flutter-notes/lib/ui
mirrored_repositories/flutter-notes/lib/ui/widget/BottomModal.dart
import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; class BottomModal extends StatelessWidget { final DateTime createdAt; final VoidCallback onDelete; final VoidCallback onEdit; final List<Widget> children; const BottomModal({ super.key, required this.createdAt, required this.onDelete, required this.onEdit, this.children = const [], }); @override Widget build(BuildContext context) { final dateFormat = DateFormat('yyyy-MM-dd – kk:mm'); return Container( padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 10), color : Colors.white, child: Column( mainAxisSize: MainAxisSize.min, children: [ ListTile( leading: const Icon(Icons.edit, color: Colors.black), title: const Text('Edit', style: TextStyle(color: Colors.black)), onTap: onEdit, ), const Divider(), ...children, ListTile( leading: const Icon(Icons.delete, color: Colors.red), title: const Text('Delete', style: TextStyle(color: Colors.red)), onTap: onDelete, ), const Divider(), Padding( padding: const EdgeInsets.all(8.0), child: Text( 'Created At: ${dateFormat.format(createdAt)}', style: const TextStyle(fontStyle: FontStyle.italic), ), ), ], ), ); } }
0
mirrored_repositories/flutter-notes/lib/ui
mirrored_repositories/flutter-notes/lib/ui/widget/BottomNavigationBar.dart
import 'package:blog/config/router.dart'; import 'package:flutter/material.dart'; const int STANDARD_SCREEN_WIDTH = 360; class AppBottomNavigationBar extends StatelessWidget { const AppBottomNavigationBar({super.key}); @override Widget build(BuildContext context) { final navBarItemsLength = navBarItems.length; return Stack( alignment: Alignment.bottomRight, clipBehavior: Clip.none, children: [ Container( decoration: const BoxDecoration( border: Border( top: BorderSide( color: Colors.grey, width: 0.5, ), ), ), height: 60, child: Row( mainAxisAlignment: MainAxisAlignment.start, children: [ for (int i = 0; i < navBarItemsLength; i++) AppBottomNavigationBarItem( label: navBarItems[i]["label"], icon: navBarItems[i]["icon"], route: navBarItems[i]["route"], onTap: navBarItems[i]["onTap"] ), ], ), ), ], ); } } class AppBottomNavigationBarItem extends StatelessWidget { final String label; final IconData icon; final String route; final void Function(BuildContext)? onTap; const AppBottomNavigationBarItem({ super.key, required this.label, required this.icon, required this.route, this.onTap, }); @override Widget build(BuildContext context) { final size = MediaQuery.of(context).size; return SizedBox( width: 70 * size.width / STANDARD_SCREEN_WIDTH - 10, height: size.height, child: InkWell( onTap: () => onTap != null ? onTap!(context) : Navigator.pushNamed(context, route), child: Center( child: Column( mainAxisSize: MainAxisSize.min, children: [ Icon(icon), ], ), ), ), ); } }
0
mirrored_repositories/flutter-notes/lib/ui
mirrored_repositories/flutter-notes/lib/ui/widget/BottomModalGroup.dart
import 'package:blog/cubit/Group.cubit.dart'; import 'package:blog/cubit/Note.cubit.dart'; import 'package:blog/models/Group.model.dart'; import 'package:blog/ui/widget/BottomModal.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:go_router/go_router.dart'; class BottomGroupModal extends StatelessWidget { final Group group; final List<Widget> children; const BottomGroupModal({ super.key, required this.group, this.children = const [], }); @override Widget build(BuildContext context) { return BottomModal( createdAt: group.createdAt!, onDelete: () { Navigator.of(context).pop(); // cubit delete note context.read<GroupCubit>().delete(group); context.read<NoteCubit>().removeGroup(group); }, onEdit: () { Navigator.of(context).pop(); // Go to the edit note page GoRouter.of(context).push('/add-group', extra: group); }, children: children, ); } }
0
mirrored_repositories/flutter-notes/lib/ui
mirrored_repositories/flutter-notes/lib/ui/widget/ScaffoldWithNavbar.dart
import 'package:blog/ui/widget/BottomNavigationBar.dart'; import 'package:flutter/material.dart'; class ScaffoldWithNavBar extends StatelessWidget { const ScaffoldWithNavBar({ super.key, required this.child, }); final Widget child; @override Widget build(BuildContext context) { return Scaffold( body: child, bottomNavigationBar: const SafeArea( child: AppBottomNavigationBar(), ), ); } }
0
mirrored_repositories/flutter-notes
mirrored_repositories/flutter-notes/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility in the flutter_test package. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:blog/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/Quiz-App-Flutter
mirrored_repositories/Quiz-App-Flutter/lib/questions_summary.dart
import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; class QuestionsSummary extends StatelessWidget { const QuestionsSummary(this.summaryData, {super.key}); final List<Map<String, Object>> summaryData; @override Widget build(BuildContext context) { return SizedBox( height: 400, child: SingleChildScrollView( child: Column( children: summaryData.map((data) { return Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Column( children: [ Container( margin: const EdgeInsets.only(right: 10), decoration: BoxDecoration( shape: BoxShape.circle, border: Border.all( color: changeColor(data), width: 15, ), color: changeColor(data), ), child: Text( ((data['qusetion_index'] as int) + 1).toString(), style: GoogleFonts.lato( color: Colors.white, ), ), ), ], ), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( textAlign: TextAlign.left, data['qusetion'] as String, style: GoogleFonts.lato( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 16), ), const SizedBox(height: 10), Text( textAlign: TextAlign.left, data['user_answer'] as String, style: GoogleFonts.lato( color: Colors.white, ), ), Text( textAlign: TextAlign.left, data['correct_answer'] as String, style: GoogleFonts.lato( color: Colors.green, ), ), const SizedBox(height: 20), ], ), ), ], ); }).toList(), ), ), ); } } Color changeColor(Map<String, Object> data) { final bool isCorrect = (data['user_answer'] as String == data['correct_answer']); if (isCorrect) { return Colors.green; } else { return Colors.red; } }
0
mirrored_repositories/Quiz-App-Flutter
mirrored_repositories/Quiz-App-Flutter/lib/quiz.dart
import 'package:flutter/material.dart'; import 'package:quiz_app/data/questions.dart'; import 'package:quiz_app/questions_screen.dart'; import 'package:quiz_app/start_screen.dart'; import 'package:quiz_app/results_screen.dart'; class Quiz extends StatefulWidget { const Quiz({super.key}); @override State<Quiz> createState() { return _QuizState(); } } class _QuizState extends State<Quiz> { // Widget? activeScreen; List<String> _selectedAnswers = []; var activeScreen = 'start-screen'; // @override // void initState() { // activeScreen = StartScreeen(switchScreen); // super.initState(); // } void _switchScreen() { setState(() { activeScreen = 'questions-screen'; }); } void _restartQuiz() { setState(() { _selectedAnswers = []; activeScreen = 'start-screen'; }); } void chooseAnswer(String answer) { _selectedAnswers.add(answer); if (_selectedAnswers.length == questions.length) { setState(() { activeScreen = 'results-screen'; }); } } @override Widget build(BuildContext context) { Widget screenWidget = StartScreeen(_switchScreen); if (activeScreen == 'questions-screen') { screenWidget = QuestionsScreen( onSelectedAnswer: chooseAnswer, ); } if (activeScreen == 'results-screen') { screenWidget = ResultScreen( chosenAnswers: _selectedAnswers, onRestartQuiz: _restartQuiz, ); } return MaterialApp( home: Scaffold( body: Container( decoration: const BoxDecoration( gradient: LinearGradient( begin: Alignment.topLeft, end: Alignment.bottomRight, colors: [ Color.fromARGB(255, 49, 8, 88), Color.fromARGB(255, 83, 7, 99), ], ), ), child: screenWidget, ), ), ); } }
0
mirrored_repositories/Quiz-App-Flutter
mirrored_repositories/Quiz-App-Flutter/lib/results_screen.dart
import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:quiz_app/answer_button.dart'; import 'package:quiz_app/data/questions.dart'; import 'package:quiz_app/questions_summary.dart'; class ResultScreen extends StatelessWidget { const ResultScreen({ super.key, required this.chosenAnswers, required this.onRestartQuiz, }); final List<String> chosenAnswers; final void Function() onRestartQuiz; List<Map<String, Object>> get summaryData { final List<Map<String, Object>> sammary = []; for (var i = 0; i < chosenAnswers.length; i++) { sammary.add({ 'qusetion_index': i, 'qusetion': questions[i].text, 'correct_answer': questions[i].answers[0], 'user_answer': chosenAnswers[i], }); } return sammary; } @override Widget build(BuildContext context) { final numTotalQuestions = questions.length; final numCorrectQuestions = summaryData .where( (data) => data['user_answer'] == data['correct_answer'], ) .length; return SizedBox( width: double.infinity, child: Container( margin: const EdgeInsets.all(40), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( "You Answerd $numCorrectQuestions of $numTotalQuestions Questions Correctly!", style: GoogleFonts.lato( color: Colors.white, fontWeight: FontWeight.bold, ), ), const SizedBox(height: 30), QuestionsSummary(summaryData), const SizedBox(height: 15), AnswerButton( answerText: "Restart Quiz!", onTap: onRestartQuiz, ) // TextButton( // onPressed: () {}, // child: const Text("Restart Quiz!"), // ), ], ), ), ); } }
0
mirrored_repositories/Quiz-App-Flutter
mirrored_repositories/Quiz-App-Flutter/lib/questions_screen.dart
import 'package:flutter/material.dart'; import 'package:quiz_app/answer_button.dart'; import 'package:quiz_app/data/questions.dart'; import 'package:google_fonts/google_fonts.dart'; class QuestionsScreen extends StatefulWidget { const QuestionsScreen({super.key, required this.onSelectedAnswer}); final void Function(String answer) onSelectedAnswer; @override State<QuestionsScreen> createState() { return _QuestionsScreenState(); } } class _QuestionsScreenState extends State<QuestionsScreen> { var currentQuestionIndex = 0; void answerQuestion(String answer) { widget.onSelectedAnswer(answer); setState(() { currentQuestionIndex++; }); } @override Widget build(BuildContext context) { final currentQuestion = questions[currentQuestionIndex]; return SizedBox( width: double.infinity, child: Container( margin: const EdgeInsets.all(40), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Text(currentQuestion.text, textAlign: TextAlign.center, style: GoogleFonts.lato( color: Colors.white, fontSize: 24, fontWeight: FontWeight.bold, )), const SizedBox(height: 30), ...currentQuestion.shuffledAnswers.map((answer) { return AnswerButton( answerText: answer, onTap: () { answerQuestion(answer); }, ); }), ], ), ), ); } }
0
mirrored_repositories/Quiz-App-Flutter
mirrored_repositories/Quiz-App-Flutter/lib/start_screen.dart
import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; class StartScreeen extends StatelessWidget { const StartScreeen(this.startQuiz, {super.key}); final void Function() startQuiz; @override Widget build(BuildContext context) { return Center( child: Column( mainAxisSize: MainAxisSize.min, children: [ Image.asset( 'assets/images/quiz-logo.png', color: const Color.fromARGB(150, 255, 255, 255), width: 300, ), const SizedBox(height: 80), Text( 'Learn Flutter the fun way!', style: GoogleFonts.lato( color: Colors.white, fontSize: 24, ), ), const SizedBox( height: 30, ), OutlinedButton.icon( onPressed: startQuiz, style: OutlinedButton.styleFrom( foregroundColor: Colors.white, ), icon: const Icon(Icons.arrow_right_alt), label: const Text( 'Start Quiz', ), ), ], ), ); } }
0
mirrored_repositories/Quiz-App-Flutter
mirrored_repositories/Quiz-App-Flutter/lib/answer_button.dart
import 'package:flutter/material.dart'; class AnswerButton extends StatelessWidget { const AnswerButton({ super.key, required this.answerText, required this.onTap, }); final String answerText; final void Function() onTap; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(6), child: ElevatedButton( style: ElevatedButton.styleFrom( fixedSize: const Size(100, 50), backgroundColor: const Color.fromARGB(255, 50, 10, 160), foregroundColor: Colors.white, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(40), ), ), onPressed: onTap, child: Text( answerText, textAlign: TextAlign.center, ), ), ); } }
0
mirrored_repositories/Quiz-App-Flutter
mirrored_repositories/Quiz-App-Flutter/lib/main.dart
import 'package:flutter/material.dart'; import 'package:quiz_app/quiz.dart'; void main() { runApp(const Quiz()); }
0
mirrored_repositories/Quiz-App-Flutter/lib
mirrored_repositories/Quiz-App-Flutter/lib/models/quiz_question.dart
class QuizQuestion { const QuizQuestion(this.text, this.answers); final String text; final List<String> answers; List<String> get shuffledAnswers { final shuffledList = List.of(answers); shuffledList.shuffle(); return shuffledList; } }
0
mirrored_repositories/Quiz-App-Flutter/lib
mirrored_repositories/Quiz-App-Flutter/lib/data/questions.dart
import 'package:quiz_app/models/quiz_question.dart'; const questions = [ QuizQuestion( 'What are the main building blocks of Flutter UIs?', [ 'Widgets', 'Components', 'Blocks', 'Functions', ], ), QuizQuestion('How are Flutter UIs built?', [ 'By combining widgets in code', 'By combining widgets in a visual editor', 'By defining widgets in config files', 'By using XCode for iOS and Android Studio for Android', ]), QuizQuestion( 'What\'s the purpose of a StatefulWidget?', [ 'Update UI as data changes', 'Update data as UI changes', 'Ignore data changes', 'Render UI that does not depend on data', ], ), QuizQuestion( 'Which widget should you try to use more often: StatelessWidget or StatefulWidget?', [ 'StatelessWidget', 'StatefulWidget', 'Both are equally good', 'None of the above', ], ), QuizQuestion( 'What happens if you change data in a StatelessWidget?', [ 'The UI is not updated', 'The UI is updated', 'The closest StatefulWidget is updated', 'Any nested StatefulWidgets are updated', ], ), QuizQuestion( 'How should you update data inside of StatefulWidgets?', [ 'By calling setState()', 'By calling updateData()', 'By calling updateUI()', 'By calling updateState()', ], ), ];
0
mirrored_repositories/Barber-Booking-App
mirrored_repositories/Barber-Booking-App/lib/main.dart
import 'dart:async'; import 'package:basp/Provider/map_data_provider.dart'; import 'package:basp/screens/AppointmentScreen.dart'; import 'package:basp/screens/bookingScreen.dart'; import 'package:basp/screens/mapsScreen.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:shared_preferences/shared_preferences.dart'; void main() { WidgetsFlutterBinding.ensureInitialized(); runApp(MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key key}) : super(key: key); @override Widget build(BuildContext context) { return MultiProvider( providers: [ ChangeNotifierProvider<MapDataProvider>( create: (_) => MapDataProvider()), ], child: MaterialApp( title: "Barber App", // --------------------- Add Theme Data ---------------------- // // Add theme data here theme: ThemeData( // Define the default brightness and colors. brightness: Brightness.dark, primaryColor: Colors.blueGrey[900], accentColor: Colors.cyan[600], // Define the default font family. // Define the default TextTheme. Use this to specify the default // text styling for headlines, titles, bodies of text, and more. textTheme: TextTheme( headline1: TextStyle( fontSize: 25.0, fontWeight: FontWeight.bold, color: Colors.white), headline2: TextStyle(fontSize: 20.0, fontWeight: FontWeight.normal), headline6: TextStyle(fontSize: 20.0, fontStyle: FontStyle.normal), bodyText2: TextStyle( fontSize: 14.0, ), ), ), // ------------------- Manage Routes ------------------- // //Add new routes here routes: { '/bookingScreen': (context) => BookingScreen(), '/mappage': (context) => Mappage(), '/appointmentScreen': (context) => AppointmentScreen(), }, home: SplashScreen(), debugShowCheckedModeBanner: false, ), ); } } class SplashScreen extends StatefulWidget { @override _SplashScreen createState() => _SplashScreen(); } class _SplashScreen extends State<SplashScreen> { // -------------- for start page Widget defaultPage = Container(); //------------ check if the user is using app for first time or not void checkSharedPrefs() async { var sharedPrefs = await SharedPreferences.getInstance(); if (sharedPrefs.containsKey("firstTime")) { defaultPage = Container(); } } //-------- initialize with a Timer that will push to new screen after few seconds @override void initState() { super.initState(); checkSharedPrefs(); Timer(Duration(seconds: 4), () { Navigator.of(context).pushReplacement( MaterialPageRoute( builder: (BuildContext context) => AppointmentScreen(), ), ); }); } // ---------------- Splash Screen Widget @override Widget build(BuildContext context) { return Scaffold( // -------------------- temp background color can be changed.... in THEME DATA backgroundColor: Colors.blueGrey[900], body: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Image.asset( "assets/splash_screen.gif", height: (60 / 100) * MediaQuery.of(context).size.height, width: MediaQuery.of(context).size.width, ), CircularProgressIndicator( strokeWidth: 4, backgroundColor: Colors.amberAccent[400], ) ], ), ); } }
0
mirrored_repositories/Barber-Booking-App/lib
mirrored_repositories/Barber-Booking-App/lib/Provider/map_data_provider.dart
import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import '../core/Data_models/map_data_model.dart'; ///MapDataProvider is the provider of MapDataModel List that can NotifyChanges to the whole list class MapDataProvider with ChangeNotifier { List<MapDataModel> mapDataList; ///Constructor, will load the list by making the necessary request MapDataProvider() { loadData(); } ///Method that loads the List with the MapDataModel Objects requested from API loadData() async { final _mapjson = await rootBundle.loadString('lib/Temporary_data/map_data.json'); final _parsed = json.decode(_mapjson).cast<Map<String, dynamic>>(); mapDataList = _parsed .map<MapDataModel>((json) => MapDataModel.fromJson(json)) .toList(); notifyListeners(); return true; } @override String toString() { return mapDataList.toString(); } //Method will return a List consisting of a Map with 2 fields //name- name of marker on map, location - cooordinates of the marker get coordinates { List<dynamic> _coordinates; for (var i = 0; i < mapDataList.length; i++) { _coordinates.add( {"name": mapDataList[i].name, "location": mapDataList[i].location}); } return [..._coordinates]; } //Method will return the complete List of MapDataModel objects get completeData { return [...mapDataList]; } //Method will return single MapDataModel object from the complete List //where the name field of the MapDataModel object matches with the name provided MapDataModel singleComplete(String name) { return mapDataList.singleWhere((element) => element.name == name); } }
0
mirrored_repositories/Barber-Booking-App/lib/Provider
mirrored_repositories/Barber-Booking-App/lib/Provider/barber_data_from_map_provider.dart/barber_data_from_map_provider.dart
import 'dart:convert'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import '../../core/Data_models/barber_data_from_map/barber_data_from_map_model.dart'; import '../../core/Data_models/barber_data_from_map/comment_model.dart'; import '../../core/Data_models/barber_data_from_map/service_mode.dart'; ///BarberDataFromMapProvider is the provider of BarberDataFromMapModel List that can NotifyChanges to the whole list ///this list has elements based on MapDataProvider List, only the Elements that were marked on the Map will be Fetched from here class BarberDataFromMapProvider with ChangeNotifier { List<BarberDataFromMapModel> _barberdatalist; ///Constructor, It will load the necessary Data into the BarberDataFromMapList BarberDataFromMapProvider() { loadData(); } //FutureMethod, it is responsible for loading data from the json file into the Model object and then into the list void loadData() async { final _mapjson = await rootBundle .loadString('lib/Temporary_data/barber_data_from_map.json'); final parsed = json.decode(_mapjson).cast<Map<String, dynamic>>(); _barberdatalist = parsed .map<BarberDataFromMapModel>( (json) => BarberDataFromMapModel.fromJson(json)) .toList(); } @override String toString() { return _barberdatalist.toString(); } ///get Method, to get the complete BarberDataList get barberDataList { return [..._barberdatalist]; } /// Method, it will return the List of Services that the particular Store offers, /// it yields a single ServiceModel object based on the storeName provided to it as a parameter List<ServiceModel> barberDataServices({@required String storeName}) { return [ ..._barberdatalist .singleWhere((element) => element.mapData.name == storeName) .services ]; } /// Method, it will return the List of Comments that the consumers wrote for a particular store, /// it yields a single CommentModel object based on the storeName provided to it as a parameter List<CommentModel> barberDataComments({@required String storeName}) { return [ ..._barberdatalist .singleWhere((element) => element.mapData.name == storeName) .comments ]; } /// Method, it will return the List of Photos that the particular Store uploaded to it's gallery, /// it yields a single Gallery object based on the storeName provided to it as a parameter List<dynamic> barberDataGallery({@required String storeName}) { return [ ..._barberdatalist .singleWhere((element) => element.mapData.name == storeName) .gallery ]; } }
0
mirrored_repositories/Barber-Booking-App/lib/core
mirrored_repositories/Barber-Booking-App/lib/core/Data_models/map_data_model.dart
import 'dart:convert'; import 'package:meta/meta.dart'; ///Data Model for providing Initial data for Map viewing ///fields are Location - for co-ordinates, name - name of the mark or shop, ///rating - for rating provided, photo - image of the shop or profile, ///workinghors- the open timing of the store class MapDataModel { MapDataModel({ @required this.location, @required this.name, @required this.rating, @required this.photo, @required this.workingHours, }); // Fields of the MapDataModel Class String location; String name; double rating; dynamic photo; WorkingHours workingHours; /// Factory of converting raw JSON string to the MapDataModel elements factory MapDataModel.fromRawJson(String str) => MapDataModel.fromJson(json.decode(str)); /// Method of converting Model into Raw JSON String String toRawJson() => json.encode(toJson()); /// Factory for converting individual JSON object into MapDataModel object factory MapDataModel.fromJson(Map<String, dynamic> json) => MapDataModel( location: json["Location"] == null ? null : json["Location"], name: json["Name"] == null ? null : json["Name"], rating: json["Rating"] == null ? null : json["Rating"].toDouble(), photo: json["Photo"], workingHours: json["WorkingHours"] == null ? null : WorkingHours.fromJson(json["WorkingHours"]), ); /// Converting individual MapDataModel object to a JSON object Map<String, dynamic> toJson() => { "Location": location == null ? null : location, "Name": name == null ? null : name, "Rating": rating == null ? null : rating, "Photo": photo, "WorkingHours": workingHours == null ? null : workingHours.toJson(), }; @override String toString() { return "${this.name}, ${this.location},${this.rating}"; } } ///WorkingHours Class represents open hours of each day in a week individually class WorkingHours { WorkingHours({ @required this.monday, @required this.tuesday, @required this.wednesday, @required this.thursday, @required this.friday, @required this.saturday, @required this.sunday, }); //Fields of WorkingHours class containing weekdays String monday; String tuesday; String wednesday; String thursday; String friday; String saturday; String sunday; ///Factory to convert Raw JSON object into WorkingHours object factory WorkingHours.fromRawJson(String str) => WorkingHours.fromJson(json.decode(str)); /// Converting WorkingHours object in Raw JSON String String toRawJson() => json.encode(toJson()); /// Factory for converting individual JSON object into WorkingHours object factory WorkingHours.fromJson(Map<String, dynamic> json) => WorkingHours( monday: json["Monday"] == null ? null : json["Monday"], tuesday: json["Tuesday"] == null ? null : json["Tuesday"], wednesday: json["Wednesday"] == null ? null : json["Wednesday"], thursday: json["Thursday"] == null ? null : json["Thursday"], friday: json["Friday"] == null ? null : json["Friday"], saturday: json["Saturday"] == null ? null : json["Saturday"], sunday: json["Sunday"] == null ? null : json["Sunday"], ); /// Converting individual WorkingHours object to a JSON object Map<String, dynamic> toJson() => { "Monday": monday == null ? null : monday, "Tuesday": tuesday == null ? null : tuesday, "Wednesday": wednesday == null ? null : wednesday, "Thursday": thursday == null ? null : thursday, "Friday": friday == null ? null : friday, "Saturday": saturday == null ? null : saturday, "Sunday": sunday == null ? null : sunday, }; }
0
mirrored_repositories/Barber-Booking-App/lib/core/Data_models
mirrored_repositories/Barber-Booking-App/lib/core/Data_models/barber_data_from_map/barber_data_from_map_model.dart
import 'dart:convert'; import 'package:meta/meta.dart'; import '../map_data_model.dart'; import 'comment_model.dart'; import 'service_mode.dart'; ///BarberDataFromMapModel class that contains Detailed information about the stores included in MapDataModel ///Containers 4 fields MapData - MapDataModel object, services - List of Service object Instances, gallery - List of photos, ///comments - List of Comment object Instances class BarberDataFromMapModel { BarberDataFromMapModel({ @required this.mapData, @required this.services, @required this.gallery, @required this.comments, }); MapDataModel mapData; List<ServiceModel> services; List<dynamic> gallery; List<CommentModel> comments; /// Factory of converting raw JSON string to the BarberDataFromMapModel elements factory BarberDataFromMapModel.fromRawJson(String str) => BarberDataFromMapModel.fromJson(json.decode(str)); /// Method of converting Model into Raw JSON String String toRawJson() => json.encode(toJson()); /// Factory for converting individual JSON object into BarberDataFromMapModel object factory BarberDataFromMapModel.fromJson(Map<String, dynamic> json) => BarberDataFromMapModel( mapData: json["MapData"] == null ? null : MapDataModel.fromJson(json["MapData"]), services: json["Services"] == null ? null : List<ServiceModel>.from( json["Services"].map((x) => ServiceModel.fromJson(x))), gallery: json["Gallery"] == null ? null : List<dynamic>.from(json["Gallery"].map((x) => x)), comments: json["Comments"] == null ? null : List<CommentModel>.from( json["Comments"].map((x) => CommentModel.fromJson(x))), ); /// Converting individual BarberDataFromMapModel object to a JSON object Map<String, dynamic> toJson() => { "MapData": mapData == null ? null : mapData.toJson(), "Services": services == null ? null : List<dynamic>.from(services.map((x) => x.toJson())), "Gallery": gallery == null ? null : List<dynamic>.from(gallery.map((x) => x)), "Comments": comments == null ? null : List<dynamic>.from(comments.map((x) => x.toJson())), }; }
0
mirrored_repositories/Barber-Booking-App/lib/core/Data_models
mirrored_repositories/Barber-Booking-App/lib/core/Data_models/barber_data_from_map/comment_model.dart
import 'dart:convert'; import 'package:flutter/widgets.dart'; ///CommentModel class Contains Individual Comment object Model(Comment is a review or statement provided by Consumers to that store) ///Contains 4 fields, commentorName - name of the consumer who wrote the Comment, photo- profile photo of the consumer who wrote the comment ///, time - Time at which the comment was published by consumer, comment - the actual Comment that the consumer wrote class CommentModel { CommentModel({ @required this.commentorName, @required this.photo, @required this.time, @required this.comment, }); String commentorName; dynamic photo; String time; String comment; /// Factory of converting raw JSON string to the CommentModel elements factory CommentModel.fromRawJson(String str) => CommentModel.fromJson(json.decode(str)); /// Method of converting Model into Raw JSON String String toRawJson() => json.encode(toJson()); /// Factory for converting individual JSON object into CommentModel object factory CommentModel.fromJson(Map<String, dynamic> json) => CommentModel( commentorName: json["CommentorName"] == null ? null : json["CommentorName"], photo: json["Photo"], time: json["Time"] == null ? null : json["Time"], comment: json["Comment"] == null ? null : json["Comment"], ); /// Converting individual CommentModel object to a JSON object Map<String, dynamic> toJson() => { "CommentorName": commentorName == null ? null : commentorName, "Photo": photo, "Time": time == null ? null : time, "Comment": comment == null ? null : comment, }; }
0
mirrored_repositories/Barber-Booking-App/lib/core/Data_models
mirrored_repositories/Barber-Booking-App/lib/core/Data_models/barber_data_from_map/service_mode.dart
import 'dart:convert'; import 'package:flutter/widgets.dart'; ///ServiceModel class contains the Individual Service object(Service is something provided by the store) ///Contains 2 fields, serviceName - name of the Service provided, price - Price of the service class ServiceModel { ServiceModel({ @required this.serviceName, @required this.price, }); String serviceName; int price; /// Factory of converting raw JSON string to the ServiceModel elements factory ServiceModel.fromRawJson(String str) => ServiceModel.fromJson(json.decode(str)); /// Method of converting Model into Raw JSON String String toRawJson() => json.encode(toJson()); /// Factory for converting individual JSON object into ServiceModel object factory ServiceModel.fromJson(Map<String, dynamic> json) => ServiceModel( serviceName: json["ServiceName"] == null ? null : json["ServiceName"], price: json["Price"] == null ? null : json["Price"], ); /// Converting individual ServiceModel object to a JSON object Map<String, dynamic> toJson() => { "ServiceName": serviceName == null ? null : serviceName, "Price": price == null ? null : price, }; }
0
mirrored_repositories/Barber-Booking-App/lib
mirrored_repositories/Barber-Booking-App/lib/Views/serviceBody.dart
import 'package:flutter/material.dart'; class ServiceBody extends StatefulWidget { @override _ServiceBodyState createState() => _ServiceBodyState(); } class _ServiceBodyState extends State<ServiceBody> { int _amount = 0; int _quantity = 0; bool _booking = false; //List<Map<String, int>> selected = []; static Map<String, int> haircuts = { 'Basic Haircut': 100, 'Fade Haircut': 140, 'Beard Trimming': 80, 'French Beard': 120, 'Afro Haircut': 300 }; List<bool> _check = [for (var i = 0; i < haircuts.length; i += 1) false]; Widget haircutprice(String name, int price, int index) { return Column( children: <Widget>[ SizedBox( height: 20, ), Padding( padding: const EdgeInsets.only(left: 25, right: 25), child: Row( children: <Widget>[ InkWell( onTap: () { setState(() { _check[index] = !_check[index]; _check[index] ? ++_quantity : --_quantity; for (bool i in _check) { if (i == true) { _booking = true; break; } else { _booking = false; continue; } } }); }, child: Container( height: 26, width: 26, decoration: BoxDecoration( shape: BoxShape.rectangle, color: _check[index] ? Colors.blue : Colors.white38, borderRadius: BorderRadius.all(Radius.circular(5.0)), ), child: !_check[index] ? Icon( Icons.add, size: 26.0, color: Colors.black, ) : Icon( Icons.clear, size: 26.0, color: Colors.white, ), ), ), SizedBox( width: 20, ), Expanded( child: Text( name, style: Theme.of(context).textTheme.headline6, ), ), Text( '\u20B9 $price', style: Theme.of(context).textTheme.headline6, ), ], ), ), ], ); } @override void initState() { super.initState(); } @override Widget build(BuildContext context) { return Container( child: ListView( children: <Widget>[ for (int i = 0; i < haircuts.length; i++) haircutprice(haircuts.keys.toList()[i].toString(), haircuts[haircuts.keys.toList()[i].toString()], i), SizedBox( height: 20, ), Container( height: 65, color: Colors.white38, child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ SizedBox( width: 10, ), Center( child: Text('$_quantity item selected', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 22, color: _booking ? Colors.white : Colors.white54, )), ), InkWell( onTap: () { if (_booking == true) { for (int i = 0; i < _check.length; i++) { if (_check[i] == true) { _amount = _amount + haircuts[haircuts.keys.toList()[i].toString()]; } } } print(_amount); //Navigator.push(context, 'appointmentScreen') }, child: Card( color: _booking ? Colors.blue : Colors.grey[850], shape: RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(10.0))), elevation: 3, child: Padding( padding: const EdgeInsets.fromLTRB(38, 8, 38, 8), child: Column( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ Text( 'Book', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 15, color: _booking ? Colors.white : Colors.white54), ), Text( 'Now', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 15, color: _booking ? Colors.white : Colors.white54), ), ], ), ), ), ), ], ), ) ], ), ); } }
0
mirrored_repositories/Barber-Booking-App/lib
mirrored_repositories/Barber-Booking-App/lib/Views/gallerybody.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; class CategoryModel { List<Widget> models; List<String> url = [ 'https://images.pexels.com/photos/792381/pexels-photo-792381.jpeg?auto=compress&cs=tinysrgb&fit=crop&h=1200&w=800', 'https://images.pexels.com/photos/227675/pexels-photo-227675.jpeg?auto=compress&cs=tinysrgb&fit=crop&h=1200&w=800', 'https://images.pexels.com/photos/1193743/pexels-photo-1193743.jpeg?auto=compress&cs=tinysrgb&fit=crop&h=1200&w=800', 'https://images.pexels.com/photos/1149831/pexels-photo-1149831.jpeg?auto=compress&cs=tinysrgb&fit=crop&h=1200&w=800', 'https://images.pexels.com/photos/1624487/pexels-photo-1624487.jpeg?auto=compress&cs=tinysrgb&fit=crop&h=1200&w=800', 'https://images.pexels.com/photos/556667/pexels-photo-556667.jpeg?auto=compress&cs=tinysrgb&fit=crop&h=1200&w=800', 'https://images.pexels.com/photos/1413412/pexels-photo-1413412.jpeg?auto=compress&cs=tinysrgb&fit=crop&h=1200&w=800', 'https://images.pexels.com/photos/459225/pexels-photo-459225.jpeg?auto=compress&cs=tinysrgb&fit=crop&h=1200&w=800', 'https://images.pexels.com/photos/853168/pexels-photo-853168.jpeg?auto=compress&cs=tinysrgb&fit=crop&h=1200&w=800', 'https://images.pexels.com/photos/220201/pexels-photo-220201.jpeg?auto=compress&cs=tinysrgb&fit=crop&h=1200&w=800', 'https://images.pexels.com/photos/1939485/pexels-photo-1939485.jpeg?auto=compress&cs=tinysrgb&fit=crop&h=1200&w=800', 'https://images.pexels.com/photos/1008155/pexels-photo-1008155.jpeg?auto=compress&cs=tinysrgb&fit=crop&h=1200&w=800', 'https://images.pexels.com/photos/853199/pexels-photo-853199.jpeg?auto=compress&cs=tinysrgb&fit=crop&h=1200&w=800', 'https://images.pexels.com/photos/278887/pexels-photo-278887.jpeg?auto=compress&cs=tinysrgb&fit=crop&h=1200&w=800' ]; Widget model(int i) { //return Stack( //children: <Widget>[ return ClipRRect( borderRadius: BorderRadius.circular(8), child: CachedNetworkImage( imageUrl: url[i], height: 85, width: 85, fit: BoxFit.cover, ), ); // Container( // height: 80, // width: 80, // decoration: BoxDecoration( // color: Colors.black26, // borderRadius: BorderRadius.circular(8), // ), // ), // Container( // height: 80, // width: 80, // alignment: Alignment.center, // child: Text( // names[i], // style: TextStyle( // color: Colors.white, // fontSize: 20, // fontWeight: FontWeight.w500, // ), // ), // ), //], //); } } class GalleryBody extends StatefulWidget { @override _GalleryBodyState createState() => _GalleryBodyState(); } class _GalleryBodyState extends State<GalleryBody> { @override Widget build(BuildContext context) { return Container( color: Colors.black12, child: GridView.count( // Create a grid with 2 columns. If you change the scrollDirection to // horizontal, this produces 2 rows. childAspectRatio:1.1, crossAxisCount: 3, padding: EdgeInsets.fromLTRB(15, 20, 15, 20), // Generate 100 widgets that display their index in the List. children: List.generate(14, (index) { return Center(child: CategoryModel().model(index)); }), ), ); } }
0
mirrored_repositories/Barber-Booking-App/lib
mirrored_repositories/Barber-Booking-App/lib/screens/AppointmentScreen.dart
import 'package:flutter/material.dart'; class AppointmentScreen extends StatefulWidget { @override _AppointmentScreenState createState() => _AppointmentScreenState(); } class _AppointmentScreenState extends State<AppointmentScreen> { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, appBar: AppBar( elevation: 0, backgroundColor: Colors.orangeAccent[100], leading: IconButton( icon: Icon( Icons.arrow_back, ), onPressed: () => Navigator.of(context).pop(), ), title: Text("Appointment"), centerTitle: true, actions: <Widget>[ IconButton( icon: Icon( Icons.notifications, ), onPressed: () {}, ), IconButton( icon: Icon( Icons.sort, ), onPressed: () => {}, ), ], ), body: Stack( children: <Widget>[ SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Card( elevation: 10, color: Colors.orangeAccent[100], margin: EdgeInsets.all(0), child: Column( children: <Widget>[ SizedBox( height: 15, ), Row( mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[ Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Row( children: <Widget>[ Text( "John Doe ", style: TextStyle( fontSize: 20, fontWeight: FontWeight.bold), ), Icon( Icons.done, size: 15, ) ], ), SizedBox( height: 5, ), Text( "Thane, India", style: TextStyle( fontSize: 14, ), ), SizedBox( height: 5, ), Row( children: <Widget>[ for (int i = 0; i < 5; i++) Icon( Icons.star, size: 17, ) ], ), SizedBox( height: 7, ), ], ), SizedBox( width: 50, ), IconButton( icon: Icon(Icons.share), onPressed: () {}, ), IconButton( icon: Icon(Icons.favorite), onPressed: () {}, ) ], ), ], ), ), Padding( padding: const EdgeInsets.fromLTRB(20, 20, 20, 0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ SizedBox( height: 40, ), Text( "Available Timings", style: TextStyle( color: Colors.black54, fontSize: 20, fontWeight: FontWeight.bold), ), SizedBox( height: 5, ), Container( width: 55, color: Colors.black54, height: 3, ), SizedBox( height: 20, ), Container( height: 110, child: ListView.builder( scrollDirection: Axis.horizontal, itemCount: 5, itemBuilder: (BuildContext ctxt, int index) { return Stack( children: <Widget>[ ClipRRect( borderRadius: BorderRadius.circular(8), child: Container( height: 110, width: 110, ), ), Container( height: 110, width: 90, decoration: BoxDecoration( color: Colors.redAccent, borderRadius: BorderRadius.circular(25), ), ), Container( height: 110, width: 90, alignment: Alignment.center, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( '09:00', style: TextStyle( color: Colors.white, fontSize: 20, fontWeight: FontWeight.w500, ), ), Text( 'AM', style: TextStyle( color: Colors.white, fontSize: 20, fontWeight: FontWeight.w500, ), ), ], ), ), ], ); }, ), ), SizedBox( height: 20, ), Text( "Services", style: TextStyle( color: Colors.black54, fontSize: 20, fontWeight: FontWeight.bold), ), SizedBox( height: 5, ), Container( width: 55, color: Colors.black54, height: 3, ), SizedBox( height: 10, ), Padding( padding: const EdgeInsets.fromLTRB(8, 4, 8, 2), child: Column( children: <Widget>[ for (int i = 0; i < 2; i++) Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Text( "Afro Haircut", style: TextStyle( color: Colors.grey, fontSize: 18, fontWeight: FontWeight.w600), ), Text( "\u20B9 300", style: TextStyle( color: Colors.grey, fontSize: 18, fontWeight: FontWeight.w600), ), ], ), SizedBox( height: 10, ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Text( "Total", style: TextStyle( color: Colors.black87, fontSize: 18, fontWeight: FontWeight.w600), ), Text( "\u20B9 600", style: TextStyle( color: Colors.black87, fontSize: 18, fontWeight: FontWeight.w600), ), ], ), ], ), ), ], ), ), Divider( height: 15, color: Colors.grey, ), Padding( padding: EdgeInsets.fromLTRB(20, 0, 20, 0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( "Whom to book for?", style: TextStyle( color: Colors.grey, fontSize: 12, fontWeight: FontWeight.w600), ), SizedBox( height: 5, ), Row( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ CircleAvatar( radius: 17, backgroundImage: NetworkImage( 'https://images.unsplash.com/photo-1506794778202-cad84cf45f1d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1868&q=80'), ), SizedBox( width: 8, ), Text( "User 1", style: TextStyle( color: Colors.grey[900], fontSize: 12, fontWeight: FontWeight.w600), ), ], ) ], ), Icon( Icons.check_circle, color: Colors.redAccent, size: 40, ), ], ), ), Divider( height: 15, color: Colors.grey, ), ], ), ), Positioned( left: 25, top: 20, child: CircleAvatar( backgroundColor: Colors.white, radius: 55.0, child: CircleAvatar( radius: 48, backgroundImage: NetworkImage( 'https://images.unsplash.com/photo-1506794778202-cad84cf45f1d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1868&q=80'), ), ), ), ], ), ); } }
0
mirrored_repositories/Barber-Booking-App/lib
mirrored_repositories/Barber-Booking-App/lib/screens/mapsScreen.dart
import 'package:basp/Provider/map_data_provider.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'package:provider/provider.dart'; import 'package:sliding_up_panel/sliding_up_panel.dart'; class Mappage extends StatefulWidget { @override _MappageState createState() => _MappageState(); } class _MappageState extends State<Mappage> { bool first = true; MapDataProvider obj; bool loading = true; void getData() async { obj = Provider.of<MapDataProvider>(context); print(obj); print(obj.mapDataList); bool l = await obj.loadData(); if (l) { setState(() { loading = false; }); } } @override Widget build(BuildContext context) { if (first) { first = false; getData(); } return SafeArea( child: Scaffold( body: loading ? Center( child: CupertinoActivityIndicator(), ) : MapBody(obj), ), ); } } // ignore: must_be_immutable class MapBody extends StatefulWidget { MapDataProvider obj; MapBody(this.obj); @override _MapBodyState createState() => _MapBodyState(obj); } class _MapBodyState extends State<MapBody> { MapDataProvider obj; _MapBodyState(this.obj); PanelController _pc = new PanelController(); MapType _mapType = MapType.normal; Map<MarkerId, Marker> markers = <MarkerId, Marker>{}; CameraPosition _kInitialPosition = const CameraPosition( target: LatLng(12.922270, 77.584290), zoom: 16.0, ); BorderRadiusGeometry radius = BorderRadius.only( topLeft: Radius.circular(24.0), topRight: Radius.circular(24.0), ); @override Widget build(BuildContext context) { void _onMapCreated(GoogleMapController controller) { for (int i = 0; i < obj.mapDataList.length; i++) { print(obj.mapDataList[i]); final MarkerId markerId = MarkerId((markers.length + 1).toString()); List cd = obj.mapDataList[i].location.split(","); LatLng markerPos = LatLng(double.parse(cd[0]), double.parse(cd[1])); final Marker marker = Marker( icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueRed), markerId: markerId, infoWindow: InfoWindow( title: "${obj.mapDataList[i].name}", snippet: "Rating: ${obj.mapDataList[i].rating}", ), position: markerPos); markers[markerId] = marker; } setState(() {}); } return SlidingUpPanel( controller: _pc, color: Colors.blueGrey[900], backdropEnabled: true, backdropColor: Colors.transparent, backdropOpacity: 0, maxHeight: MediaQuery.of(context).devicePixelRatio * 150, borderRadius: radius, collapsed: InkWell( onTap: () { _pc.open(); }, child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.only( topRight: Radius.circular(40.0), topLeft: Radius.circular(40.0)), color: Colors.blueGrey[900]), child: Column( children: <Widget>[ Container( decoration: BoxDecoration( borderRadius: BorderRadius.only( topRight: Radius.circular(40.0), topLeft: Radius.circular(40.0)), color: Colors.purple), height: 10, ), Container( color: Colors.blueGrey[900], child: Row( children: <Widget>[ Padding( padding: const EdgeInsets.all(20), child: Icon( Icons.keyboard_arrow_up, color: Colors.white70, size: 30, ), ), Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Text( "Explore Nearby", style: TextStyle( fontSize: 20, color: Colors.white, ), ), Text( "Barbers", style: TextStyle( color: Colors.white70, ), ), ], ) ], ), ), Container( width: 140, color: Colors.white38, height: 4, ), ], ), ), ), panel: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Container( decoration: BoxDecoration( borderRadius: BorderRadius.only( topRight: Radius.circular(40.0), topLeft: Radius.circular(40.0)), color: Colors.purple), height: 20, ), Padding( padding: const EdgeInsets.all(20.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( "Nearby Barbers", style: TextStyle( fontSize: 22, color: Colors.white, ), ), SizedBox( height: 10, ), Container( width: 120, color: Colors.white38, height: 4, ), SizedBox( height: 10, ), Container( width: 80, color: Colors.white38, height: 4, ), ], ), ), Expanded( child: Padding( padding: const EdgeInsets.all(20.0), child: ListView.builder( itemCount: obj.mapDataList.length, itemBuilder: (BuildContext ctxt, int index) { return Card( margin: EdgeInsets.only(bottom: 20), shadowColor: Colors.white, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20.0)), color: Colors.black, elevation: 1, child: Padding( padding: const EdgeInsets.fromLTRB(20, 10, 20, 10), child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ CircleAvatar( radius: 25, backgroundImage: NetworkImage( 'https://images.unsplash.com/photo-1506794778202-cad84cf45f1d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1868&q=80'), ), SizedBox( width: 10, ), Expanded( child: Column( mainAxisAlignment: MainAxisAlignment.spaceAround, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( 'John Doe', style: TextStyle( fontSize: 23.0, fontWeight: FontWeight.bold, color: Colors.white), ), Text( 'Thane', style: TextStyle( fontSize: 20.0, fontWeight: FontWeight.normal, color: Colors.white54), ), ], ), ), Column( mainAxisAlignment: MainAxisAlignment.spaceAround, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( '3.6', style: TextStyle( fontSize: 23.0, fontWeight: FontWeight.bold, color: Colors.white), ), Text( 'mtrs.', style: TextStyle( fontSize: 20.0, fontWeight: FontWeight.normal, fontStyle: FontStyle.italic, color: Colors.white54), ), ], ), ], ), ), ); }), ), ), ], ), body: Stack( children: <Widget>[ GoogleMap( mapToolbarEnabled: false, zoomGesturesEnabled: true, zoomControlsEnabled: false, mapType: _mapType, markers: Set<Marker>.of(markers.values), initialCameraPosition: _kInitialPosition, onMapCreated: _onMapCreated, ), Positioned( left: 300, top: 400, right: 15, bottom: 30, child: Column( //mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ FloatingActionButton( backgroundColor: Colors.white, elevation: 15, child: Icon( Icons.tune, color: Colors.black, ), onPressed: () {}, ), SizedBox( height: 10, ), FloatingActionButton( backgroundColor: Colors.white, elevation: 15, child: Icon( Icons.my_location, color: Colors.black, ), onPressed: () {}, ), ], ), ), Padding( padding: const EdgeInsets.fromLTRB(10, 15, 10, 0), child: Card( elevation: 15.0, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10.0)), color: Colors.white, child: Container( height: 70, width: double.infinity, child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ IconButton( icon: Icon( Icons.menu, size: 30, color: Colors.black, ), onPressed: () {}, ), Container( decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(10.0)), color: Colors.grey[200]), margin: EdgeInsets.fromLTRB(0, 15, 0, 15), padding: EdgeInsets.all(10), height: 50, width: MediaQuery.of(context).devicePixelRatio * 100, child: Text( "Search Here ...", style: TextStyle(color: Colors.grey, fontSize: 18), ), ), IconButton( icon: Icon( Icons.clear, color: Colors.black, size: 30, ), onPressed: () {}, ), ], ), ), ), ) ], ), ); } }
0
mirrored_repositories/Barber-Booking-App/lib
mirrored_repositories/Barber-Booking-App/lib/screens/bookingScreen.dart
import 'package:basp/Views/gallerybody.dart'; import 'package:flutter/material.dart'; import 'package:basp/Views/serviceBody.dart'; class BookingScreen extends StatefulWidget { @override _BookingScreenState createState() => _BookingScreenState(); } class _BookingScreenState extends State<BookingScreen> with SingleTickerProviderStateMixin { TabController _tabController; @override void initState() { super.initState(); _tabController = TabController(vsync: this, initialIndex: 0, length: 3); } @override Widget build(BuildContext context) { // BorderRadiusGeometry radius = BorderRadius.only( // topLeft: Radius.circular(24.0), // topRight: Radius.circular(24.0), // ); return Container( child: Stack( fit: StackFit.expand, children: <Widget>[ Image.network( 'https://thumbs.dreamstime.com/b/blue-sky-clouds-abstract-art-background-watercolor-digital-artwork-136551201.jpg', fit: BoxFit.fitHeight, ), Scaffold( endDrawer: Drawer(), appBar: AppBar( title: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ SizedBox(width: 50,), Text( "Booking", style: Theme.of(context).textTheme.headline6, ), IconButton( icon: Icon(Icons.notifications), onPressed: () {}, ), ], ), leading: IconButton( icon: Icon(Icons.arrow_back), onPressed: () {}, ), ), backgroundColor: Colors.transparent, body: ListView( children: <Widget>[ Card( margin: EdgeInsets.fromLTRB(40, 20, 40, 30), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(50.0)), color: Theme.of(context).primaryColor, elevation: 10, child: Padding( padding: const EdgeInsets.fromLTRB(0, 50, 0, 10), child: Column( children: <Widget>[ CircleAvatar( backgroundColor: Colors.white, radius: 48.0, child: CircleAvatar( radius: 40, backgroundImage: NetworkImage( 'https://images.unsplash.com/photo-1506794778202-cad84cf45f1d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1868&q=80'), ), ), SizedBox( height: 7, ), Text( 'John Doe', style: Theme.of(context).textTheme.headline1, ), SizedBox( height: 7, ), Text( 'Thane', style: Theme.of(context).textTheme.headline2, ), ], ), ), ), Container( height: 5000, decoration: BoxDecoration( borderRadius: BorderRadius.only( topRight: Radius.circular(40.0), topLeft: Radius.circular(40.0)), color: Theme.of(context).primaryColor), child: Scaffold( backgroundColor: Colors.transparent, appBar: AppBar( shape: RoundedRectangleBorder( borderRadius: BorderRadius.only( topRight: Radius.circular(40.0), topLeft: Radius.circular(40.0))), title: TabBar( indicatorSize: TabBarIndicatorSize.label, indicatorWeight: 3, labelColor: Colors.white, unselectedLabelColor: Colors.white38, controller: _tabController, indicatorColor: Colors.white, tabs: <Widget>[ Tab( child: Text( "Services", style: TextStyle(fontSize: 20), )), Tab( child: Text( "Gallery", style: TextStyle(fontSize: 20), )), Tab( child: Text( "Reviews", style: TextStyle(fontSize: 20), )) ], ), ), body: TabBarView( controller: _tabController, children: <Widget>[ ServiceBody(), GalleryBody(), Container(child: Text("hello")), ], ), ), ), ], ), ), ], ), ); } }
0
mirrored_repositories/currency_converter
mirrored_repositories/currency_converter/lib/main.dart
import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'dart:async'; import 'dart:convert'; const request = API_URL; void main() async { runApp(MaterialApp( home: Home(), theme: ThemeData( hintColor: Colors.amber, primaryColor: Colors.white, inputDecorationTheme: InputDecorationTheme( enabledBorder: OutlineInputBorder(borderSide: BorderSide(color: Colors.amber)), focusedBorder: OutlineInputBorder(borderSide: BorderSide(color: Colors.white)), hintStyle: TextStyle(color: Colors.amber), )))); } Future<Map> getData() async { http.Response response = await http.get(request); return json.decode(response.body); } class Home extends StatefulWidget { @override _HomeState createState() => _HomeState(); } class _HomeState extends State<Home> { final realController = TextEditingController(); final dolarController = TextEditingController(); final bitcoinController = TextEditingController(); double dolar; double bitcoin; void _realChanged(String text) { if (text.isEmpty) { _clearAll(); return; } double real = double.parse(text); dolarController.text = (real / dolar).toStringAsFixed(2); bitcoinController.text = (real / bitcoin).toStringAsFixed(10); } void _dolarChanged(String text) { if (text.isEmpty) { _clearAll(); return; } double dolar = double.parse(text); realController.text = (dolar * this.dolar).toStringAsFixed(2); bitcoinController.text = (dolar * this.dolar / bitcoin).toStringAsFixed(10); } void _bitcoinChanged(String text) { if (text.isEmpty) { _clearAll(); return; } double bitcoin = double.parse(text); realController.text = (bitcoin * this.bitcoin).toStringAsFixed(2); dolarController.text = (bitcoin * this.bitcoin / dolar).toStringAsFixed(2); } void _clearAll() { realController.text = ""; dolarController.text = ""; bitcoinController.text = ""; } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.black, appBar: AppBar( title: Text("\$ Conversor \$"), backgroundColor: Colors.amber, centerTitle: true, ), body: FutureBuilder<Map>( future: getData(), builder: (context, snapshot) { switch (snapshot.connectionState) { case ConnectionState.none: case ConnectionState.waiting: return Center( child: Text( "Carregando Dados...", style: TextStyle(color: Colors.amber, fontSize: 25.0), textAlign: TextAlign.center, )); default: if (snapshot.hasError) { return Center( child: Text( "Erro ao Carregar Dados!", style: TextStyle(color: Colors.amber, fontSize: 25.0), textAlign: TextAlign.center, )); } else { dolar = snapshot.data["results"]["currencies"]["USD"]["buy"]; bitcoin = snapshot.data["results"]["currencies"]["BTC"]["buy"]; return SingleChildScrollView( padding: EdgeInsets.all(10.0), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ Text( "Real = 1 | Dólar = $dolar | Bitcoin = $bitcoin", textAlign: TextAlign.center, style: TextStyle(color: Colors.amber, fontSize: 15.0), ), Divider(), Divider(), Icon(Icons.monetization_on, size: 150.0, color: Colors.amber), Divider(), Divider(), buildTextField( "Reais", "R\$ ", realController, _realChanged), Divider(), buildTextField( "Dólar", "US\$ ", dolarController, _dolarChanged), Divider(), buildTextField("Bitcoin", "₿\$ ", bitcoinController, _bitcoinChanged), ], ), ); } } })); } } Widget buildTextField( String label, String prefix, TextEditingController c, Function f) { return TextField( controller: c, decoration: InputDecoration( labelText: label, labelStyle: TextStyle(color: Colors.amber), border: OutlineInputBorder(), prefixText: prefix), style: TextStyle(color: Colors.amber, fontSize: 25.0), onChanged: f, keyboardType: TextInputType.number, ); }
0
mirrored_repositories/TODO-APP-FLUTTER
mirrored_repositories/TODO-APP-FLUTTER/lib/main.dart
import 'package:flutter/material.dart'; import 'package:flutter_todolist/screens/notes_screen.dart'; import 'package:google_fonts/google_fonts.dart'; void main() => runApp(const StartPage()); class StartPage extends StatefulWidget { const StartPage({Key? key}) : super(key: key); @override State<StartPage> createState() => _StartPageState(); } class _StartPageState extends State<StartPage> { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData(textTheme: GoogleFonts.caudexTextTheme()), home: const MyApp()); } }
0
mirrored_repositories/TODO-APP-FLUTTER/lib
mirrored_repositories/TODO-APP-FLUTTER/lib/screens/notes_screen.dart
import 'dart:math'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_slidable/flutter_slidable.dart'; import 'package:intl/intl.dart'; class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key); @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { final TextEditingController _newTodoController = TextEditingController(); List<String> todos = []; List<Color> colors = []; @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, appBar: AppBar( leading: const Icon( Icons.menu, color: Colors.black, ), elevation: 0, backgroundColor: Colors.transparent, centerTitle: true, title: const Text( "My Todo's", style: TextStyle(color: Colors.black), ), actions: [ IconButton( onPressed: () { debugPrint("hkhj"); }, icon: const Icon( Icons.add, color: Colors.black, ), ) ], ), body: Padding( padding: const EdgeInsets.all(12.0), child: Column( children: [ const SizedBox( height: 12, ), const Text("Todo's Available!", style: TextStyle(color: Colors.grey, fontSize: 15)), const SizedBox( height: 12, ), Expanded( child: todos.isNotEmpty ? ListView.separated( itemCount: todos.length, physics: const BouncingScrollPhysics(), itemBuilder: ( context, index, ) { return Slidable( key: Key(todos[index]), startActionPane: const ActionPane( motion: ScrollMotion(), children: [ SlidableAction( onPressed: null, label: 'Edit', icon: CupertinoIcons.pencil_outline, backgroundColor: Colors.white60, ) ]), endActionPane: ActionPane( motion: const ScrollMotion(), children: [ SlidableAction( key: Key(todos[index]), onPressed: (_) => { setState(() { todos.remove(todos[index]); colors.remove(colors[index]); }) }, backgroundColor: Colors.white, icon: Icons.delete, label: 'Delete', ) ]), child: Container( height: 90, padding: const EdgeInsets.all(12), decoration: BoxDecoration( color: colors[index], borderRadius: BorderRadius.circular(10)), child: Row( children: [ Expanded( child: ListTile( leading: const Icon( CupertinoIcons.check_mark_circled, color: Colors.white, ), title: Text(todos[index]), trailing: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisSize: MainAxisSize.min, children: [ // const Icon(CupertinoIcons.bell_circle,color: Colors.white,), Text(DateFormat('yyyy-MM-dd') .format(DateTime.now())) ], ), ), ) ], ), ), ); }, separatorBuilder: (BuildContext context, int index) { return const SizedBox( height: 16, ); }, ) : LayoutBuilder(builder: (ctx, constrains) { return ListView( children: [ Column( children: <Widget>[ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const Text( "Good Day,Mr Kweku Anansi.", style: TextStyle( fontSize: 20, fontWeight: FontWeight.w100, ), ), Text(DateFormat('KK:mm a') .format(DateTime.now())) ], ), const SizedBox( height: 50, ), const Text( 'Empty Todos...', style: TextStyle( fontSize: 35, fontWeight: FontWeight.bold), ), Container( height: 300, decoration: const BoxDecoration( image: DecorationImage( image: AssetImage( "assets/new.png", ), fit: BoxFit.fill), ), ) ], ), ], ); })) ], ), ), floatingActionButton: FloatingActionButton( onPressed: () { showModalBottomSheet( isScrollControlled: true, backgroundColor: Colors.transparent, context: context, builder: (context) => SingleChildScrollView( child: Container( padding: EdgeInsets.only( bottom: MediaQuery.of(context).viewInsets.bottom), decoration: const BoxDecoration( color: Colors.white, borderRadius: BorderRadius.only( topLeft: Radius.circular(20), topRight: Radius.circular(20)), ), child: Container( color: Colors.white, child: Container( // height: 900, padding: const EdgeInsets.all(20), decoration: const BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(10))), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ const Text( "Add New Todo ", textAlign: TextAlign.center, style: TextStyle(fontSize: 15, color: Colors.black), ), const SizedBox( height: 10, ), TextField( controller: _newTodoController, decoration: const InputDecoration( labelText: "About Today's Todo"), textCapitalization: TextCapitalization.sentences, maxLines: 3, ), const SizedBox( height: 5, ), TextButton( onPressed: () { Navigator.pop(context); if (_newTodoController.text == '') { return; } setState(() { todos.add(_newTodoController.text); colors.add(Colors .primaries[Random() .nextInt(Colors.primaries.length)] .shade300); }); _newTodoController.clear(); }, child: Column( children: const [ SizedBox( height: 50, width: double.infinity, child: Card( color: Colors.blue, child: Center( child: Text( "Save", style: TextStyle(color: Colors.black), ), ), ), ) ], ), ), ], ), ), )), ), ); }, tooltip: 'Add new Todo', child: const Icon(Icons.add), ), ); } }
0
mirrored_repositories/TODO-APP-FLUTTER
mirrored_repositories/TODO-APP-FLUTTER/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_todolist/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const StartPage()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/Bus-Tracking-system/src/bus_tracking_system
mirrored_repositories/Bus-Tracking-system/src/bus_tracking_system/lib/main.dart
import 'package:bus_tracking_system/screen/splash.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'package:bus_tracking_system/screen/ui.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); // initialize app await Firebase.initializeApp(); // initialize Firebase runApp(MyApp()); // run app } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData(), home: splash(), ); } } class LoginPage extends StatefulWidget { @override _LoginPageState createState() => _LoginPageState(); } class _LoginPageState extends State<LoginPage> { bool isStudent = true; void toggleLoginOption() { setState(() { isStudent = !isStudent; }); } @override Widget build(BuildContext context) { return UI(); } }
0
mirrored_repositories/Bus-Tracking-system/src/bus_tracking_system/lib
mirrored_repositories/Bus-Tracking-system/src/bus_tracking_system/lib/Constants/constants.dart
import 'package:flutter/material.dart'; const String orsapikey = "5b3ce3597851110001cf62486114402a56174aa9b0294c6ade29f118"; //Enter the required API const Color primaryColor = Color.fromARGB(15, 97, 150, 255);
0
mirrored_repositories/Bus-Tracking-system/src/bus_tracking_system/lib
mirrored_repositories/Bus-Tracking-system/src/bus_tracking_system/lib/screen/map_page.dart
import 'package:bus_tracking_system/screen/maps.dart'; import 'package:flutter/material.dart'; // import 'package:bus_tracking_system/screen/select_routes.dart'; class MapPage extends StatelessWidget { final String location; MapPage({required this.location}); @override Widget build(BuildContext context) { Size size = MediaQuery.of(context).size; return Scaffold( appBar: AppBar( title: Text('Map - $location'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text('Map of $location'), SizedBox(height: 20), ElevatedButton( child: Text('Select Route'), style: ElevatedButton.styleFrom( primary: Colors.pink, padding: EdgeInsets.symmetric(horizontal: 50, vertical: 15), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(30), ), ), onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (BuildContext context) { return BusTracking(); }, ), ); }, ), ], ), ), ); } }
0
mirrored_repositories/Bus-Tracking-system/src/bus_tracking_system/lib
mirrored_repositories/Bus-Tracking-system/src/bus_tracking_system/lib/screen/profile.dart
import 'package:flutter/material.dart'; class ProfilePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Profile'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ CircleAvatar( backgroundColor: Colors.black, radius: 95, child: Container( alignment: Alignment.center, child: Icon( Icons.person, size: 120, color: Colors.white, ), ), ), SizedBox(height: 20), Text( 'Email: xyz@gmail.com', style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, ), ), Spacer(), TextButton( onPressed: () { // Show dialog for changing password showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: Text('Change Password'), content: Column( mainAxisSize: MainAxisSize.min, children: [ TextField( decoration: InputDecoration( labelText: 'New Password', ), ), SizedBox(height: 10), TextField( decoration: InputDecoration( labelText: 'Re-enter Password', ), ), ], ), actions: [ TextButton( onPressed: () { // Handle password change Navigator.of(context).pop(); }, child: Text('Save'), ), TextButton( onPressed: () { // Close the dialog Navigator.of(context).pop(); }, child: Text('Cancel'), ), ], ); }, ); }, child: Text('Change Password'), ), ], ), ), ); } }
0
mirrored_repositories/Bus-Tracking-system/src/bus_tracking_system/lib
mirrored_repositories/Bus-Tracking-system/src/bus_tracking_system/lib/screen/destination_info.dart
import 'package:latlong2/latlong.dart'; class DestinationInfo { final LatLng destinationLocation; DestinationInfo(this.destinationLocation); }
0
mirrored_repositories/Bus-Tracking-system/src/bus_tracking_system/lib
mirrored_repositories/Bus-Tracking-system/src/bus_tracking_system/lib/screen/locations_page.dart
import 'package:flutter/material.dart'; import 'package:bus_tracking_system/screen/maps.dart'; import 'package:bus_tracking_system/screen/profile.dart'; class LocationsPage extends StatefulWidget { @override _LocationsPageState createState() => _LocationsPageState(); } class _LocationsPageState extends State<LocationsPage> { List<String> _locations = [ 'Prem Nagar UPES', 'Clock Tower', 'Dehradun ISBT', 'Bidholi', 'Kandholi', ]; void _showLogoutConfirmationDialog() { showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: Text('Logout'), content: Text('Do you want to log out?'), actions: [ TextButton( onPressed: () { // Perform logout operation Navigator.of(context).pop(); // Add your logout logic here }, child: Text('Yes'), ), TextButton( onPressed: () { Navigator.of(context).pop(); }, child: Text('No'), ), ], ); }, ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.white, title: Text( 'Select Route', style: TextStyle(color: Colors.black), ), leading: Builder( builder: (BuildContext context) { return IconButton( icon: Icon(Icons.menu), color: Colors.black, onPressed: () { Scaffold.of(context).openDrawer(); }, ); }, ), ), drawer: Drawer( child: ListView( padding: EdgeInsets.zero, children: <Widget>[ DrawerHeader( decoration: BoxDecoration( color: Colors.blue, ), child: Text( 'Menu', style: TextStyle( color: Colors.white, fontSize: 24, ), ), ), ListTile( title: Text('Select Route'), onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => LocationsPage(), ), ); }, ), ListTile( title: Text('Profile'), onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => ProfilePage(), ), ); }, ), ListTile( title: Text('Logout'), onTap: _showLogoutConfirmationDialog, ), ], ), ), body: ListView.builder( itemCount: _locations.length, itemBuilder: (BuildContext context, int index) { return GestureDetector( onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => BusTracking(), ), ); }, child: Card( margin: EdgeInsets.symmetric(horizontal: 10, vertical: 5), child: Padding( padding: EdgeInsets.all(20), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( _locations[index], style: TextStyle( fontWeight: FontWeight.bold, fontSize: 16, color: Colors.black, ), ), SizedBox(height: 5), Text( 'Driver: John Doe', style: TextStyle( fontWeight: FontWeight.normal, fontSize: 12, ), ), SizedBox(height: 5), Text( 'Phone: +91-7894521642', style: TextStyle( fontSize: 12, fontWeight: FontWeight.normal, ), ), SizedBox(height: 10), ElevatedButton( onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (context) => BusTracking(), ), ); }, child: Text( 'Track in Map', style: TextStyle(color: Colors.white), ), style: ElevatedButton.styleFrom( primary: Colors.blue, padding: EdgeInsets.symmetric( horizontal: 50, vertical: 15, ), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(30), ), ), ), ], ), ), ), ); }, ), ); } }
0
mirrored_repositories/Bus-Tracking-system/src/bus_tracking_system/lib
mirrored_repositories/Bus-Tracking-system/src/bus_tracking_system/lib/screen/DriverLoginPage.dart
import 'dart:convert'; import 'package:app_settings/app_settings.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_database/firebase_database.dart'; import 'package:flutter/material.dart'; import 'package:flutter_map/flutter_map.dart'; import 'package:http/http.dart' as http; import 'package:latlong2/latlong.dart'; import 'package:geolocator/geolocator.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import '../Constants/constants.dart'; import 'package:bus_tracking_system/screen/profile.dart'; import 'package:bus_tracking_system/screen/locations_page.dart'; class DriverLoginPage extends StatefulWidget { @override _DriverLoginPageState createState() => _DriverLoginPageState(); } class _DriverLoginPageState extends State<DriverLoginPage> { final isLoading = false; LatLng DestinationLocation = LatLng(0, 0); // Initialize with default values // late LatLng destinationLocation = LatLng( // 30.3253, //For driver location // 78.0413); List<LatLng> polylinePoints = []; // Initialize with an empty list final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); late DatabaseReference dbRef; @override void initState() { super.initState(); requestPermission(); dbRef = FirebaseDatabase.instance.ref().child('DestinationLocation'); } Future<void> requestPermission() async { LocationPermission permission = await Geolocator.requestPermission(); if (permission == LocationPermission.denied || permission == LocationPermission.deniedForever) { showDialog( context: context, builder: (BuildContext context) => AlertDialog( title: Text('Location Permission Required'), content: Text('This app needs to access your location to work properly.'), actions: <Widget>[ TextButton( child: Text('Cancel'), onPressed: () => Navigator.of(context).pop(), ), TextButton( child: Text('Settings'), onPressed: () => AppSettings.openAppSettings(), ), ], ), ); } else { getCurrentLocation(); } } Future<void> getCurrentLocation() async { Position position = await Geolocator.getCurrentPosition( desiredAccuracy: LocationAccuracy.high); setState(() { DestinationLocation = LatLng(position.latitude, position.longitude); }); } @override Widget build(BuildContext context) { return Scaffold( body: Center( child: ElevatedButton( onPressed: () { isLoading ? null : requestPermission().then((value) { Map<String, double> values = { 'latitude': DestinationLocation.latitude, 'longitude': DestinationLocation.longitude, }; dbRef.push().set(values); }); }, child: Text("Request Location Permission"), ), ), ); } }
0
mirrored_repositories/Bus-Tracking-system/src/bus_tracking_system/lib
mirrored_repositories/Bus-Tracking-system/src/bus_tracking_system/lib/screen/splash.dart
import 'package:flutter/material.dart'; import '../main.dart'; class splash extends StatefulWidget { const splash({super.key}); @override State<splash> createState() => _splashState(); } class _splashState extends State<splash> { @override void initState() { super.initState(); _navigatetohome(); } _navigatetohome() async { await Future.delayed(Duration(milliseconds: 2000), () {}); Navigator.pushReplacement( context, MaterialPageRoute(builder: (context) => LoginPage())); } @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Container( width: double.infinity, height: double.infinity, decoration: BoxDecoration(color: Color(0xfff6f8f4)), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Center( child:Image.asset( 'assets/images/bus.png', ), ), Text( " UPES BUS TARCKER", style: TextStyle( height: 5, color: Colors.blueAccent, fontWeight: FontWeight.bold, fontSize: 30.0, ), ), CircularProgressIndicator(), ], )), ), ); } }
0
mirrored_repositories/Bus-Tracking-system/src/bus_tracking_system/lib
mirrored_repositories/Bus-Tracking-system/src/bus_tracking_system/lib/screen/maps.dart
import 'dart:async'; import 'dart:convert'; import 'package:app_settings/app_settings.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_database/firebase_database.dart'; import 'package:firebase_database/ui/firebase_animated_list.dart'; import 'package:flutter/material.dart'; import 'package:flutter_map/flutter_map.dart'; import 'package:http/http.dart' as http; import 'package:latlong2/latlong.dart'; import 'package:geolocator/geolocator.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import '../Constants/constants.dart'; import 'package:bus_tracking_system/screen/profile.dart'; import 'package:bus_tracking_system/screen/locations_page.dart'; import 'package:bus_tracking_system/screen/DriverLoginPage.dart'; class BusTracking extends StatefulWidget { @override _BusTrackingState createState() => _BusTrackingState(); } // class Destination extends StatefulWidget { // final double destinationLatitude; // final double destinationLongitude; // Destination({ // required this.destinationLatitude, // required this.destinationLongitude, // }); // // const Destination({Key? key}) : super(key: key); // @override // State<Destination> createState() => _RealTimeDestLocation(); // } // Retirieving Destination Location // class _RealTimeDestLocation extends State<Destination> { // final ref = FirebaseDatabase.instance.ref('DestinationLocation'); // double latitude = 0; // double longitude = 0; // @override // void initState() { // super.initState(); // ref.onValue.listen((event) { // final DataSnapshot snapshot = event.snapshot; // Access the DataSnapshot // final destinationLocationData = snapshot.value as Map<dynamic, dynamic>?; // print( // "Destination Location Data: $destinationLocationData"); // Debugging line // if (destinationLocationData != null) { // setState(() { // latitude = destinationLocationData['Latitude'] as double; // longitude = destinationLocationData['Longitude'] as double; // }); // if (latitude != null && longitude != null) { // print("Latitude: $latitude, Longitude: $longitude"); // // Use latitude and longitude values here // } // } // }); // } // @override // Widget build(BuildContext context) { // return Scaffold( // body: Column( // children: [Text(latitude.toString()) // , Text(longitude.toString())], // )); // Empty widget, no UI elements // } // } class _BusTrackingState extends State<BusTracking> { String apiKey = orsapikey; //OpenRouteService API key late String distance = ''; late String time = ''; bool isLoading = false; //A flag to check the status of the api data loading late LatLng sourceLocation = LatLng(0, 0); //For user location // late LatLng destinationLocation = LatLng(30.3253, // 78.0413); //Destination Location (retrieved from the firebase database; must be connected to firebase) late LatLng destinationLocation = LatLng(0, 0); // double destinationLatitude = 0; // Initialize with default value // double destinationLongitude = 0; // Initialize with default value List<LatLng> polylinePoints = []; final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); late DatabaseReference dbRef; // Query dbRef2 = FirebaseDatabase.instance.ref().child('DestinationLocation'); @override void initState() { super.initState(); // dbRef2.once().then((snapshot){ // if (snapshot.value != null) { // final destinationLocationData = snapshot.value as Map<dynamic, dynamic>?; // if (destinationLocationData != null) { // final latitude = destinationLocationData['Latitude'] as double?; // final longitude = destinationLocationData['Longitude'] as double?; // if (latitude != null && longitude != null) { // setState(() { // destinationLatitude = latitude; // destinationLongitude = longitude; // }); // } // } // } // }); // Initialize Firebase Database reference try{ final dbReference = FirebaseDatabase.instance.ref().child('DestinationLocation'); dbReference.once().then((DatabaseEvent databaseEvent) { if (databaseEvent.snapshot.value != null) { final destinationLocationData = databaseEvent.snapshot.value as Map<dynamic, dynamic>; final latitude = destinationLocationData['latitude'] as double?; final longitude = destinationLocationData['longitude'] as double?; print(latitude); print(longitude); if (latitude != null && longitude != null) { setState(() { destinationLocation = LatLng(latitude, longitude); }); } } }); } catch (e) { throw Exception("Error accessing Firebase Database"); } dbRef = FirebaseDatabase.instance.ref().child('Value'); initNotifications(); requestPermission(); } // dbRef.onValue.listen((event) { // if (event.snapshot.value != null) { // final locationString = event.snapshot.value as String; // final regex = RegExp(r'LatLng\(latitude:(.*), longitude:(.*)\)'); // final match = regex.firstMatch(locationString); // if (match != null && match.groupCount == 2) { // final latitude = double.parse(match.group(1)!); // final longitude = double.parse(match.group(2)!); // print("Latitude: $latitude, Longitude: $longitude"); // setState(() { // destinationLocation = LatLng(latitude, longitude); // }); // } // } // }); //Permission to access live-location Future<void> requestPermission() async { LocationPermission permission = await Geolocator.requestPermission(); if (permission == LocationPermission.denied) { showDialog( context: context, builder: (BuildContext context) => AlertDialog( title: Text('Location Permission Required'), content: Text('This app needs to access your location to work properly.'), actions: <Widget>[ TextButton( child: Text('Cancel'), onPressed: () => Navigator.of(context).pop(), ), TextButton( child: Text('Settings'), onPressed: () => AppSettings.openAppSettings(), ), ], ), ); } else if (permission == LocationPermission.deniedForever) { showDialog( context: context, builder: (BuildContext context) => AlertDialog( title: Text('Location Permission Required'), content: Text('This app needs to access your location to work properly.'), actions: <Widget>[ TextButton( child: Text('Cancel'), onPressed: () => Navigator.of(context).pop(), ), TextButton( child: Text('Settings'), onPressed: () => AppSettings.openAppSettings(), ), ], ), ); } else { getCurrentLocation(); } } //Extraction of Live-location Future<void> getCurrentLocation() async { Position position = await Geolocator.getCurrentPosition( desiredAccuracy: LocationAccuracy.high); setState(() { sourceLocation = LatLng(position.latitude, position.longitude); }); fetchPolyline(sourceLocation, destinationLocation).then((points) { setState(() { polylinePoints = points; }); }); } //Time format String formatTime(double duration) { if (duration >= 60) { int hours = duration ~/ 60; int minutes = (duration % 60).toInt(); return '${hours}h ${minutes}m'; } else { return '${duration.round()}min'; } } //Notification Alert for Bus_Arrival Future<void> initNotifications() async { const AndroidInitializationSettings initializationSettingsAndroid = AndroidInitializationSettings('@mipmap/ic_launcher'); final DarwinInitializationSettings initializationSettingsIOS = DarwinInitializationSettings( requestSoundPermission: true, requestBadgePermission: true, requestAlertPermission: true, ); final InitializationSettings initializationSettings = InitializationSettings( android: initializationSettingsAndroid, iOS: initializationSettingsIOS, ); await flutterLocalNotificationsPlugin.initialize(initializationSettings); } Future<void> showNotification() async { const AndroidNotificationDetails androidPlatformChannelSpecifics = AndroidNotificationDetails( 'bus_arrival_channel', 'Bus Arrival', importance: Importance.max, priority: Priority.high, ); const DarwinNotificationDetails iOSPlatformChannelSpecifics = DarwinNotificationDetails(); const NotificationDetails platformChannelSpecifics = NotificationDetails( android: androidPlatformChannelSpecifics, iOS: iOSPlatformChannelSpecifics, ); await flutterLocalNotificationsPlugin.show( 0, 'Bus is about to reach', 'The bus will arrive within 2 minutes.', platformChannelSpecifics, ); } //Calculate distance and time through an API request using OpenRouteService API Future<void> calculateDistanceAndTime() async { setState(() { isLoading = true; }); String url = 'https://api.openrouteservice.org/v2/directions/driving-car?api_key=$apiKey&start=${sourceLocation.longitude},${sourceLocation.latitude}&end=${destinationLocation.longitude},${destinationLocation.latitude}'; try { final response = await http.get(Uri.parse(url)); if (response.statusCode == 200) { final jsonResponse = json.decode(response.body); final route = jsonResponse['features'][0]['properties']; setState(() { distance = (route['segments'][0]['distance'] / 1000).toStringAsFixed(2) + "km"; double duration = (route['segments'][0]['duration'] / 60); time = formatTime(duration); }); //This will display an alert that the bus is near // if (double.parse(time) <= 2) { // showNotification(); // } } else { throw Exception('Failed to load data'); } } catch (e) { print('Error: $e'); } finally { setState(() { isLoading = false; }); } } //Fetching polylines points via the ORS API Future<List<LatLng>> fetchPolyline(LatLng source, LatLng destination) async { final response = await http.get(Uri.parse( 'https://api.openrouteservice.org/v2/directions/driving-car?api_key=$apiKey&start=${source.longitude},${source.latitude}&end=${destination.longitude},${destination.latitude}')); if (response.statusCode == 200) { final jsonResponse = jsonDecode(response.body); final coordinates = jsonResponse['features'][0]['geometry']['coordinates']; return coordinates .map<LatLng>((coord) => LatLng(coord[1], coord[0])) .toList(); } else { throw Exception('Failed to load polyline'); } } void _showLogoutConfirmationDialog() { showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: Text('Logout'), content: Text('Do you want to log out?'), actions: [ TextButton( onPressed: () { // Perform logout operation Navigator.of(context).pop(); // Add your logout logic here }, child: Text('Yes'), ), TextButton( onPressed: () { Navigator.of(context).pop(); }, child: Text('No'), ), ], ); }, ); } @override Widget build(BuildContext context) { final bool isDistanceTimeVisible = distance.isNotEmpty && time.isNotEmpty; return Scaffold( appBar: AppBar( backgroundColor: Colors.white, title: Text( 'Select Route', style: TextStyle(color: Colors.black), ), leading: Builder( builder: (BuildContext context) { return IconButton( icon: Icon(Icons.menu), color: Colors.black, onPressed: () { Scaffold.of(context).openDrawer(); }, ); }, ), ), drawer: Drawer( child: ListView( padding: EdgeInsets.zero, children: <Widget>[ DrawerHeader( decoration: BoxDecoration( color: Colors.blue, ), child: Text( 'Menu', style: TextStyle( color: Colors.white, fontSize: 24, ), ), ), ListTile( title: Text('Select Route'), onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => LocationsPage(), ), ); }, ), ListTile( title: Text('Profile'), onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => ProfilePage(), ), ); }, ), ListTile( title: Text('Logout'), onTap: _showLogoutConfirmationDialog, ), ], ), ), body: Column( children: [ Expanded( child: FlutterMap( options: MapOptions( center: LatLng(destinationLocation.latitude, destinationLocation.longitude), zoom: 15.0, ), children: [ TileLayer( urlTemplate: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', subdomains: ['a', 'b', 'c'], ), MarkerLayer( markers: [ Marker( width: 30.0, height: 30.0, point: sourceLocation, builder: (ctx) => Container( child: Image.asset( 'assets/images/person.png', //Custom Person icon width: 5.0, height: 5.0, ), ), ), Marker( width: 35.0, height: 35.0, point: LatLng(destinationLocation.latitude, destinationLocation.longitude), builder: (ctx) => Container( child: Image.asset( 'assets/images/busicon.png', //Custom Bus icon width: 5.0, height: 5.0, ), ), ), ], ), PolylineLayer( polylines: [ Polyline( points: polylinePoints, strokeWidth: 4.0, color: Colors.blue, ), ], ), ], ), ), Padding( padding: const EdgeInsets.all(8.0), child: Column( children: [ Text( 'Distance: $distance', style: TextStyle(fontSize: 16), ), Text( 'Time: $time', style: TextStyle(fontSize: 16), ), Text( 'Latitude: ${destinationLocation.latitude}', style: TextStyle(fontSize: 16), ), Text( 'Longitude: ${destinationLocation.longitude}', style: TextStyle(fontSize: 16), ), if (!isDistanceTimeVisible) // calculateDistanceAndTime();isLoading ? null : calculateDistanceAndTime, ElevatedButton( onPressed: () { isLoading ? null : calculateDistanceAndTime().then((value) { Map<String, String> values = { 'Distance': distance, 'Time': time, 'sourceLocation': sourceLocation.toString(), 'destinationLocation': destinationLocation.toString(), }; dbRef.push().set(values); }); }, child: Text('Show Distance & Time'), style: ButtonStyle( backgroundColor: MaterialStateProperty.resolveWith<Color>( (Set<MaterialState> states) { if (states.contains(MaterialState.disabled)) { return Colors.grey; } return Colors .blue; //when ORS api data fetching is successful and it is ready to show required data(distance and time) }, ), ), ), ], ), ), ], ), ); } }
0
mirrored_repositories/Bus-Tracking-system/src/bus_tracking_system/lib
mirrored_repositories/Bus-Tracking-system/src/bus_tracking_system/lib/screen/ui.dart
import 'dart:math'; import 'package:bus_tracking_system/Constants/constants.dart'; import 'package:bus_tracking_system/helper/helperFunction.dart'; import 'package:bus_tracking_system/screen/splash.dart'; import 'package:bus_tracking_system/services/authServices.dart'; import 'package:bus_tracking_system/services/databaseServices.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_database/firebase_database.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:bus_tracking_system/screen/locations_page.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:bus_tracking_system/screen/DriverLoginPage.dart'; // import 'package:location/location.dart'; class UI extends StatefulWidget { //is a @override State<UI> createState() => _UIState(); } class _UIState extends State<UI> { AuthService _auth = AuthService(); bool isStudent = true; late final String email; late final String password; final _formfield = GlobalKey<FormState>(); TextEditingController emailController = TextEditingController(); TextEditingController passController = TextEditingController(); bool passToggle = true; late DatabaseReference dbRef; void toggleLoginOption() { setState(() { isStudent = !isStudent; }); } @override void initState() { super.initState(); dbRef = FirebaseDatabase.instance.ref().child('Students'); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( centerTitle: true, title: Text( 'BUS TRACKER', ), ), body: Center( child: Padding( padding: EdgeInsets.symmetric(horizontal: 20, vertical: 60), child: Form( key: _formfield, child: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Text( isStudent ? 'LOGIN' : 'LOGIN', style: TextStyle( fontSize: 24, fontWeight: FontWeight.bold, ), ), SizedBox(height: 20), TextFormField( keyboardType: TextInputType.emailAddress, controller: emailController, decoration: InputDecoration( labelText: "Email", border: OutlineInputBorder(), prefixIcon: Icon(Icons.email), ), validator: (value) { bool emailValid = RegExp( r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-z0-9]+\.[a-zA-Z]+") .hasMatch(value!); if (value.isEmpty) { return "Enter Email"; } else if (!emailValid) { return "Enter valid Email"; } }, ), SizedBox(height: 10), TextFormField( keyboardType: TextInputType.emailAddress, controller: passController, obscureText: passToggle, decoration: InputDecoration( labelText: "Password", border: OutlineInputBorder(), prefixIcon: Icon(Icons.lock), suffixIcon: InkWell( onTap: () { setState(() { passToggle = !passToggle; }); }, child: Icon(passToggle ? Icons.visibility_off : Icons.visibility)), ), validator: (value) { if (value!.isEmpty) { return 'Enter Password'; } else if (passController.text.length < 9) { return "Password length should be more than 9 characters"; } }, ), SizedBox(height: 20), InkWell( onTap: () { Map<String, String> Students = { 'email': emailController.text, 'password': passController.text, }; dbRef.push().set(Students); FirebaseAuth.instance .signInWithEmailAndPassword( email: emailController.text, password: passController.text) .then((value) { Navigator.push( context, MaterialPageRoute(builder: (BuildContext context) { return LocationsPage(); }), ); }); }, child: Container( height: 50, decoration: BoxDecoration( color: Colors.blueAccent, borderRadius: BorderRadius.circular(5), ), child: Center( child: Text( "Login", style: TextStyle( color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold, ), ), ), ), ), SizedBox(height: 10), TextButton( onPressed: () { if (isStudent) { Navigator.push( context, MaterialPageRoute(builder: (context) => DriverLoginPage()), ); } else { Navigator.push( context, MaterialPageRoute(builder: (context) => LocationsPage()), ); } }, child: Text( isStudent ? 'Log in as Driver' : 'Log in as Student', style: TextStyle(fontSize: 20), ), ), ], ))), ), ), ); } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(StringProperty('password', password)); } }
0
mirrored_repositories/Bus-Tracking-system/src/bus_tracking_system/lib
mirrored_repositories/Bus-Tracking-system/src/bus_tracking_system/lib/helper/helperFunction.dart
import 'package:shared_preferences/shared_preferences.dart'; class HelperFunctions { //class used in ui.dart static String userLoggedInKey = "LOGGEDINKEY"; static String usernameKey = "USERNAMEKEY"; ///to save name static String userEmailKey = "USEREMAILKEY"; // saving the data in shared preferences static Future<bool> savedUserLoggedInStatus(bool isUserloggedIn) async { SharedPreferences sf = await SharedPreferences.getInstance(); return await sf.setBool(userLoggedInKey, isUserloggedIn); //setBool= sets the new value true/false } static Future<bool> savedUserNameSF(String userName) async { SharedPreferences sf = await SharedPreferences.getInstance(); return await sf.setString(usernameKey, userName); } static Future<bool> savedUserEmailSF(String userEmail) async { SharedPreferences sf = await SharedPreferences.getInstance(); return await sf.setString(userEmailKey, userEmail); } // getting the data from shared preferences static Future<bool?> getUserLoggedInStatus() async { SharedPreferences sf = await SharedPreferences.getInstance(); return sf.getBool(userLoggedInKey); //tells if the user is logged in } static Future<String?> getUserEmailFromSF() async { SharedPreferences sf = await SharedPreferences.getInstance(); return sf.getString(userEmailKey); //gives emailid } static Future<String?> getUserNamefromSF() async { SharedPreferences sf = await SharedPreferences.getInstance(); return sf.getString(usernameKey); // } }
0
mirrored_repositories/Bus-Tracking-system/src/bus_tracking_system/lib
mirrored_repositories/Bus-Tracking-system/src/bus_tracking_system/lib/services/authServices.dart
//import 'package:chat_app/helper/helper_function.dart'; import 'package:bus_tracking_system/services/databaseServices.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; class AuthService { final FirebaseAuth firebaseAuth = FirebaseAuth.instance; //login Future loginWithUserEmailandPassword(String email, String password) async { try { User user = (await firebaseAuth.signInWithEmailAndPassword( //firebase class=User //signinwithemailandpass email: email, password: password)) .user!; if (user != null) { return true; } } on FirebaseAuthException catch (e) { return e.message; } } //register Future registerUserWithEmailandPassword( String fullName, String email, String password) async { try { User user = (await firebaseAuth.createUserWithEmailAndPassword( email: email, password: password)) .user!; if (user != null) { await DatabaseService(uid: user.uid).savingUserData(fullName, email); return true; } } on FirebaseAuthException catch (e) { return e.message; } } //sign out /*Future signOut() async { try { await HelperFunctions.savedUserLoggedInStatus(false);//helperfunction is a file with shared preference await HelperFunctions.savedUserEmailSF(""); await HelperFunctions.savedUserNameSF(""); await firebaseAuth.signOut(); } catch (e) { return null; } }*/ }
0