repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/E-Commerce-Store/lib/utils/theme
mirrored_repositories/E-Commerce-Store/lib/utils/theme/widget_themes/elevated_button_theme.dart
import 'package:flutter/material.dart'; import '../../constants/colors.dart'; import '../../constants/sizes.dart'; class CustomElevatedButtonTheme { CustomElevatedButtonTheme._(); /* -- Light Theme -- */ static final lightElevatedButtonTheme = ElevatedButtonThemeData( style: ElevatedButton.styleFrom( elevation: 0, foregroundColor: AppColors.light, backgroundColor: AppColors.primary, disabledForegroundColor: AppColors.darkGrey, disabledBackgroundColor: AppColors.buttonDisabled, side: const BorderSide(color: AppColors.primary), padding: const EdgeInsets.symmetric(vertical: Sizes.buttonHeight), textStyle: const TextStyle( fontSize: 16, color: AppColors.textWhite, fontWeight: FontWeight.w600), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(Sizes.buttonRadius)), ), ); /* -- Dark Theme -- */ static final darkElevatedButtonTheme = ElevatedButtonThemeData( style: ElevatedButton.styleFrom( elevation: 0, foregroundColor: AppColors.light, backgroundColor: AppColors.primary, disabledForegroundColor: AppColors.darkGrey, disabledBackgroundColor: AppColors.darkerGrey, side: const BorderSide(color: AppColors.primary), padding: const EdgeInsets.symmetric(vertical: Sizes.buttonHeight), textStyle: const TextStyle( fontSize: 16, color: AppColors.textWhite, fontWeight: FontWeight.w600), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(Sizes.buttonRadius)), ), ); }
0
mirrored_repositories/E-Commerce-Store/lib/utils/theme
mirrored_repositories/E-Commerce-Store/lib/utils/theme/widget_themes/appbar_theme.dart
import 'package:flutter/material.dart'; import '../../constants/colors.dart'; import '../../constants/sizes.dart'; class CustomAppBarTheme { CustomAppBarTheme._(); static const lightAppBarTheme = AppBarTheme( elevation: 0, centerTitle: false, scrolledUnderElevation: 0, backgroundColor: Colors.transparent, surfaceTintColor: Colors.transparent, iconTheme: IconThemeData(color: AppColors.black, size: Sizes.iconMd), actionsIconTheme: IconThemeData(color: AppColors.black, size: Sizes.iconMd), titleTextStyle: TextStyle( fontSize: 18.0, fontWeight: FontWeight.w600, color: AppColors.black), ); static const darkAppBarTheme = AppBarTheme( elevation: 0, centerTitle: false, scrolledUnderElevation: 0, backgroundColor: Colors.transparent, surfaceTintColor: Colors.transparent, iconTheme: IconThemeData(color: AppColors.black, size: Sizes.iconMd), actionsIconTheme: IconThemeData(color: AppColors.white, size: Sizes.iconMd), titleTextStyle: TextStyle( fontSize: 18.0, fontWeight: FontWeight.w600, color: AppColors.white), ); }
0
mirrored_repositories/E-Commerce-Store/lib/utils/theme
mirrored_repositories/E-Commerce-Store/lib/utils/theme/widget_themes/checkbox_theme.dart
import 'package:flutter/material.dart'; import '../../constants/colors.dart'; import '../../constants/sizes.dart'; class CustomCheckboxTheme { CustomCheckboxTheme._(); /// Customizable Light Text Theme static CheckboxThemeData lightCheckboxTheme = CheckboxThemeData( shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(Sizes.xs)), checkColor: MaterialStateProperty.resolveWith((states) { if (states.contains(MaterialState.selected)) { return AppColors.white; } else { return AppColors.black; } }), fillColor: MaterialStateProperty.resolveWith((states) { if (states.contains(MaterialState.selected)) { return AppColors.primary; } else { return Colors.transparent; } }), ); /// Customizable Dark Text Theme static CheckboxThemeData darkCheckboxTheme = CheckboxThemeData( shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(Sizes.xs)), checkColor: MaterialStateProperty.resolveWith((states) { if (states.contains(MaterialState.selected)) { return AppColors.white; } else { return AppColors.black; } }), fillColor: MaterialStateProperty.resolveWith((states) { if (states.contains(MaterialState.selected)) { return AppColors.primary; } else { return Colors.transparent; } }), ); }
0
mirrored_repositories/E-Commerce-Store/lib/utils
mirrored_repositories/E-Commerce-Store/lib/utils/helpers/pricing_calculator.dart
class PricingCalculator { /// -- Calculate Price based on tax and shipping static double calculateTotalPrice(double productPrice, String location) { double taxRate = getTaxRateForLocation(location); double taxAmount = productPrice * taxRate; double shippingCost = getShippingCost(location); double totalPrice = productPrice + taxAmount + shippingCost; return totalPrice; } /// -- Calculate shipping cost static String calculateShippingCost(double productPrice, String location) { double shippingCost = getShippingCost(location); return shippingCost.toStringAsFixed(2); } /// -- Calculate tax static String calculateTax(double productPrice, String location) { double taxRate = getTaxRateForLocation(location); double taxAmount = productPrice * taxRate; return taxAmount.toStringAsFixed(2); } static double getTaxRateForLocation(String location) { return 0.10; } static double getShippingCost(String location) { return 5.00; } }
0
mirrored_repositories/E-Commerce-Store/lib/utils
mirrored_repositories/E-Commerce-Store/lib/utils/helpers/helper_functions.dart
import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:intl/intl.dart'; class HelperFunctions { static Color? getColor(String value) { if (value == 'Green') { return Colors.green; } else if (value == 'Green') { return Colors.green; } else if (value == 'Red') { return Colors.red; } else if (value == 'Blue') { return Colors.blue; } else if (value == 'Pink') { return Colors.pink; } else if (value == 'Grey') { return Colors.grey; } else if (value == 'Purple') { return Colors.purple; } else if (value == 'Black') { return Colors.black; } else if (value == 'White') { return Colors.white; } else if (value == 'Yellow') { return Colors.yellow; } else if (value == 'Orange') { return Colors.deepOrange; } else if (value == 'Brown') { return Colors.brown; } else if (value == 'Teal') { return Colors.teal; } else if (value == 'Indigo') { return Colors.indigo; } else { return null; } } static void showSnackBar(String message) { ScaffoldMessenger.of(Get.context!).showSnackBar( SnackBar(content: Text(message)), ); } static void showAlert(String title, String message) { showDialog( context: Get.context!, builder: (BuildContext context) { return AlertDialog( title: Text(title), content: Text(message), actions: [ TextButton( onPressed: () => Navigator.of(context).pop(), child: const Text('OK'), ), ], ); }, ); } static void navigateToScreen(BuildContext context, Widget screen) { Navigator.push( context, MaterialPageRoute(builder: (_) => screen), ); } static String truncateText(String text, int maxLength) { if (text.length <= maxLength) { return text; } else { return '${text.substring(0, maxLength)}...'; } } static bool isDarkMode(BuildContext context) { return Theme.of(context).brightness == Brightness.dark; } static Size screenSize() { return MediaQuery.of(Get.context!).size; } static double screenHeight() { return MediaQuery.of(Get.context!).size.height; } static double screenWidth() { return MediaQuery.of(Get.context!).size.width; } static String getFormattedDate(DateTime date, {String format = 'dd MMM yyyy'}) { return DateFormat(format).format(date); } static List<T> removeDuplicates<T>(List<T> list) { return list.toSet().toList(); } static List<Widget> wrapWidgets(List<Widget> widgets, int rowSize) { final wrappedList = <Widget>[]; for (var i = 0; i < widgets.length; i += rowSize) { final rowChildren = widgets.sublist( i, i + rowSize > widgets.length ? widgets.length : i + rowSize); wrappedList.add(Row(children: rowChildren)); } return wrappedList; } }
0
mirrored_repositories/E-Commerce-Store/lib/utils
mirrored_repositories/E-Commerce-Store/lib/utils/exceptions/exceptions.dart
class CustomExceptions implements Exception { final String message; /// Default constructor with a generic error message. const CustomExceptions( [this.message = 'An unexpected error occurred. Please try again.']); /// Create an authentication exception from a Firebase authentication exception code. factory CustomExceptions.fromCode(String code) { switch (code) { case 'email-already-in-use': return const CustomExceptions( 'The email address is already registered. Please use a different email.'); case 'invalid-email': return const CustomExceptions( 'The email address provided is invalid. Please enter a valid email.'); case 'weak-password': return const CustomExceptions( 'The password is too weak. Please choose a stronger password.'); case 'user-disabled': return const CustomExceptions( 'This user account has been disabled. Please contact support for assistance.'); case 'user-not-found': return const CustomExceptions('Invalid login details. User not found.'); case 'wrong-password': return const CustomExceptions( 'Incorrect password. Please check your password and try again.'); case 'INVALID_LOGIN_CREDENTIALS': return const CustomExceptions( 'Invalid login credentials. Please double-check your information.'); case 'too-many-requests': return const CustomExceptions( 'Too many requests. Please try again later.'); case 'invalid-argument': return const CustomExceptions( 'Invalid argument provided to the authentication method.'); case 'invalid-password': return const CustomExceptions('Incorrect password. Please try again.'); case 'invalid-phone-number': return const CustomExceptions('The provided phone number is invalid.'); case 'operation-not-allowed': return const CustomExceptions( 'The sign-in provider is disabled for your Firebase project.'); case 'session-cookie-expired': return const CustomExceptions( 'The Firebase session cookie has expired. Please sign in again.'); case 'uid-already-exists': return const CustomExceptions( 'The provided user ID is already in use by another user.'); case 'sign_in_failed': return const CustomExceptions('Sign-in failed. Please try again.'); case 'network-request-failed': return const CustomExceptions( 'Network request failed. Please check your internet connection.'); case 'internal-error': return const CustomExceptions( 'Internal error. Please try again later.'); case 'invalid-verification-code': return const CustomExceptions( 'Invalid verification code. Please enter a valid code.'); case 'invalid-verification-id': return const CustomExceptions( 'Invalid verification ID. Please request a new verification code.'); case 'quota-exceeded': return const CustomExceptions( 'Quota exceeded. Please try again later.'); default: return const CustomExceptions(); } } }
0
mirrored_repositories/E-Commerce-Store/lib/utils
mirrored_repositories/E-Commerce-Store/lib/utils/exceptions/platform_exceptions.dart
class CustomPlatformException implements Exception { final String code; CustomPlatformException(this.code); String get message { switch (code) { case 'INVALID_LOGIN_CREDENTIALS': return 'Invalid login credentials. Please double-check your information.'; case 'too-many-requests': return 'Too many requests. Please try again later.'; case 'invalid-argument': return 'Invalid argument provided to the authentication method.'; case 'invalid-password': return 'Incorrect password. Please try again.'; case 'invalid-phone-number': return 'The provided phone number is invalid.'; case 'operation-not-allowed': return 'The sign-in provider is disabled for your Firebase project.'; case 'session-cookie-expired': return 'The Firebase session cookie has expired. Please sign in again.'; case 'uid-already-exists': return 'The provided user ID is already in use by another user.'; case 'sign_in_failed': return 'Sign-in failed. Please try again.'; case 'network-request-failed': return 'Network request failed. Please check your internet connection.'; case 'internal-error': return 'Internal error. Please try again later.'; case 'invalid-verification-code': return 'Invalid verification code. Please enter a valid code.'; case 'invalid-verification-id': return 'Invalid verification ID. Please request a new verification code.'; case 'quota-exceeded': return 'Quota exceeded. Please try again later.'; default: return 'An unexpected platform error occurred. Please try again.'; } } }
0
mirrored_repositories/E-Commerce-Store/lib/utils
mirrored_repositories/E-Commerce-Store/lib/utils/exceptions/firebase_exceptions.dart
class CustomFirebaseException implements Exception { final String code; /// Constructor that takes an error code. CustomFirebaseException(this.code); /// Get the corresponding error message based on the error code. String get message { switch (code) { case 'unknown': return 'An unknown Firebase error occurred. Please try again.'; case 'invalid-custom-token': return 'The custom token format is incorrect. Please check your custom token.'; case 'custom-token-mismatch': return 'The custom token corresponds to a different audience.'; case 'user-disabled': return 'The user account has been disabled.'; case 'user-not-found': return 'No user found for the given email or UID.'; case 'invalid-email': return 'The email address provided is invalid. Please enter a valid email.'; case 'email-already-in-use': return 'The email address is already registered. Please use a different email.'; case 'wrong-password': return 'Incorrect password. Please check your password and try again.'; case 'weak-password': return 'The password is too weak. Please choose a stronger password.'; case 'provider-already-linked': return 'The account is already linked with another provider.'; case 'operation-not-allowed': return 'This operation is not allowed. Contact support for assistance.'; case 'invalid-credential': return 'The supplied credential is malformed or has expired.'; case 'invalid-verification-code': return 'Invalid verification code. Please enter a valid code.'; case 'invalid-verification-id': return 'Invalid verification ID. Please request a new verification code.'; case 'captcha-check-failed': return 'The reCAPTCHA response is invalid. Please try again.'; case 'app-not-authorized': return 'The app is not authorized to use Firebase Authentication with the provided API key.'; case 'keychain-error': return 'A keychain error occurred. Please check the keychain and try again.'; case 'internal-error': return 'An internal authentication error occurred. Please try again later.'; case 'invalid-app-credential': return 'The app credential is invalid. Please provide a valid app credential.'; case 'user-mismatch': return 'The supplied credentials do not correspond to the previously signed-in user.'; case 'requires-recent-login': return 'This operation is sensitive and requires recent authentication. Please log in again.'; case 'quota-exceeded': return 'Quota exceeded. Please try again later.'; case 'account-exists-with-different-credential': return 'An account already exists with the same email but different sign-in credentials.'; case 'missing-iframe-start': return 'The email template is missing the iframe start tag.'; case 'missing-iframe-end': return 'The email template is missing the iframe end tag.'; case 'missing-iframe-src': return 'The email template is missing the iframe src attribute.'; case 'auth-domain-config-required': return 'The authDomain configuration is required for the action code verification link.'; case 'missing-app-credential': return 'The app credential is missing. Please provide valid app credentials.'; case 'session-cookie-expired': return 'The Firebase session cookie has expired. Please sign in again.'; case 'uid-already-exists': return 'The provided user ID is already in use by another user.'; case 'web-storage-unsupported': return 'Web storage is not supported or is disabled.'; case 'app-deleted': return 'This instance of FirebaseApp has been deleted.'; case 'user-token-mismatch': return 'The provided user\'s token has a mismatch with the authenticated user\'s user ID.'; case 'invalid-message-payload': return 'The email template verification message payload is invalid.'; case 'invalid-sender': return 'The email template sender is invalid. Please verify the sender\'s email.'; case 'invalid-recipient-email': return 'The recipient email address is invalid. Please provide a valid recipient email.'; case 'missing-action-code': return 'The action code is missing. Please provide a valid action code.'; case 'user-token-expired': return 'The user\'s token has expired, and authentication is required. Please sign in again.'; case 'INVALID_LOGIN_CREDENTIALS': return 'Invalid login credentials.'; case 'expired-action-code': return 'The action code has expired. Please request a new action code.'; case 'invalid-action-code': return 'The action code is invalid. Please check the code and try again.'; case 'credential-already-in-use': return 'This credential is already associated with a different user account.'; default: return 'An unexpected Firebase error occurred. Please try again.'; } } }
0
mirrored_repositories/E-Commerce-Store/lib/utils
mirrored_repositories/E-Commerce-Store/lib/utils/exceptions/format_exceptions.dart
class CustomFormatException implements Exception { /// The associated error message. final String message; /// Default constructor with a generic error message. const CustomFormatException( [this.message = 'An unexpected format error occurred. Please check your input.']); /// Create a format exception from a specific error message. factory CustomFormatException.fromMessage(String message) { return CustomFormatException(message); } /// Get the corresponding error message. String get formattedMessage => message; /// Create a format exception from a specific error code. factory CustomFormatException.fromCode(String code) { switch (code) { case 'invalid-email-format': return const CustomFormatException( 'The email address format is invalid. Please enter a valid email.'); case 'invalid-phone-number-format': return const CustomFormatException( 'The provided phone number format is invalid. Please enter a valid number.'); case 'invalid-date-format': return const CustomFormatException( 'The date format is invalid. Please enter a valid date.'); case 'invalid-url-format': return const CustomFormatException( 'The URL format is invalid. Please enter a valid URL.'); case 'invalid-credit-card-format': return const CustomFormatException( 'The credit card format is invalid. Please enter a valid credit card number.'); case 'invalid-numeric-format': return const CustomFormatException( 'The input should be a valid numeric format.'); default: return const CustomFormatException(); } } }
0
mirrored_repositories/E-Commerce-Store/lib/utils
mirrored_repositories/E-Commerce-Store/lib/utils/exceptions/firebase_auth_exceptions.dart
class CustomFirebaseAuthException implements Exception { final String code; /// Constructor that takes an error code. CustomFirebaseAuthException(this.code); /// Get the corresponding error message based on the error code. String get message { switch (code) { case 'email-already-in-use': return 'The email address is already registered. Please use a different email.'; case 'invalid-email': return 'The email address provided is invalid. Please enter a valid email.'; case 'weak-password': return 'The password is too weak. Please choose a stronger password.'; case 'user-disabled': return 'This user account has been disabled. Please contact support for assistance.'; case 'user-not-found': return 'Invalid login details. User not found.'; case 'wrong-password': return 'Incorrect password. Please check your password and try again.'; case 'invalid-verification-code': return 'Invalid verification code. Please enter a valid code.'; case 'invalid-verification-id': return 'Invalid verification ID. Please request a new verification code.'; case 'quota-exceeded': return 'Quota exceeded. Please try again later.'; case 'email-already-exists': return 'The email address already exists. Please use a different email.'; case 'provider-already-linked': return 'The account is already linked with another provider.'; case 'requires-recent-login': return 'This operation is sensitive and requires recent authentication. Please log in again.'; case 'credential-already-in-use': return 'This credential is already associated with a different user account.'; case 'user-mismatch': return 'The supplied credentials do not correspond to the previously signed in user.'; case 'account-exists-with-different-credential': return 'An account already exists with the same email but different sign-in credentials.'; case 'operation-not-allowed': return 'This operation is not allowed. Contact support for assistance.'; case 'expired-action-code': return 'The action code has expired. Please request a new action code.'; case 'invalid-action-code': return 'The action code is invalid. Please check the code and try again.'; case 'missing-action-code': return 'The action code is missing. Please provide a valid action code.'; case 'user-token-expired': return 'The user\'s token has expired, and authentication is required. Please sign in again.'; case 'invalid-credential': return 'The supplied credential is malformed or has expired.'; case 'user-token-revoked': return 'The user\'s token has been revoked. Please sign in again.'; case 'invalid-message-payload': return 'The email template verification message payload is invalid.'; case 'invalid-sender': return 'The email template sender is invalid. Please verify the sender\'s email.'; case 'invalid-recipient-email': return 'The recipient email address is invalid. Please provide a valid recipient email.'; case 'missing-iframe-start': return 'The email template is missing the iframe start tag.'; case 'missing-iframe-end': return 'The email template is missing the iframe end tag.'; case 'missing-iframe-src': return 'The email template is missing the iframe src attribute.'; case 'auth-domain-config-required': return 'The authDomain configuration is required for the action code verification link.'; case 'missing-app-credential': return 'The app credential is missing. Please provide valid app credentials.'; case 'invalid-app-credential': return 'The app credential is invalid. Please provide a valid app credential.'; case 'session-cookie-expired': return 'The Firebase session cookie has expired. Please sign in again.'; case 'uid-already-exists': return 'The provided user ID is already in use by another user.'; case 'invalid-cordova-configuration': return 'The provided Cordova configuration is invalid.'; case 'app-deleted': return 'This instance of FirebaseApp has been deleted.'; case 'user-token-mismatch': return 'The provided user\'s token has a mismatch with the authenticated user\'s user ID.'; case 'web-storage-unsupported': return 'Web storage is not supported or is disabled.'; case 'app-not-authorized': return 'The app is not authorized to use Firebase Authentication with the provided API key.'; case 'keychain-error': return 'A keychain error occurred. Please check the keychain and try again.'; case 'internal-error': return 'An internal authentication error occurred. Please try again later.'; case 'INVALID_LOGIN_CREDENTIALS': return 'Invalid login credentials.'; default: return 'An unexpected authentication error occurred. Please try again.'; } } }
0
mirrored_repositories/flutter_google_map_route
mirrored_repositories/flutter_google_map_route/lib/map_request.dart
import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'package:http/http.dart' as http; import 'dart:convert'; const apiKey = "YOUR_API_KEY"; class GoogleMapsServices{ Future<String> getRouteCoordinates(LatLng l1, LatLng l2)async{ String url = "https://maps.googleapis.com/maps/api/directions/json?origin=${l1.latitude},${l1.longitude}&destination=${l2.latitude},${l2.longitude}&key=$apiKey"; http.Response response = await http.get(url); Map values = jsonDecode(response.body); print("====================>>>>>>>>${values}"); return values["routes"][0]["overview_polyline"]["points"]; } }
0
mirrored_repositories/flutter_google_map_route
mirrored_repositories/flutter_google_map_route/lib/main.dart
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_map_route/map_request.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'package:location/location.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Google Maps Demo', home: MapSample(), ); } } class MapSample extends StatefulWidget { @override State<MapSample> createState() => MapSampleState(); } class MapSampleState extends State<MapSample> { bool loading = true; final Set<Marker> _markers = {}; final Set<Polyline> _polyLines = {}; GoogleMapsServices _googleMapsServices = GoogleMapsServices(); Set<Polyline> get polyLines => _polyLines; Completer<GoogleMapController> _controller = Completer(); static LatLng latLng; LocationData currentLocation; // Future<Position> locateUser() async { // return Geolocator() // .getCurrentPosition(desiredAccuracy: LocationAccuracy.high); // } @override void initState() { setState(() { getLocation(); }); // loading = true; super.initState(); } // getUserLocation() async { // __currentLocation = await locateUser(); // setState(() { // latLng = LatLng(__currentLocation.latitude, __currentLocation.longitude); // _onAddMarkerButtonPressed(); // }); // print('center:====== $latLng'); // } getLocation() async { var location = new Location(); location.onLocationChanged().listen(( currentLocation) { print(currentLocation.latitude); print(currentLocation.longitude); setState(() { latLng = LatLng(currentLocation.latitude, currentLocation.longitude); }); print("getLocation:$latLng"); _onAddMarkerButtonPressed(); loading = false; }); } void _onAddMarkerButtonPressed() { setState(() { _markers.add(Marker( markerId: MarkerId("111"), position: latLng, icon: BitmapDescriptor.defaultMarker, )); }); } void onCameraMove(CameraPosition position) { latLng = position.target; } List<LatLng> _convertToLatLng(List points) { List<LatLng> result = <LatLng>[]; for (int i = 0; i < points.length; i++) { if (i % 2 != 0) { result.add(LatLng(points[i - 1], points[i])); } } return result; } void sendRequest() async { LatLng destination = LatLng(20.008751, 73.780037); String route = await _googleMapsServices.getRouteCoordinates( latLng, destination); createRoute(route); _addMarker(destination,"KTHM Collage"); } void createRoute(String encondedPoly) { _polyLines.add(Polyline( polylineId: PolylineId(latLng.toString()), width: 4, points: _convertToLatLng(_decodePoly(encondedPoly)), color: Colors.red)); } void _addMarker(LatLng location, String address) { _markers.add(Marker( markerId: MarkerId("112"), position: location, infoWindow: InfoWindow(title: address, snippet: "go here"), icon: BitmapDescriptor.defaultMarker)); } List _decodePoly(String poly) { var list = poly.codeUnits; var lList = new List(); int index = 0; int len = poly.length; int c = 0; do { var shift = 0; int result = 0; do { c = list[index] - 63; result |= (c & 0x1F) << (shift * 5); index++; shift++; } while (c >= 32); if (result & 1 == 1) { result = ~result; } var result1 = (result >> 1) * 0.00001; lList.add(result1); } while (index < len); for (var i = 2; i < lList.length; i++) lList[i] += lList[i - 2]; print(lList.toString()); return lList; } @override Widget build(BuildContext context) { // print("getLocation111:$latLng"); return new Scaffold( body: GoogleMap( polylines: polyLines, markers: _markers, mapType: MapType.normal, initialCameraPosition: CameraPosition( target: latLng, zoom: 14.4746, ), onCameraMove: onCameraMove, onMapCreated: (GoogleMapController controller) { _controller.complete(controller); }, ), floatingActionButton: FloatingActionButton.extended( onPressed: (){ sendRequest(); }, label: Text('Destination'), icon: Icon(Icons.directions_boat), ), ); } }
0
mirrored_repositories/flutter_google_map_route
mirrored_repositories/flutter_google_map_route/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_map_route/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/SKWeatherApp
mirrored_repositories/SKWeatherApp/lib/main.dart
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:weather_app/bloc/suggestions_popup/suggestions_popup_cubit.dart'; import 'package:weather_app/ui/screens/main_screen.dart'; import 'package:weather_app/ui/theme/app_theme.dart'; import 'bloc/suggestion_cities/suggestion_cities_cubit.dart'; import 'bloc/weather_info/weather_info_cubit.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MultiProvider( providers: [ Provider<WeatherCubit>( create: (context) => WeatherCubit()..getWeatherByName('Odessa'), ), Provider<SuggestionsCubit>( create: (context) => SuggestionsCubit(), ), Provider<CitySuggestionCubit>( create: (context) => CitySuggestionCubit(), ) ], child: MaterialApp( theme: AppTheme.dark, debugShowCheckedModeBanner: false, initialRoute: '/', routes: { '/': (context) => MainScreen(), }, ), ); } }
0
mirrored_repositories/SKWeatherApp/lib/bloc
mirrored_repositories/SKWeatherApp/lib/bloc/weather_info/weather_info_cubit.dart
import 'package:bloc/bloc.dart'; import 'package:weather_app/api/weather_api.dart'; import 'package:weather_app/bloc/weather_info/weather_info_state.dart'; class WeatherCubit extends Cubit<WeatherState> { final WeatherApi weatherApi = WeatherApi(); WeatherCubit() : super(WeatherLoadingState()); Future<void> getWeatherByName(String city) async { try { emit(WeatherLoadingState()); final weather = await weatherApi.getWeatherInCity(city); emit(WeatherLoadedState(cityWeatherModel: weather)); } catch (e) { emit( WeatherErrorState( errorMessage: e.toString(), ), ); } } Future<void> getWeatherById(String id) async { try { emit(WeatherLoadingState()); final weather = await weatherApi.getWeatherInCityByID(id); emit(WeatherLoadedState(cityWeatherModel: weather)); } catch (e) { emit( WeatherErrorState( errorMessage: e.toString(), ), ); } } }
0
mirrored_repositories/SKWeatherApp/lib/bloc
mirrored_repositories/SKWeatherApp/lib/bloc/weather_info/weather_info_state.dart
import 'package:weather_app/api/models/city_weather_model.dart'; abstract class WeatherState {} class WeatherEmptyState extends WeatherState {} class WeatherLoadingState extends WeatherState {} class WeatherLoadedState extends WeatherState { CityWeatherModel cityWeatherModel; WeatherLoadedState({required this.cityWeatherModel}); } class WeatherErrorState extends WeatherState { String errorMessage; WeatherErrorState({required this.errorMessage}); }
0
mirrored_repositories/SKWeatherApp/lib/bloc
mirrored_repositories/SKWeatherApp/lib/bloc/suggestions_popup/suggestions_popup_state.dart
class SuggestionsState { final bool showSuggstion; const SuggestionsState({required this.showSuggstion}); @override bool operator ==(Object other) { return identical(this, other) || (other is SuggestionsState && runtimeType == other.runtimeType && showSuggstion == other.showSuggstion); } @override int get hashCode => showSuggstion.hashCode; SuggestionsState copyWith(bool newState) { return SuggestionsState(showSuggstion: newState); } }
0
mirrored_repositories/SKWeatherApp/lib/bloc
mirrored_repositories/SKWeatherApp/lib/bloc/suggestions_popup/suggestions_popup_cubit.dart
import 'package:bloc/bloc.dart'; import 'package:weather_app/bloc/suggestions_popup/suggestions_popup_state.dart'; class SuggestionsCubit extends Cubit<SuggestionsState> { SuggestionsCubit() : super(const SuggestionsState(showSuggstion: false)); Future<void> changeSuggestionState(bool newState) async { final newS = state.copyWith(newState); emit(newS); } }
0
mirrored_repositories/SKWeatherApp/lib/bloc
mirrored_repositories/SKWeatherApp/lib/bloc/suggestion_cities/suggestion_cities_state.dart
import 'package:weather_app/api/models/city_suggestiond_model.dart'; class CitySuggestionState {} class CitySuggestionLoadedState extends CitySuggestionState { List<CityList> cityListModel; CitySuggestionLoadedState({required this.cityListModel}); } class CitySuggestionErrorState extends CitySuggestionState { String errorMessage; CitySuggestionErrorState({required this.errorMessage}); } class CitySuggestionEmptyState extends CitySuggestionState {}
0
mirrored_repositories/SKWeatherApp/lib/bloc
mirrored_repositories/SKWeatherApp/lib/bloc/suggestion_cities/suggestion_cities_cubit.dart
import 'package:bloc/bloc.dart'; import 'package:weather_app/api/models/city_suggestiond_model.dart'; import 'package:weather_app/api/weather_api.dart'; import 'package:weather_app/bloc/suggestion_cities/suggestion_cities_state.dart'; class CitySuggestionCubit extends Cubit<CitySuggestionState> { final WeatherApi weatherApi = WeatherApi(); CitySuggestionCubit() : super(CitySuggestionEmptyState()); List<CityList> internalList = []; Future<void> setWeather(List<CityList> list) async { if (list.isEmpty) { emit( CitySuggestionErrorState( errorMessage: 'ERROR', ), ); } else { emit(CitySuggestionEmptyState()); final listCities = list; emit(CitySuggestionLoadedState(cityListModel: listCities)); internalList = list; } } Future<List<CityList>> getSuggestionsCityList() async { return internalList; } }
0
mirrored_repositories/SKWeatherApp/lib
mirrored_repositories/SKWeatherApp/lib/api/weather_api.dart
import 'dart:convert'; import 'package:http/http.dart' as http; import 'package:weather_app/api/models/city_suggestiond_model.dart'; import 'package:weather_app/api/models/city_weather_model.dart'; import 'api_key.dart'; class WeatherApi { static const String baseURL = 'api.openweathermap.org'; static const String getWeatherByCityName = 'data/2.5/weather'; static const String getCitiesSuggestion = '/data/2.5/find'; static const apiKey = openWeatherApiKey; Future<CityWeatherModel> getWeatherInCity(String city) async { Map<String, String> params = { 'q': city, 'appid': apiKey, 'units': 'metric' }; var request = await http.get(Uri.https(baseURL, getWeatherByCityName, params)); CityWeatherModel cityWeatherModel = CityWeatherModel.fromJson(json.decode(request.body)); return cityWeatherModel; } Future<CityWeatherModel> getWeatherInCityByID(String cityID) async { Map<String, String> params = { 'id': cityID, 'appid': apiKey, 'units': 'metric' }; var request = await http.get(Uri.https(baseURL, getWeatherByCityName, params)); CityWeatherModel cityWeatherModel = CityWeatherModel.fromJson(json.decode(request.body)); return cityWeatherModel; } Future<List<CityList>> getCitySuggestion(String city) async { Map<String, String> params = {'q': city, 'appid': apiKey}; var request = await http.get(Uri.https(baseURL, getCitiesSuggestion, params)); CitiesSuggestionsModel citiesSuggestionsModel = CitiesSuggestionsModel.fromJson(json.decode(request.body)); List<CityList> suggestions = citiesSuggestionsModel.list.toList(); return suggestions; } }
0
mirrored_repositories/SKWeatherApp/lib
mirrored_repositories/SKWeatherApp/lib/api/api_key.dart
const String openWeatherApiKey = '43ab8c640aaf970b2b2cd835369a340d';
0
mirrored_repositories/SKWeatherApp/lib/api
mirrored_repositories/SKWeatherApp/lib/api/models/city_suggestiond_model.dart
class CitiesSuggestionsModel { int count; List<CityList> list; CitiesSuggestionsModel({required this.count, required this.list}); factory CitiesSuggestionsModel.fromJson(Map<String, dynamic> json) { final cities = (json['list'] as List).map((e) => CityList.fromJson(e)).toList(); return CitiesSuggestionsModel(count: json['count'], list: cities); } } class CityList { int id; String name; Sys sys; CityList({ required this.id, required this.name, required this.sys, }); factory CityList.fromJson(Map<String, dynamic> json) { final sys = Sys.fromJson(json['sys']); return CityList(id: json['id'], name: json['name'], sys: sys); } } class Sys { String country; Sys({required this.country}); factory Sys.fromJson(Map<String, dynamic> json) { return Sys(country: json['country']); } }
0
mirrored_repositories/SKWeatherApp/lib/api
mirrored_repositories/SKWeatherApp/lib/api/models/city_weather_model.dart
class CityWeatherModel { List<Weather> weather; String base; Main main; int dt; Sys sys; int timezone; int id; String name; CityWeatherModel({ required this.weather, required this.base, required this.main, required this.dt, required this.sys, required this.timezone, required this.id, required this.name, }); factory CityWeatherModel.fromJson(Map<String, dynamic> json) { var weather = List.from(json['weather']).map((e) => Weather.fromJson(e)).toList(); var main = Main.fromJson(json['main']); var sys = Sys.fromJson(json['sys']); return CityWeatherModel( weather: weather, base: json['base'], main: main, dt: json['dt'], sys: sys, timezone: json['timezone'], id: json['id'], name: json['name']); } } class Weather { int id; String main; String description; String icon; Weather({ required this.id, required this.main, required this.description, required this.icon, }); factory Weather.fromJson(Map<String, dynamic> json) { return Weather( id: json['id'], main: json['main'], description: json['description'], icon: json['icon']); } } class Main { num temp; double tempMin; double tempMax; Main({ required this.temp, required this.tempMin, required this.tempMax, }); factory Main.fromJson(Map<String, dynamic> json) { return Main( temp: json['temp'], tempMin: json['temp_min'], tempMax: json['temp_max']); } } class Sys { String country; Sys({ required this.country, }); factory Sys.fromJson(Map<String, dynamic> json) { return Sys(country: json['country']); } }
0
mirrored_repositories/SKWeatherApp/lib
mirrored_repositories/SKWeatherApp/lib/helpers/custom_colors.dart
import 'package:flutter/material.dart'; class CustomColors { static const Color hintGrey = Color.fromRGBO(140, 140, 140, 1.0); static const Color lightGrey = Color.fromRGBO(249, 249, 249, 1.0); static const Color transparentWhite = Color.fromRGBO(255, 255, 255, 0.75); }
0
mirrored_repositories/SKWeatherApp/lib
mirrored_repositories/SKWeatherApp/lib/helpers/utils.dart
import 'package:intl/intl.dart'; class Utils { static String getCurrentYear() { return DateFormat('yyyy').format( DateTime.now(), ); } static bool isDayTime() { var now = DateTime.now(); String currentTimeString = DateFormat('HH').format(now).toString(); int currentTimeInt = int.parse(currentTimeString); return currentTimeInt <= 6 || currentTimeInt >= 17 ? false : true; } static String unixToDate(int time) { DateTime date = DateTime.fromMillisecondsSinceEpoch(time * 1000); return (DateFormat('d MMM yyy').format(date)); } }
0
mirrored_repositories/SKWeatherApp/lib
mirrored_repositories/SKWeatherApp/lib/helpers/strings.dart
class Strings { static const String answer = 'But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful.'; static const String faq = 'Frequently Asked Questions'; static const String popularcitiesTitle = 'Check the weather in the most popular cities in the world'; static const String searchBarHint = 'Start typing to search...'; static const String cityNotFoundHint = 'City not found, please try to change your search query'; }
0
mirrored_repositories/SKWeatherApp/lib/ui
mirrored_repositories/SKWeatherApp/lib/ui/widgets/faq_widget.dart
import 'package:flutter/material.dart'; import 'package:weather_app/helpers/custom_colors.dart'; import 'package:weather_app/helpers/utils.dart'; import '../../helpers/strings.dart'; class FaqScreen extends StatefulWidget { const FaqScreen({super.key}); @override State<FaqScreen> createState() => _FaqScreenState(); } class _FaqScreenState extends State<FaqScreen> { bool questionFirstVisibility = false; bool questionSecondVisibility = false; bool questionThirdVisibility = false; bool questionFourthVisibility = false; @override Widget build(BuildContext context) { //dynamic dimensions double tileHeight = MediaQuery.of(context).size.height / 12; return Column( children: [ Column( children: [ SizedBox( height: tileHeight, ), const Padding( padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8), child: Text( Strings.faq, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 26), ), ), SizedBox( height: tileHeight, ), ], ), GestureDetector( onTap: () => { setState(() => questionFirstVisibility = !questionFirstVisibility) }, child: Padding( padding: const EdgeInsets.all(8.0), child: Container( decoration: const BoxDecoration( borderRadius: BorderRadius.all( Radius.circular(30), ), color: CustomColors.lightGrey), height: tileHeight, width: double.infinity, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const Padding( padding: EdgeInsets.only(left: 36), child: Text( 'Question 1', style: TextStyle(fontWeight: FontWeight.w400, fontSize: 16), ), ), Padding( padding: const EdgeInsets.only(right: 36), child: Icon(questionFirstVisibility ? Icons.keyboard_arrow_down : Icons.keyboard_arrow_up), ), ], ), ), ), ), questionFirstVisibility ? Padding( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), child: Container( decoration: const BoxDecoration( borderRadius: BorderRadius.all( Radius.circular(30), ), color: CustomColors.lightGrey), child: const Padding( padding: EdgeInsets.symmetric(horizontal: 20, vertical: 15), child: Text( style: TextStyle( fontSize: 14.0, fontWeight: FontWeight.w400, height: 2.1 //You can set your custom height here ), Strings.answer, ), ), ), ) : const SizedBox(), GestureDetector( onTap: () => { setState(() => questionSecondVisibility = !questionSecondVisibility) }, child: Padding( padding: const EdgeInsets.all(8.0), child: Container( decoration: const BoxDecoration( borderRadius: BorderRadius.all( Radius.circular(30), ), color: CustomColors.lightGrey), height: tileHeight, width: double.infinity, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const Padding( padding: EdgeInsets.only(left: 36), child: Text( 'Question 2', style: TextStyle(fontWeight: FontWeight.w400, fontSize: 16), ), ), Padding( padding: const EdgeInsets.only(right: 36), child: Icon(questionSecondVisibility ? Icons.keyboard_arrow_down : Icons.keyboard_arrow_up), ), ], ), ), ), ), questionSecondVisibility ? Padding( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), child: Container( decoration: const BoxDecoration( borderRadius: BorderRadius.all( Radius.circular(30), ), color: CustomColors.lightGrey), child: const Padding( padding: EdgeInsets.symmetric(horizontal: 20, vertical: 15), child: Text( style: TextStyle( fontSize: 14.0, fontWeight: FontWeight.w400, height: 2.1 //You can set your custom height here ), Strings.answer, ), ), ), ) : const SizedBox(), GestureDetector( onTap: () => { setState(() => questionThirdVisibility = !questionThirdVisibility) }, child: Padding( padding: const EdgeInsets.all(8.0), child: Container( decoration: const BoxDecoration( borderRadius: BorderRadius.all( Radius.circular(30), ), color: CustomColors.lightGrey), height: tileHeight, width: double.infinity, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const Padding( padding: EdgeInsets.only(left: 36), child: Text( 'Question 3', style: TextStyle(fontWeight: FontWeight.w400, fontSize: 16), ), ), Padding( padding: const EdgeInsets.only(right: 36), child: Icon(questionThirdVisibility ? Icons.keyboard_arrow_down : Icons.keyboard_arrow_up), ), ], ), ), ), ), questionThirdVisibility ? Padding( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), child: Container( decoration: const BoxDecoration( borderRadius: BorderRadius.all( Radius.circular(30), ), color: CustomColors.lightGrey), child: const Padding( padding: EdgeInsets.symmetric(horizontal: 20, vertical: 15), child: Text( style: TextStyle( fontSize: 14.0, fontWeight: FontWeight.w400, height: 2.1 //You can set your custom height here ), Strings.answer, ), ), ), ) : const SizedBox(), GestureDetector( onTap: () => { setState(() => questionFourthVisibility = !questionFourthVisibility) }, child: Padding( padding: const EdgeInsets.all(8.0), child: Container( decoration: const BoxDecoration( borderRadius: BorderRadius.all( Radius.circular(30), ), color: CustomColors.lightGrey), height: tileHeight, width: double.infinity, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const Padding( padding: EdgeInsets.only(left: 36), child: Text( 'Question 4', style: TextStyle(fontWeight: FontWeight.w400, fontSize: 16), ), ), Padding( padding: const EdgeInsets.only(right: 36), child: Icon(questionFourthVisibility ? Icons.keyboard_arrow_down : Icons.keyboard_arrow_up), ), ], ), ), ), ), questionFourthVisibility ? Padding( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), child: Container( decoration: const BoxDecoration( borderRadius: BorderRadius.all( Radius.circular(30), ), color: CustomColors.lightGrey), child: const Padding( padding: EdgeInsets.symmetric(horizontal: 20, vertical: 15), child: Text( style: TextStyle( fontSize: 14.0, fontWeight: FontWeight.w400, height: 2.1 //You can set your custom height here ), Strings.answer, ), ), ), ) : const SizedBox(), SizedBox( height: tileHeight * 2, ), Container( alignment: Alignment.center, height: tileHeight * 1.5, color: CustomColors.lightGrey, child: Text( 'Vitalii - ${Utils.getCurrentYear()}', style: const TextStyle(fontWeight: FontWeight.w400, fontSize: 16), ), ) ], ); } }
0
mirrored_repositories/SKWeatherApp/lib/ui
mirrored_repositories/SKWeatherApp/lib/ui/widgets/cities_widget.dart
import 'package:flutter/material.dart'; import 'package:weather_app/helpers/strings.dart'; import 'city_card.dart'; class CitiesGrid extends StatelessWidget { const CitiesGrid({ Key? key, required this.onNewYorkPress, required this.onParisPress, required this.onDubaiPress, required this.onLondonPress, }) : super(key: key); final VoidCallback onNewYorkPress; final VoidCallback onLondonPress; final VoidCallback onDubaiPress; final VoidCallback onParisPress; @override Widget build(BuildContext context) { final double cardHeight = MediaQuery.of(context).size.height / 3; return Column( children: [ const SizedBox(height: 70), const Padding( padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8), child: Text( Strings.popularcitiesTitle, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 26), ), ), const SizedBox(height: 35), CityCard( cardHeight: cardHeight, cityImg: 'assets/images/bg_nyc.jpg', cityName: 'New York', onCityTap: onNewYorkPress), CityCard( cardHeight: cardHeight, cityImg: 'assets/images/bg_london.jpg', cityName: 'London', onCityTap: onLondonPress), CityCard( cardHeight: cardHeight, cityImg: 'assets/images/bg_dubai.jpg', cityName: 'Dubai', onCityTap: onDubaiPress), CityCard( cardHeight: cardHeight, cityImg: 'assets/images/bg_paris.jpg', cityName: 'Paris', onCityTap: onParisPress), ], ); } }
0
mirrored_repositories/SKWeatherApp/lib/ui
mirrored_repositories/SKWeatherApp/lib/ui/widgets/city_card.dart
import 'package:flutter/material.dart'; class CityCard extends StatelessWidget { const CityCard({ Key? key, required this.onCityTap, required this.cardHeight, required this.cityName, required this.cityImg, }) : super(key: key); final VoidCallback onCityTap; final double cardHeight; final String cityName; final String cityImg; @override Widget build(BuildContext context) { return GestureDetector( onTap: onCityTap, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), child: Stack( alignment: AlignmentDirectional.bottomCenter, children: [ Container( height: cardHeight, decoration: BoxDecoration( borderRadius: const BorderRadius.all(Radius.circular(30)), image: DecorationImage( image: AssetImage(cityImg), fit: BoxFit.cover, ), ), ), Padding( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 14), child: Container( alignment: Alignment.center, decoration: const BoxDecoration( borderRadius: BorderRadius.all( Radius.circular(30), ), color: Colors.white), height: cardHeight / 6, child: Text( cityName, style: const TextStyle( fontWeight: FontWeight.w400, fontSize: 16), ), ), ) ], ), ), ); } }
0
mirrored_repositories/SKWeatherApp/lib/ui
mirrored_repositories/SKWeatherApp/lib/ui/appbar/simple_custom_app_bar.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:weather_app/api/weather_api.dart'; import 'package:weather_app/bloc/suggestion_cities/suggestion_cities_cubit.dart'; import 'package:weather_app/helpers/strings.dart'; import 'package:weather_app/helpers/utils.dart'; import '../../bloc/suggestions_popup/suggestions_popup_cubit.dart'; class SimpleCustomAppBar extends StatefulWidget { const SimpleCustomAppBar({super.key}); @override State<SimpleCustomAppBar> createState() => _SimpleCustomAppBarState(); } class _SimpleCustomAppBarState extends State<SimpleCustomAppBar> { late final TextEditingController _controller; late final WeatherApi _weatherApi; @override void initState() { _controller = TextEditingController(); _weatherApi = WeatherApi(); super.initState(); } @override Widget build(BuildContext context) { var uiCubit = context.read<SuggestionsCubit>(); var cubitSuggestion = context.read<CitySuggestionCubit>(); return Column( children: [ Padding( padding: const EdgeInsets.all(16), child: Container( decoration: const BoxDecoration( color: Colors.white, borderRadius: BorderRadius.all( Radius.circular(30), ), ), height: 60, child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Expanded( child: Padding( padding: const EdgeInsets.only(left: 12), child: TextField( onSubmitted: (value) { searchData(uiCubit, cubitSuggestion, _weatherApi, _controller.text); }, textInputAction: TextInputAction.search, controller: _controller, decoration: const InputDecoration( hintText: Strings.searchBarHint, ), ), ), ), Padding( padding: const EdgeInsets.only(right: 8), child: SizedBox( width: 44, height: 44, child: RawMaterialButton( elevation: 0, onPressed: () { if (_controller.text.isNotEmpty) { searchData(uiCubit, cubitSuggestion, _weatherApi, _controller.text); } }, fillColor: Utils.isDayTime() ? Colors.lightBlue : Colors.blueGrey, shape: const CircleBorder(), child: const Icon( color: Colors.white, Icons.search_rounded, size: 30.0, ), ), ), ), ], ), ), ), ], ); } void searchData(SuggestionsCubit uiCubit, CitySuggestionCubit cubitSuggestion, WeatherApi weatherApi, String textFromController) { weatherApi.getCitySuggestion(textFromController).then((value) { uiCubit.changeSuggestionState(true); cubitSuggestion.setWeather(value); }); } @override void dispose() { _controller.dispose(); super.dispose(); } }
0
mirrored_repositories/SKWeatherApp/lib/ui
mirrored_repositories/SKWeatherApp/lib/ui/theme/app_theme.dart
import 'package:flutter/material.dart'; import '../../helpers/custom_colors.dart'; class AppTheme { static final dark = ThemeData( inputDecorationTheme: const InputDecorationTheme( filled: true, fillColor: Colors.white, hintStyle: TextStyle(color: CustomColors.hintGrey), border: InputBorder.none, ), scaffoldBackgroundColor: Colors.white); }
0
mirrored_repositories/SKWeatherApp/lib/ui
mirrored_repositories/SKWeatherApp/lib/ui/screens/main_screen.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:weather_app/ui/appbar/simple_custom_app_bar.dart'; import 'package:weather_app/bloc/suggestions_popup/suggestions_popup_cubit.dart'; import 'package:weather_app/bloc/suggestions_popup/suggestions_popup_state.dart'; import 'package:weather_app/bloc/weather_info/weather_info_cubit.dart'; import 'package:weather_app/bloc/weather_info/weather_info_state.dart'; import 'package:weather_app/helpers/custom_colors.dart'; import 'package:weather_app/helpers/strings.dart'; import 'package:weather_app/ui/widgets/faq_widget.dart'; import '../../bloc/suggestion_cities/suggestion_cities_cubit.dart'; import '../../bloc/suggestion_cities/suggestion_cities_state.dart'; import '../../helpers/utils.dart'; import '../widgets/cities_widget.dart'; class MainScreen extends StatelessWidget { MainScreen({super.key}); final ScrollController _scrollController = ScrollController(); @override Widget build(BuildContext context) { var cubit = context.read<WeatherCubit>(); var uiCubit = context.read<SuggestionsCubit>(); var cubitSuggestion = context.read<CitySuggestionCubit>(); double screenHeight = MediaQuery.of(context).size.height; double tileHeight = screenHeight / 12; return Scaffold( body: SingleChildScrollView( controller: _scrollController, child: Column( children: [ Container( decoration: BoxDecoration( image: Utils.isDayTime() ? const DecorationImage( image: AssetImage("assets/images/bg_hero_day.jpg"), fit: BoxFit.cover, ) : const DecorationImage( image: AssetImage("assets/images/bg_hero_night.jpg"), fit: BoxFit.cover, ), ), height: screenHeight, child: Stack( children: [ Align( alignment: Alignment.topCenter, child: Padding( padding: EdgeInsets.only(top: tileHeight * 2), child: const SimpleCustomAppBar(), ), ), BlocBuilder<WeatherCubit, WeatherState>( builder: (context, state) { if (state is WeatherLoadedState) { return weatherCardFull(tileHeight, state); } if (state is WeatherErrorState) { return weatherCardError(tileHeight); } if (state is WeatherLoadingState) { return weatherCardLoading(tileHeight); } else { return weatherCardUnknownState(tileHeight); } }, ), StreamBuilder<SuggestionsState>( stream: uiCubit.stream, initialData: uiCubit.state, builder: (context, snapshot) { return suggestionBox( uiCubit, tileHeight, cubitSuggestion, cubit); }, ), ], ), ), CitiesGrid( onDubaiPress: () => { cubit.getWeatherByName('Dubai'), animateToTop(_scrollController) }, onLondonPress: () => { cubit.getWeatherByName('London'), animateToTop(_scrollController) }, onNewYorkPress: () => { cubit.getWeatherByName('New York'), animateToTop(_scrollController) }, onParisPress: () => { cubit.getWeatherByName('Paris'), animateToTop(_scrollController) }, ), const FaqScreen(), ], ), ), ); } Widget suggestionBox(SuggestionsCubit uiCubit, double tileHeight, CitySuggestionCubit cubitSuggestion, WeatherCubit cubit) { return Align( alignment: Alignment.topCenter, child: uiCubit.state.showSuggstion ? Padding( padding: EdgeInsets.only(top: tileHeight * 3), child: BlocBuilder<CitySuggestionCubit, CitySuggestionState>( builder: (context, state) { if (state is CitySuggestionLoadedState) { return Column( mainAxisSize: MainAxisSize.max, children: [ Padding( padding: const EdgeInsets.fromLTRB(16, 20, 16, 0), child: Container( decoration: const BoxDecoration( color: Colors.white, borderRadius: BorderRadius.all( Radius.circular(30), ), ), // height: 100, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 20), child: ListView.builder( shrinkWrap: true, itemCount: state.cityListModel.length, itemBuilder: (context, index) { return InkWell( onTap: () => { FocusManager.instance.primaryFocus ?.unfocus(), cubit.getWeatherById( state.cityListModel[index].id .toString(), ), uiCubit.changeSuggestionState( !uiCubit.state.showSuggstion) }, child: SizedBox( height: 40, child: Text( '${state.cityListModel[index].name}, ${state.cityListModel[index].sys.country}'), ), ); }), ), ), ), ], ); } if (state is CitySuggestionErrorState) { return Padding( padding: const EdgeInsets.fromLTRB(16, 20, 16, 0), child: Container( decoration: const BoxDecoration( color: Colors.white, borderRadius: BorderRadius.all( Radius.circular(30), ), ), height: 100, child: const Center( child: Text(Strings.cityNotFoundHint), ), ), ); } else { return Container(height: 100, color: Colors.blue); } }, ), ) : Container(), ); } Widget weatherCardUnknownState(double tileHeight) { return Padding( padding: EdgeInsets.only(top: tileHeight * 4.5, right: 16, left: 16), child: Container( height: tileHeight * 4.7, decoration: const BoxDecoration( color: CustomColors.transparentWhite, borderRadius: BorderRadius.all( Radius.circular(30), ), ), child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: const [ Icon(Icons.sentiment_very_dissatisfied_rounded), SizedBox(height: 10), Text('Something went completely wrong') ], ), ), ), ); } Widget weatherCardLoading(double tileHeight) { return Padding( padding: EdgeInsets.only(top: tileHeight * 4.5, right: 16, left: 16), child: Container( height: tileHeight * 4.6, decoration: const BoxDecoration( color: CustomColors.transparentWhite, borderRadius: BorderRadius.all( Radius.circular(30), ), ), child: const Center( child: CircularProgressIndicator(), ), ), ); } Widget weatherCardError(double tileHeight) { return Padding( padding: EdgeInsets.only(top: tileHeight * 4.5, right: 16, left: 16), child: Container( height: tileHeight * 4.6, decoration: const BoxDecoration( color: CustomColors.transparentWhite, borderRadius: BorderRadius.all( Radius.circular(30), ), ), child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: const [ Icon(Icons.sentiment_very_dissatisfied_rounded), SizedBox(height: 10), Text('Something went wrong') ], ), ), ), ); } Widget weatherCardFull(double tileHeight, WeatherLoadedState state) { return Padding( padding: EdgeInsets.only(top: tileHeight * 2.5), child: Align( alignment: Alignment.center, child: Padding( padding: const EdgeInsets.all(16.0), child: Container( decoration: const BoxDecoration( color: CustomColors.transparentWhite, borderRadius: BorderRadius.all( Radius.circular(30), ), ), child: Padding( padding: const EdgeInsets.all(20.0), child: SizedBox( child: Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Container( decoration: const BoxDecoration( color: Colors.white, borderRadius: BorderRadius.all( Radius.circular(30), ), ), width: 100, height: 100, child: Image.network( fit: BoxFit.fill, 'http://openweathermap.org/img/w/${state.cityWeatherModel.weather[0].icon}.png'), ), const SizedBox(width: 20), Expanded( flex: 2, child: SizedBox( height: 100, child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Text( '${state.cityWeatherModel.main.temp.toInt()}℃', style: const TextStyle( fontSize: 18, fontWeight: FontWeight.w500), ), Text( state.cityWeatherModel.weather[0].main, style: const TextStyle( fontSize: 16, fontWeight: FontWeight.w400), ), Text( state.cityWeatherModel.weather[0].description, style: const TextStyle( fontSize: 16, color: CustomColors.hintGrey, ), ), ], ), ), ), ], ), Padding( padding: const EdgeInsets.symmetric(vertical: 24), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( '${state.cityWeatherModel.name}, ${state.cityWeatherModel.sys.country}', style: const TextStyle( fontWeight: FontWeight.w500, fontSize: 18), ), Text( Utils.unixToDate(state.cityWeatherModel.dt), style: const TextStyle( color: CustomColors.hintGrey, fontWeight: FontWeight.w400, fontSize: 16), ) ], ), ), const Divider( color: Colors.blue, ), Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Column( children: [ const Padding( padding: EdgeInsets.only(bottom: 6), child: Text( 'Min', style: TextStyle( color: CustomColors.hintGrey, fontWeight: FontWeight.w400, fontSize: 16), ), ), Padding( padding: const EdgeInsets.only(top: 6), child: Text( '${state.cityWeatherModel.main.tempMin.toInt()}℃', style: const TextStyle( fontWeight: FontWeight.w500, fontSize: 18), ), ) ], ), Container( width: 0.6, height: 60, color: Colors.blue, ), Padding( padding: const EdgeInsets.symmetric(vertical: 16), child: Column( children: [ const Padding( padding: EdgeInsets.only(bottom: 6), child: Text( 'Max', style: TextStyle( color: CustomColors.hintGrey, fontWeight: FontWeight.w400, fontSize: 16), ), ), Padding( padding: const EdgeInsets.only(top: 6), child: Text( '${state.cityWeatherModel.main.tempMax.toInt()}℃', style: const TextStyle( fontWeight: FontWeight.w500, fontSize: 18), ), ) ], ), ) ], ), ], ), ), ), ), ), ), ); } void animateToTop(ScrollController controller) { controller.animateTo(_scrollController.position.minScrollExtent, duration: const Duration(milliseconds: 500), curve: Curves.ease); } }
0
mirrored_repositories/rick_and_morty_flutter
mirrored_repositories/rick_and_morty_flutter/lib/main.dart
import 'package:animated_splash_screen/animated_splash_screen.dart'; import 'package:flutter/material.dart'; import 'package:rick_and_morty/Screens/HomeScreen.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; void main() => runApp(MaterialApp( theme: ThemeData.dark(), debugShowCheckedModeBanner: false, home: AnimatedSplashScreen( splash: Center( child: SpinKitDoubleBounce( color: Colors.black, size: 125, ), ), backgroundColor: Colors.white, duration: 1400, nextScreen: HomeScreen(), ), ));
0
mirrored_repositories/rick_and_morty_flutter/lib
mirrored_repositories/rick_and_morty_flutter/lib/Utils/colors.dart
import 'package:flutter/material.dart'; Color navItemColor = Colors.black; Color pageColor = Colors.white; Color cardColor = Color(0XFF593c8f);
0
mirrored_repositories/rick_and_morty_flutter/lib
mirrored_repositories/rick_and_morty_flutter/lib/Screens/Location.dart
import 'dart:convert'; import 'package:connectivity/connectivity.dart'; import 'package:flutter/material.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:http/http.dart' as http; import 'package:rick_and_morty/Utils/colors.dart'; class Location extends StatefulWidget { @override _LocationState createState() => _LocationState(); } class _LocationState extends State<Location> { List location = []; bool loading = false; static int pageCount = 1; String webURL = "https://rickandmortyapi.com/api/location/?page=$pageCount"; ScrollController _controller; var refreshkey = GlobalKey<RefreshIndicatorState>(); int checkCount(pageCount) { return pageCount <= 0 ? pageCount = 1 : pageCount; } @override void initState() { _controller = ScrollController(); super.initState(); this.checkConnectivity(); } checkConnectivity() async { var connectivityResult = await (Connectivity().checkConnectivity()); if ((connectivityResult == ConnectivityResult.mobile) || (connectivityResult == ConnectivityResult.wifi)) this.fetchLocation(this.webURL); else showDialog( context: context, builder: (BuildContext context) { return AlertDialog( backgroundColor: Colors.white, elevation: 50, title: Text( "No internet connectivity 🤦‍♂️", textAlign: TextAlign.center, style: TextStyle( color: Colors.black, fontFamily: 'Nunito', fontWeight: FontWeight.bold), ), content: Text( "Please connect the device to internet.", textAlign: TextAlign.center, style: TextStyle(color: Colors.black, fontFamily: 'Nunito'), ), ); }); } fetchLocation(url) async { setState(() { loading = true; }); var response = await http.get(url); if (response.statusCode == 200) { var data = json.decode(response.body)['results']; setState(() { location = data; loading = false; }); } else { loading = false; location = []; } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.transparent, centerTitle: true, elevation: 0, title: Text( 'Location', style: TextStyle( color: Colors.black, fontWeight: FontWeight.bold, fontFamily: 'Nunito'), ), ), backgroundColor: pageColor, body: locationBody(), floatingActionButton: Column( mainAxisAlignment: MainAxisAlignment.end, children: [ FloatingActionButton( onPressed: refreshlist, backgroundColor: Colors.black, heroTag: null, child: new Icon( Icons.refresh_outlined, color: Colors.white, )), SizedBox( height: 20, ), FloatingActionButton( onPressed: () { if (_controller.offset <= _controller.position.minScrollExtent && !_controller.position.outOfRange) { setState(() { pageCount = this.checkCount(pageCount); pageCount--; fetchLocation( "https://rickandmortyapi.com/api/location/?page=$pageCount"); }); } }, heroTag: null, backgroundColor: Colors.black, child: new Icon( Icons.arrow_left, color: Colors.white, )), SizedBox( height: 20, ), FloatingActionButton( onPressed: () { if (_controller.offset <= _controller.position.minScrollExtent && !_controller.position.outOfRange) { setState(() { pageCount = this.checkCount(pageCount); pageCount++; fetchLocation( "https://rickandmortyapi.com/api/location/?page=$pageCount"); }); } }, heroTag: null, backgroundColor: Colors.black, child: new Icon( Icons.arrow_right, color: Colors.white, )), ], ), ); } Future<Null> refreshlist() async { refreshkey.currentState?.show(atTop: true); await Future.delayed( Duration(seconds: 0.5.toInt())); //wait here for 2 second setState(() { this.fetchLocation(webURL); pageCount = 1; }); } Widget locationBody() { if (location.contains(null) || location.length < 0 || loading) { return Center( child: SpinKitDoubleBounce( color: Colors.black, size: 125, ), ); } return SafeArea( child: RefreshIndicator( child: ListView.builder( controller: _controller, itemCount: location.length, itemBuilder: (context, index) { return locationCard(location[index]); }), onRefresh: refreshlist, ), ); } Widget locationCard(index) { var name = index['name']; var type = index['type']; var dimension = index['dimension']; List residents = index['residents']; return Padding( padding: const EdgeInsets.all(15.0), child: Card( elevation: 15, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(25.0), ), color: cardColor, child: Container( margin: EdgeInsets.all(20.0), height: 155.0, child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ Expanded( child: Text(name, style: TextStyle( fontSize: 25, color: Colors.white, fontWeight: FontWeight.bold, letterSpacing: 2, fontFamily: 'Nunito')), ), SizedBox( height: 20.0, ), Column( children: [ Row(children: [ Text("Type\t:\t", style: TextStyle( fontSize: 20, color: Colors.white, fontFamily: 'Nunito')), Text(type, style: TextStyle( fontSize: 20, color: Colors.white, fontWeight: FontWeight.bold, fontFamily: 'Nunito')), ]), SizedBox( height: 10, ), Row(children: [ Text("Dimension\t:\t", style: TextStyle( fontSize: 20, color: Colors.white, fontFamily: 'Nunito')), Expanded( child: Text(dimension, style: TextStyle( fontSize: 20, color: Colors.white, fontWeight: FontWeight.bold, fontFamily: 'Nunito')), ), ]), SizedBox( height: 10, ), Row(children: [ Text("Residents count\t:\t", style: TextStyle( fontSize: 20, color: Colors.white, fontFamily: 'Nunito')), Text(residents.length.toString(), style: TextStyle( fontSize: 20, color: Colors.white, fontWeight: FontWeight.bold, fontFamily: 'Nunito')), ]), ], ) ], ), )), ); } }
0
mirrored_repositories/rick_and_morty_flutter/lib
mirrored_repositories/rick_and_morty_flutter/lib/Screens/Characters.dart
import 'dart:convert'; import 'package:connectivity/connectivity.dart'; import 'package:flutter/material.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:http/http.dart' as http; import 'package:expansion_card/expansion_card.dart'; import 'package:rick_and_morty/Utils/colors.dart'; class Character extends StatefulWidget { @override _CharacterState createState() => _CharacterState(); } class _CharacterState extends State<Character> { List characters = []; bool loading = false; static int pageCount = 0; String webURL = "https://rickandmortyapi.com/api/character/?page=$pageCount"; ScrollController _controller; var refreshkey = GlobalKey<RefreshIndicatorState>(); int checkCount(pageCount) { return pageCount <= 0 ? pageCount = 1 : pageCount; } @override void initState() { _controller = ScrollController(); checkConnectivity(); super.initState(); } checkConnectivity() async { var connectivityResult = await (Connectivity().checkConnectivity()); if ((connectivityResult == ConnectivityResult.mobile) || (connectivityResult == ConnectivityResult.wifi)) this.fetchCharacter(this.webURL); else showDialog( context: context, builder: (BuildContext context) { return AlertDialog( backgroundColor: Colors.white, elevation: 50, title: Text( "No internet connectivity 🤦‍♂️", textAlign: TextAlign.center, style: TextStyle( color: Colors.black, fontFamily: 'Nunito', fontWeight: FontWeight.bold), ), content: Text( "Please connect the device to internet.", textAlign: TextAlign.center, style: TextStyle(color: Colors.black, fontFamily: 'Nunito'), ), ); }); } fetchCharacter(url) async { setState(() { loading = true; }); var response = await http.get(url); if (response.statusCode == 200) { var data = json.decode(response.body)['results']; setState(() { characters = data; loading = false; }); } else { print("Error"); characters = []; loading = false; } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.transparent, centerTitle: true, elevation: 0, title: Text( 'Characters', style: TextStyle( color: Colors.black, fontWeight: FontWeight.bold, fontFamily: 'Nunito'), ), ), backgroundColor: pageColor, body: characterBody(), floatingActionButton: Column( mainAxisAlignment: MainAxisAlignment.end, children: [ FloatingActionButton( onPressed: refreshlist, backgroundColor: Colors.black, heroTag: null, child: new Icon( Icons.refresh_outlined, color: Colors.white, )), SizedBox( height: 20, ), FloatingActionButton( onPressed: () { if (_controller.offset <= _controller.position.minScrollExtent && !_controller.position.outOfRange) { setState(() { pageCount = this.checkCount(pageCount); pageCount--; fetchCharacter( "https://rickandmortyapi.com/api/character/?page=$pageCount"); }); } }, heroTag: null, backgroundColor: Colors.black, child: new Icon( Icons.arrow_left, color: Colors.white, )), SizedBox( height: 20, ), FloatingActionButton( onPressed: () { if (_controller.offset <= _controller.position.minScrollExtent && !_controller.position.outOfRange) { setState(() { pageCount = this.checkCount(pageCount); pageCount++; fetchCharacter( "https://rickandmortyapi.com/api/character/?page=$pageCount"); }); } }, heroTag: null, backgroundColor: Colors.black, child: new Icon( Icons.arrow_right, color: Colors.white, )), ], ), ); } Future<Null> refreshlist() async { refreshkey.currentState?.show(atTop: true); await Future.delayed( Duration(seconds: 0.5.toInt())); //wait here for 2 second setState(() { this.fetchCharacter(webURL); pageCount = 1; }); } Widget characterBody() { if (characters.contains(null) || characters.length < 0 || loading) { return Center( child: SpinKitDoubleBounce( color: Colors.black, size: 125, ), ); } return RefreshIndicator( child: ListView.builder( controller: _controller, itemCount: characters.length, itemBuilder: (context, index) { return characterCard(characters[index]); }, ), onRefresh: refreshlist, ); } Widget characterCard(index) { var name = index['name']; var imageURL = index['image']; var status = index['status']; var species = index['species']; var gender = index['gender']; var location = index['origin']['name']; List episodes = index['episode']; return Container( child: ExpansionCard( backgroundColor: pageColor, borderRadius: 20, title: Container( child: Row( children: <Widget>[ Container( width: 100, height: 100, decoration: BoxDecoration( color: Colors.white10, borderRadius: BorderRadius.horizontal( left: Radius.elliptical(15, 15), right: Radius.elliptical(15, 15)), image: DecorationImage( fit: BoxFit.fill, image: NetworkImage(imageURL), )), ), SizedBox( width: 20, ), Expanded( child: Text( name, style: TextStyle( fontSize: 25, fontWeight: FontWeight.bold, fontFamily: 'Nunito', color: Colors.black, letterSpacing: 1.5), ), ), ], ), ), children: <Widget>[ Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ Row( children: [ Container( margin: EdgeInsets.only(left: 140), child: Text("Status \t:\t", style: TextStyle( fontSize: 20, color: Colors.black, fontFamily: 'Nunito')), ), Container( child: Text(status, style: TextStyle( fontSize: 20, color: Colors.black, fontWeight: FontWeight.bold, fontFamily: 'Nunito')), ), ], ), Row( children: [ Container( margin: EdgeInsets.only(left: 140), child: Text("Species \t:\t", style: TextStyle( fontSize: 20, color: Colors.black, fontFamily: 'Nunito')), ), Container( child: Expanded( child: Text(species, style: TextStyle( fontSize: 20, color: Colors.black, fontWeight: FontWeight.bold, fontFamily: 'Nunito')), ), ), ], ), Row( children: [ Container( margin: EdgeInsets.only(left: 140), child: Text("Gender \t:\t", style: TextStyle( fontSize: 20, color: Colors.black, fontFamily: 'Nunito')), ), Container( child: Text(gender, style: TextStyle( fontSize: 20, color: Colors.black, fontWeight: FontWeight.bold, fontFamily: 'Nunito')), ), ], ), Row( children: [ Container( margin: EdgeInsets.only(left: 140), child: Text("Location \t:\t", style: TextStyle( fontSize: 20, color: Colors.black, fontFamily: 'Nunito')), ), Container( child: Expanded( child: Text(location, style: TextStyle( fontSize: 20, color: Colors.black, fontWeight: FontWeight.bold, fontFamily: 'Nunito')), ), ), ], ), Row( children: [ Container( margin: EdgeInsets.only(left: 140), child: Text("Total Episodes \t:\t", style: TextStyle( fontSize: 20, color: Colors.black, fontFamily: 'Nunito')), ), Container( child: Text(episodes.length.toString(), style: TextStyle( fontSize: 20, color: Colors.black, fontWeight: FontWeight.bold, fontFamily: 'Nunito')), ), ], ) ], ) ], ), ); } }
0
mirrored_repositories/rick_and_morty_flutter/lib
mirrored_repositories/rick_and_morty_flutter/lib/Screens/Episodes.dart
import 'dart:convert'; import 'package:connectivity/connectivity.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:http/http.dart' as http; import 'package:rick_and_morty/Utils/colors.dart'; class Episodes extends StatefulWidget { @override _EpisodesState createState() => _EpisodesState(); } class _EpisodesState extends State<Episodes> { List episodes = []; bool loading = false; static int pageCount = 1; ScrollController _controller; String webURL = "https://rickandmortyapi.com/api/episode?page=$pageCount"; var refreshkey = GlobalKey<RefreshIndicatorState>(); int checkCount(pageCount) { return pageCount <= 0 ? pageCount = 1 : pageCount; } @override void initState() { _controller = ScrollController(); super.initState(); this.checkConnectivity(); } checkConnectivity() async { var connectivityResult = await (Connectivity().checkConnectivity()); if ((connectivityResult == ConnectivityResult.mobile) || (connectivityResult == ConnectivityResult.wifi)) this.fetchEpisodes(this.webURL); else showDialog( context: context, builder: (BuildContext context) { return AlertDialog( backgroundColor: Colors.white, elevation: 50, title: Text( "No internet connectivity 🤦‍♂️", textAlign: TextAlign.center, style: TextStyle( color: Colors.black, fontFamily: 'Nunito', fontWeight: FontWeight.bold), ), content: Text( "Please connect the device to internet.", textAlign: TextAlign.center, style: TextStyle(color: Colors.black, fontFamily: 'Nunito'), ), ); }); } fetchEpisodes(url) async { setState(() { loading = true; }); var response = await http.get(url); if (response.statusCode == 200) { var data = json.decode(response.body)['results']; setState(() { loading = false; episodes = data; }); } else { loading = true; episodes = []; } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.transparent, centerTitle: true, elevation: 0, title: Text( 'Episodes', style: TextStyle( color: Colors.black, fontWeight: FontWeight.bold, fontFamily: 'Nunito'), ), ), backgroundColor: pageColor, body: episodeBody(), floatingActionButton: Column( mainAxisAlignment: MainAxisAlignment.end, children: [ FloatingActionButton( onPressed: refreshlist, backgroundColor: Colors.black, heroTag: null, child: new Icon( Icons.refresh_outlined, color: Colors.white, )), SizedBox( height: 20, ), FloatingActionButton( onPressed: () { if (_controller.offset <= _controller.position.minScrollExtent && !_controller.position.outOfRange) { setState(() { pageCount = this.checkCount(pageCount); pageCount--; fetchEpisodes( "https://rickandmortyapi.com/api/episode/?page=$pageCount"); }); } }, heroTag: null, backgroundColor: Colors.black, child: new Icon( Icons.arrow_left, color: Colors.white, )), SizedBox( height: 20, ), FloatingActionButton( onPressed: () { if (_controller.offset <= _controller.position.minScrollExtent && !_controller.position.outOfRange) { setState(() { pageCount = this.checkCount(pageCount); pageCount++; fetchEpisodes( "https://rickandmortyapi.com/api/episode/?page=$pageCount"); }); } }, heroTag: null, backgroundColor: Colors.black, child: new Icon( Icons.arrow_right, color: Colors.white, )), ], ), ); } Future<Null> refreshlist() async { refreshkey.currentState?.show(atTop: true); await Future.delayed( Duration(seconds: 0.5.toInt())); //wait here for 2 second setState(() { this.fetchEpisodes(webURL); pageCount = 1; }); } Widget episodeBody() { if (episodes.contains(null) || episodes.length < 0 || loading) { return Center( child: SpinKitDoubleBounce( color: Colors.black, size: 125, ), ); } return SafeArea( child: RefreshIndicator( child: ListView.builder( controller: _controller, itemCount: episodes.length, itemBuilder: (context, index) { return episodeCard(episodes[index]); }), onRefresh: refreshlist, ), ); } Widget episodeCard(index) { var name = index['name']; var airDate = index['air_date']; var episode = index['episode']; List characters = index['characters']; return Padding( padding: const EdgeInsets.all(15.0), child: Card( elevation: 15, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(25.0), ), color: cardColor, child: Container( margin: EdgeInsets.all(20.0), height: 155.0, child: Column( children: [ Expanded( child: Text(name, style: TextStyle( fontSize: 20, color: Colors.white, fontWeight: FontWeight.bold, letterSpacing: 2, fontFamily: 'Nunito')), ), SizedBox( height: 20.0, ), Column( // mainAxisAlignment: MainAxisAlignment.center, children: [ Row(children: [ Text("Air Date\t:\t", style: TextStyle( fontSize: 20, color: Colors.white, fontFamily: 'Nunito')), Text(airDate, style: TextStyle( fontSize: 20, color: Colors.white, fontWeight: FontWeight.bold, fontFamily: 'Nunito')), ]), SizedBox( height: 10, ), Row(children: [ Text("Episode\t:\t", style: TextStyle( fontSize: 20, color: Colors.white, fontFamily: 'Nunito')), Expanded( child: Text(episode, style: TextStyle( fontSize: 20, color: Colors.white, fontWeight: FontWeight.bold, fontFamily: 'Nunito')), ), ]), SizedBox( height: 10, ), Row(children: [ Text("Character count\t:\t", style: TextStyle( fontSize: 20, color: Colors.white, fontFamily: 'Nunito')), Text(characters.length.toString(), style: TextStyle( fontSize: 20, color: Colors.white, fontWeight: FontWeight.bold, fontFamily: 'Nunito')), ]), ], ) ], ), )), ); } }
0
mirrored_repositories/rick_and_morty_flutter/lib
mirrored_repositories/rick_and_morty_flutter/lib/Screens/HomeScreen.dart
import 'package:flutter/material.dart'; import 'package:bottom_navy_bar/bottom_navy_bar.dart'; import 'package:rick_and_morty/Screens/About%20Me.dart'; import 'package:rick_and_morty/Screens/Characters.dart'; import 'package:rick_and_morty/Screens/Episodes.dart'; import 'package:rick_and_morty/Screens/Location.dart'; import 'package:rick_and_morty/Utils/colors.dart'; Color c4 = Colors.white; class HomeScreen extends StatefulWidget { @override _HomeScreenState createState() => _HomeScreenState(); } class _HomeScreenState extends State<HomeScreen> { int currentIndex = 0; List colorList = [pageColor, pageColor, pageColor, pageColor]; List screenList = [Character(), Location(), Episodes(), AboutMe()]; @override Widget build(BuildContext context) { return Scaffold( body: screenList[currentIndex], bottomNavigationBar: BottomNavyBar( animationDuration: Duration(milliseconds: 250), backgroundColor: colorList[currentIndex], selectedIndex: currentIndex, showElevation: false, onItemSelected: (index) { setState(() { currentIndex = index; }); }, curve: Curves.easeInOutSine, items: [ BottomNavyBarItem( icon: Icon( Icons.face_outlined, color: navItemColor, size: 30, ), title: Text( 'Characters', style: TextStyle( fontFamily: 'Nunito', ), ), activeColor: navItemColor, ), BottomNavyBarItem( icon: Icon( Icons.location_city_outlined, size: 30, color: navItemColor, ), title: Text( 'Location', style: TextStyle( fontFamily: 'Nunito', ), ), activeColor: navItemColor, ), BottomNavyBarItem( icon: Icon( Icons.play_circle_fill_outlined, size: 30, color: navItemColor, ), title: Text( 'Episodes', style: TextStyle( fontFamily: 'Nunito', ), ), activeColor: navItemColor, ), BottomNavyBarItem( icon: Icon( Icons.account_circle_outlined, size: 30, color: navItemColor, ), title: Text( 'About Me', style: TextStyle( fontFamily: 'Nunito', ), ), activeColor: navItemColor, ) ], ), ); } }
0
mirrored_repositories/rick_and_morty_flutter/lib
mirrored_repositories/rick_and_morty_flutter/lib/Screens/About Me.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:url_launcher/url_launcher.dart'; class AboutMe extends StatelessWidget { _launchGitHub() async { const git = "https://github.com/KathirvelChandrasekaran"; if (await canLaunch(git)) await launch(git); else throw 'Could not launch $git'; } _launchLinkedin() async { const linkedin = "https://www.linkedin.com/in/kathirvel-chandrasekaran/"; if (await canLaunch(linkedin)) await launch(linkedin); else throw 'Could not launch $linkedin'; } _launchSourceCode() async { const git = "https://github.com/KathirvelChandrasekaran/rick_and_morty_flutter"; if (await canLaunch(git)) await launch(git); else throw 'Could not launch $git'; } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, body: SafeArea( child: Center( child: Container( // color: Colors.black, width: MediaQuery.of(context).size.width * 0.65, margin: EdgeInsets.fromLTRB(10, 50, 10, 0), child: Column( children: [ Card( elevation: 18, shape: CircleBorder(), child: CircleAvatar( maxRadius: 75, backgroundImage: AssetImage('images/Me.jpg'), ), ), SizedBox( height: 15.0, ), Text( "Kathirvel Chandrasekaran", textAlign: TextAlign.center, style: TextStyle( fontSize: 30, color: Colors.black, letterSpacing: 2, fontWeight: FontWeight.w400, fontFamily: 'Nunito'), ), SizedBox( height: 15.0, ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ GestureDetector( onTap: _launchGitHub, child: CircleAvatar( maxRadius: 30, backgroundImage: AssetImage('images/github.png'), ), ), SizedBox( width: 25, ), GestureDetector( onTap: _launchLinkedin, child: Image.asset( 'images/linkedin.png', width: 70, ), ), ], ), SizedBox( height: 15.0, ), Divider( color: Colors.black38, ), SizedBox( height: 15.0, ), GestureDetector( onTap: _launchSourceCode, child: Container( child: Container( width: MediaQuery.of(context).size.width * 0.65, height: 70, padding: EdgeInsets.all(20), decoration: BoxDecoration( color: Colors.black, borderRadius: BorderRadius.circular(50)), child: Text( 'Source code', textAlign: TextAlign.center, style: TextStyle( color: Colors.white, fontSize: 20, fontFamily: 'Nunito'), ), ), ), ) ], ), ), )), ); } }
0
mirrored_repositories
mirrored_repositories/BMICalculatorApp/bmi_result_screen.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class BmiResultScreen extends StatelessWidget { final int age; final int result; final bool isMale; BmiResultScreen({ required this.age, required this.result, required this.isMale, }); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( leading: IconButton( onPressed: () { Navigator.pop(context); }, icon: Icon( Icons.keyboard_arrow_left, ), ), title: Text( 'Result', ), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( 'Gender : ${isMale? 'Male':'Female'}', style: TextStyle( fontSize: 25.0, fontWeight: FontWeight.bold, ), ), Text( 'Result : $result', style: TextStyle( fontSize: 25.0, fontWeight: FontWeight.bold, ), ), Text( 'Age : $age', style: TextStyle( fontSize: 25.0, fontWeight: FontWeight.bold, ), ), ], ), ), ); } }
0
mirrored_repositories
mirrored_repositories/BMICalculatorApp/bmi_screen.dart
import 'dart:math'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:untitled/bmi_result_screen.dart'; class BmiScreen extends StatefulWidget { @override State<BmiScreen> createState() => _BmiScreenState(); } class _BmiScreenState extends State<BmiScreen> { bool isMale = true; double height = 120.0; int weight = 40; int age = 20; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text( 'Bmi Calculator', ), ), body: Column( children: [ Expanded( child: Padding( padding: const EdgeInsets.all(20.0), child: Row( children: [ Expanded( child: GestureDetector( onTap: () { setState(() { isMale = true; }); }, child: Container( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Image(image: AssetImage('assets/images/male.png'), height: 90, width: 90, ), SizedBox( height: 15, ), Text( 'MALE', style: TextStyle( fontSize: 25.0, fontWeight: FontWeight.bold, ), ), ], ), decoration: BoxDecoration( borderRadius: BorderRadius.circular(10,), color: isMale? Colors.blue:Colors.grey[400], ), ), ), ), SizedBox( width: 20.0, ), Expanded( child: GestureDetector( onTap: (){ setState(() { isMale = false; }); }, child: Container( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Image(image: AssetImage('assets/images/female.png'), height: 90, width: 90, ), SizedBox( height: 15, ), Text( 'FEMALE', style: TextStyle( fontSize: 25.0, fontWeight: FontWeight.bold, ), ), ], ), decoration: BoxDecoration( borderRadius: BorderRadius.circular(10,), color: isMale? Colors.grey[400]:Colors.blue, ), ), ), ), ], ), ), ), Expanded( child: Padding( padding: const EdgeInsets.symmetric( horizontal: 20.0, ), child: Container( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( 'HEIGHT', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 25.0, ), ), Row( crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, mainAxisAlignment: MainAxisAlignment.center, children: [ Text( '${height.round()}', style: TextStyle( fontWeight: FontWeight.w900, fontSize: 40.0, ), ), SizedBox( width: 5.0, ), Text( 'CM', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 20.0, ), ), ], ), Slider(value: height, max: 220.0, min: 80.0, onChanged: (value){ print(value.round()); setState(() { height = value; }); },), ], ), decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: Colors.grey[400], ), ), ), ), Expanded( child:Padding( padding: const EdgeInsets.all(20.0), child: Row( children: [ Expanded( child: Container( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( 'WEIGHT', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 25.0, ), ), Text( '${weight}', style: TextStyle( fontWeight: FontWeight.w900, fontSize: 40.0, ), ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ FloatingActionButton(onPressed: (){ setState(() { weight--; }); }, mini: true, child: Icon( Icons.remove, ), ), FloatingActionButton(onPressed: (){ setState(() { weight++; }); }, mini: true, child: Icon( Icons.add, ), ), ], ), ], ), decoration: BoxDecoration( borderRadius: BorderRadius.circular(10,), color: Colors.grey[400], ), ), ), SizedBox(width: 20.0,), Expanded( child: Container( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( 'AGE', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 25.0, ), ), Text( '${age}', style: TextStyle( fontWeight: FontWeight.w900, fontSize: 40.0, ), ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ FloatingActionButton(onPressed: (){ setState(() { age--; }); }, mini: true, child: Icon( Icons.remove, ), ), FloatingActionButton(onPressed: (){ setState(() { age++; }); }, mini: true, child: Icon( Icons.add, ), ), ], ), ], ), decoration: BoxDecoration( borderRadius: BorderRadius.circular(10,), color: Colors.grey[400], ), ), ), ], ), ), ), Container( width: double.infinity, color: Colors.blue, height: 50.0, child: MaterialButton( onPressed: (){ var result = weight / pow(height/100, 2); print(result.round()); Navigator.push(context, MaterialPageRoute( builder: (context) => BmiResultScreen( age: age, result: result.round(), isMale: isMale, ), ), ); }, child: Text( 'Calculate', style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 16, ), ), ), ), ], ), ); } }
0
mirrored_repositories
mirrored_repositories/BMICalculatorApp/main.dart
import 'package:flutter/material.dart'; import 'package:untitled/bmi_result_screen.dart'; import 'package:untitled/bmi_screen.dart'; import 'package:untitled/home_screen.dart'; import 'package:untitled/login_screen.dart'; import 'package:untitled/massenger_screen.dart'; import 'package:untitled/users_model.dart'; import 'counter_screen.dart'; void main() { runApp(MyApp()); } // Statless Widget // Statfull Widget // class MyApp class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: BmiScreen(), ); } }
0
mirrored_repositories/Login_Flutter
mirrored_repositories/Login_Flutter/lib/main.dart
import 'package:flutter/material.dart'; import './src/app.dart'; void main () { runApp(App()); }
0
mirrored_repositories/Login_Flutter/lib
mirrored_repositories/Login_Flutter/lib/src/app.dart
import 'package:flutter/material.dart'; import './screens/login_screen.dart'; class App extends StatelessWidget { Widget build (context) { return MaterialApp( title: 'Log Me in!', theme: ThemeData( primaryColor: Colors.black, //Color AppBar accentColor: Colors.white, //Color texto en botones canvasColor: Colors.white, //Fondo de la applicación buttonColor: Colors.grey[600], //Color del fondo de los botones buttonTheme: ButtonThemeData( textTheme: ButtonTextTheme.accent, //Color texto botones ), ), home: Scaffold( appBar: AppBar( title: Text('Login'), ), body: LoginScreen(), ) ); } }
0
mirrored_repositories/Login_Flutter/lib/src
mirrored_repositories/Login_Flutter/lib/src/mixins/validation_mixin.dart
class ValidationMixin { String validateEmail(String value) { if (!value.contains('@')) return 'Please enter a valid email.'; return null; } String validatePassword(String value) { if (value.length < 8) return 'Password is required and must be 8+ characters'; return null; } }
0
mirrored_repositories/Login_Flutter/lib/src
mirrored_repositories/Login_Flutter/lib/src/screens/login_screen.dart
import 'package:flutter/material.dart'; import '../mixins/validation_mixin.dart'; class LoginScreen extends StatefulWidget { createState() { return LoginScreenState(); } } class LoginScreenState extends State<LoginScreen> with ValidationMixin { final formKey = GlobalKey<FormState>(); String email = ''; String password = ''; Widget build(context) { return Container( margin: EdgeInsets.all(15.0), padding: EdgeInsets.all(15.0), child: Form( key: formKey, child: Column( children: <Widget>[ emailField(), passwordField(), Container(margin: EdgeInsets.only(top: 15.0)), submitButton(), ], ), ), ); } Widget emailField() { return TextFormField( keyboardType: TextInputType.emailAddress, decoration: InputDecoration( labelText: 'Email', hintText: '[email protected]', ), validator: validateEmail, //From ValidationMixin onSaved: (String value) { email = value; }, ); } Widget passwordField() { return TextFormField( obscureText: true, //Oculta caracteres decoration: InputDecoration( labelText: 'Password', hintText: 'Password', ), validator: validatePassword, //From ValidationMixin onSaved: (String value) { password = value; }, ); } Widget submitButton() { return RaisedButton( color: Colors.blue, //Especificar un color aquí ignora el color del tema. onPressed: () { if (formKey.currentState.validate()){ formKey.currentState.save(); print('Time to post $email and $password to my API'); } }, child: Text('Done'), ); } }
0
mirrored_repositories/Login_Flutter
mirrored_repositories/Login_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:login_state/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(new 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/Flutter-Instagram-clone-App
mirrored_repositories/Flutter-Instagram-clone-App/lib/main.dart
import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_instagram_app/providers/user_provider.dart'; import 'package:flutter_instagram_app/responsive/mobile_screen_layout.dart'; import 'package:flutter_instagram_app/responsive/responsive_layout_screen.dart'; import 'package:flutter_instagram_app/responsive/web_screen_layout.dart'; import 'package:flutter_instagram_app/screens/login_screen.dart'; import 'package:flutter_instagram_app/utils/colors.dart'; import 'package:flutter_instagram_app/utils/my_theme.dart'; import 'package:provider/provider.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); if (kIsWeb) { await Firebase.initializeApp( options: const FirebaseOptions( apiKey: "AIzaSyAjjqpkYCO_ZzkXID4OpRgUL4s4XkXhPgA", appId: "1:836239946911:web:e90f16959fd98d0b0cdeaa", messagingSenderId: "836239946911", projectId: "flutter-instagram-clone-d402d", storageBucket: "flutter-instagram-clone-d402d.appspot.com"), ); } else { await Firebase.initializeApp(); } runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is the root of your application. @override Widget build(BuildContext context) { return MultiProvider( providers: [ ChangeNotifierProvider<UserProvider>(create: (_) => UserProvider()), ChangeNotifierProvider<ThemeProvider>( create: (context) => ThemeProvider()) ], builder: (context, _) { final themeProvider = Provider.of<ThemeProvider>(context); return MaterialApp( debugShowCheckedModeBanner: false, title: 'Instagram Clone', themeMode: themeProvider.themeMode, theme: MyTheme.lightTheme(), darkTheme: MyTheme.darkTheme(), home: StreamBuilder( stream: FirebaseAuth.instance.authStateChanges(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.active) { if (snapshot.hasData) { return const ResponsiveLayout( webScreenLayout: WebSreenLayout(), mobileScreenLayout: MobileScreenLayout()); } else if (snapshot.hasError) { return Center( child: Text('${snapshot.error}'), ); } } if (snapshot.connectionState == ConnectionState.waiting) { return const Center( child: CircularProgressIndicator( color: primaryColor, ), ); } return const LoginScreen(); }, )); }, ); } }
0
mirrored_repositories/Flutter-Instagram-clone-App/lib
mirrored_repositories/Flutter-Instagram-clone-App/lib/widgets/text_field_input.dart
import 'package:flutter/material.dart'; class TextFieldInput extends StatelessWidget { final TextEditingController textEditingController; final bool isPass; final String hintText; final TextInputType textInputType; const TextFieldInput({ Key? key, required this.textEditingController, this.isPass = false, required this.hintText, required this.textInputType, }) : super(key: key); @override Widget build(BuildContext context) { final inputBorder = OutlineInputBorder( borderSide: Divider.createBorderSide(context) ); return TextField( controller: textEditingController, keyboardType: textInputType, obscureText: isPass, decoration: InputDecoration( hintText: hintText, border: inputBorder, focusedBorder: inputBorder, enabledBorder: inputBorder, filled: true, contentPadding: const EdgeInsets.all(8) ), ); } }
0
mirrored_repositories/Flutter-Instagram-clone-App/lib
mirrored_repositories/Flutter-Instagram-clone-App/lib/widgets/change_theme_button_widget.dart
import 'package:flutter/material.dart'; import 'package:flutter_instagram_app/utils/my_theme.dart'; import 'package:provider/provider.dart'; class ChangeThemeButtonWidget extends StatelessWidget { const ChangeThemeButtonWidget({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final themeProvider = Provider.of<ThemeProvider>(context); return Switch.adaptive( activeColor: Colors.blue, value: themeProvider.isDarkMode, onChanged: (value) { final provider = Provider.of<ThemeProvider>(context, listen: false); provider.toggleTheme(value); }, ); } }
0
mirrored_repositories/Flutter-Instagram-clone-App/lib
mirrored_repositories/Flutter-Instagram-clone-App/lib/widgets/post_card.dart
import 'dart:io'; import 'dart:ui'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:flutter_instagram_app/model/users.dart'; import 'package:flutter_instagram_app/providers/user_provider.dart'; import 'package:flutter_instagram_app/resources/firestore_methods.dart'; import 'package:flutter_instagram_app/screens/comments_screen.dart'; import 'package:flutter_instagram_app/utils/colors.dart'; import 'package:flutter_instagram_app/utils/global_variables.dart'; import 'package:flutter_instagram_app/utils/utils.dart'; import 'package:flutter_instagram_app/widgets/like_animation.dart'; import 'package:intl/intl.dart'; import 'package:provider/provider.dart'; class PostCard extends StatefulWidget { final snap; const PostCard({Key? key, required this.snap}) : super(key: key); @override State<PostCard> createState() => _PostCardState(); } class _PostCardState extends State<PostCard> { bool isLikeAnimating = false; int commentsLength = 0; @override void initState() { super.initState(); getComments(); } void getComments() async { try { QuerySnapshot snap = await FirebaseFirestore.instance .collection("posts") .doc(widget.snap['postId']) .collection("comments") .get(); commentsLength = snap.docs.length; } catch (e) { showSnackBar(e.toString(), context); } setState(() {}); } @override Widget build(BuildContext context) { final User user = Provider.of<UserProvider>(context).getUser; return Container( decoration: BoxDecoration( border: Border.all( color: MediaQuery.of(context).size.width > webScreenSize ? secondaryColor : mobileBackgroundColor), color: Theme.of(context).scaffoldBackgroundColor), padding: const EdgeInsets.symmetric( vertical: 10, ), child: Column( children: [ //Header Section Container( padding: const EdgeInsets.symmetric( vertical: 4, horizontal: 16, ).copyWith(right: 0), child: Row( children: [ CircleAvatar( radius: 16, backgroundImage: NetworkImage(widget.snap['profImage']), ), Expanded( child: Padding( padding: const EdgeInsets.only(left: 8), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( widget.snap['username'], style: const TextStyle(fontWeight: FontWeight.bold), ) ], ), ), ), IconButton( onPressed: () { showDialog( context: context, builder: (context) => Dialog( child: ListView( padding: const EdgeInsets.symmetric(vertical: 16), shrinkWrap: true, children: [ 'Delete', ] .map( (e) => InkWell( onTap: () async { String res = await FirestoreMethods() .deletePost(widget.snap['postId']); Navigator.of(context).pop(); if (res == 'success') { showSnackBar("Post deleted.", context); } else { showSnackBar(res, context); } }, child: Container( padding: const EdgeInsets.symmetric( vertical: 12, horizontal: 16), child: Text(e), ), ), ) .toList(), ), ), ); }, icon: const Icon(Icons.more_vert)) ], ), ), //Image Section GestureDetector( onDoubleTap: () async { await FirestoreMethods().likePost( widget.snap['postId'], user.uid, widget.snap['likes'], ); setState(() { isLikeAnimating = true; }); }, child: Stack( alignment: Alignment.center, children: [ SizedBox( height: MediaQuery.of(context).size.height * 0.35, width: double.infinity, child: Image.network( widget.snap['postUrl'], fit: BoxFit.cover, ), ), AnimatedOpacity( duration: const Duration(milliseconds: 200), opacity: isLikeAnimating ? 1 : 0, child: LikeAnimation( child: const Icon( Icons.favorite, color: Colors.white, size: 100, ), isAnimating: isLikeAnimating, duration: const Duration(milliseconds: 400), onEnd: () { setState(() { isLikeAnimating = false; }); }, ), ), ], ), ), //Likes Comment Scetion Row( children: [ LikeAnimation( isAnimating: widget.snap['likes'].contains(user.uid), smallLike: true, child: IconButton( onPressed: () async { await FirestoreMethods().likePost( widget.snap['postId'], user.uid, widget.snap['likes']); }, icon: widget.snap['likes'].contains(user.uid) ? const Icon(Icons.favorite, color: Colors.red) : const Icon(Icons.favorite_border), ), ), IconButton( onPressed: () => Navigator.of(context).push(MaterialPageRoute( builder: (context) => CommentsScreen( snap: widget.snap, ), )), icon: const Icon(Icons.comment_outlined), ), IconButton( onPressed: () {}, icon: const Icon(Icons.send), ), Expanded( child: Align( alignment: Alignment.bottomRight, child: IconButton( onPressed: () {}, icon: const Icon(Icons.bookmark_border)), )) ], ), //Description & No. of comments Container( padding: const EdgeInsets.symmetric(horizontal: 16), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ DefaultTextStyle( style: Theme.of(context) .textTheme .subtitle2! .copyWith(fontWeight: FontWeight.w800), child: Text( '${widget.snap['likes'].length} likes', style: Theme.of(context).textTheme.bodyText2, ), ), Container( width: double.infinity, padding: const EdgeInsets.only(top: 8), child: RichText( text: TextSpan( style: TextStyle(color: Theme.of(context).primaryColor), children: [ TextSpan( text: widget.snap['username'], style: const TextStyle(fontWeight: FontWeight.bold)), TextSpan(text: ' ${widget.snap['description']}') ], ), ), ), InkWell( onTap: () {}, child: Container( padding: const EdgeInsets.symmetric(vertical: 4), child: Text( "View all $commentsLength comments", style: const TextStyle(fontSize: 16, color: secondaryColor), ), ), ), Container( child: Text( DateFormat.yMMMd().format( widget.snap['datePublished'].toDate(), ), style: const TextStyle(fontSize: 12, color: secondaryColor), ), ), ], ), ) ], ), ); } }
0
mirrored_repositories/Flutter-Instagram-clone-App/lib
mirrored_repositories/Flutter-Instagram-clone-App/lib/widgets/follow_button.dart
import 'package:flutter/material.dart'; class FollowButton extends StatelessWidget { final Function()? function; final Color backgroundColor; final Color borderColor; final String text; final Color textColor; const FollowButton({ Key? key, this.function, required this.backgroundColor, required this.borderColor, required this.text, required this.textColor, }) : super(key: key); @override Widget build(BuildContext context) { return Container( padding: const EdgeInsets.only(top: 5), child: TextButton( onPressed: function, child: Container( decoration: BoxDecoration( color: backgroundColor, border: Border.all(color: borderColor), borderRadius: BorderRadius.circular(5), ), alignment: Alignment.center, child: Text(text, style: TextStyle( color: textColor, fontWeight: FontWeight.bold, )), width: 250, height: 27, )), ); } }
0
mirrored_repositories/Flutter-Instagram-clone-App/lib
mirrored_repositories/Flutter-Instagram-clone-App/lib/widgets/comment_card.dart
import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; class CommentCard extends StatefulWidget { final snap; const CommentCard({Key? key, required this.snap}) : super(key: key); @override _CommentCardState createState() => _CommentCardState(); } class _CommentCardState extends State<CommentCard> { @override Widget build(BuildContext context) { return Container( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 18), child: Row( children: [ CircleAvatar( backgroundImage: NetworkImage(widget.snap['profilePic']), radius: 18, ), Expanded( child: Padding( padding: const EdgeInsets.only(left: 16), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [ RichText( text: TextSpan( style: TextStyle(color: Theme.of(context).primaryColor), children: [ TextSpan( text: widget.snap['username'], style: const TextStyle(fontWeight: FontWeight.bold), ), TextSpan( text: widget.snap['commentText'], ) ], ), ), Padding( padding: const EdgeInsets.only(top: 4), child: Text( DateFormat.yMMMd() .format(widget.snap['datePublished'].toDate()), style: const TextStyle( fontSize: 12, fontWeight: FontWeight.w400), ), ), ], ), ), ), Container( padding: const EdgeInsets.all(8), child: const Icon( Icons.favorite, size: 16, ), ) ], ), ); } }
0
mirrored_repositories/Flutter-Instagram-clone-App/lib
mirrored_repositories/Flutter-Instagram-clone-App/lib/widgets/like_animation.dart
import 'package:flutter/material.dart'; class LikeAnimation extends StatefulWidget { final Widget child; final bool isAnimating; final Duration duration; final VoidCallback? onEnd; final bool smallLike; const LikeAnimation({ Key? key, required this.child, required this.isAnimating, this.duration = const Duration(milliseconds: 150), this.onEnd, this.smallLike = false, }) : super(key: key); @override _LikeAnimationState createState() => _LikeAnimationState(); } class _LikeAnimationState extends State<LikeAnimation> with SingleTickerProviderStateMixin { late AnimationController controller; late Animation<double> scale; @override void initState() { super.initState(); controller = AnimationController( vsync: this, duration: Duration(milliseconds: widget.duration.inMilliseconds ~/ 2), ); scale = Tween<double>(begin: 1, end: 1.2).animate(controller); } @override void didUpdateWidget(covariant LikeAnimation oldWidget) { super.didUpdateWidget(oldWidget); if (widget.isAnimating != oldWidget.isAnimating) { startAnimation(); } } startAnimation() async { if (widget.isAnimating || widget.smallLike) { await controller.forward(); await controller.reverse(); await Future.delayed(const Duration(milliseconds: 200)); if (widget.onEnd != null) { widget.onEnd!(); } } } @override void dispose() { super.dispose(); controller.dispose(); } @override Widget build(BuildContext context) { return ScaleTransition( scale: scale, child: widget.child, ); } }
0
mirrored_repositories/Flutter-Instagram-clone-App/lib
mirrored_repositories/Flutter-Instagram-clone-App/lib/responsive/responsive_layout_screen.dart
import 'package:flutter/material.dart'; import 'package:flutter_instagram_app/providers/user_provider.dart'; import 'package:flutter_instagram_app/utils/global_variables.dart'; import 'package:provider/provider.dart'; class ResponsiveLayout extends StatefulWidget { final Widget webScreenLayout; final Widget mobileScreenLayout; const ResponsiveLayout( {Key? key, required this.webScreenLayout, required this.mobileScreenLayout}) : super(key: key); @override State<ResponsiveLayout> createState() => _ResponsiveLayoutState(); } class _ResponsiveLayoutState extends State<ResponsiveLayout> { @override void initState() { super.initState(); addData(); } addData() async { UserProvider _userProvider = Provider.of(context, listen: false); await _userProvider.refreshUser(); } @override Widget build(BuildContext context) { return LayoutBuilder( builder: (context, constraints) { if (constraints.maxWidth > webScreenSize) { //Web Screen return widget.webScreenLayout; } //mobile Screen return widget.mobileScreenLayout; }, ); } }
0
mirrored_repositories/Flutter-Instagram-clone-App/lib
mirrored_repositories/Flutter-Instagram-clone-App/lib/responsive/web_screen_layout.dart
import 'package:flutter/material.dart'; import 'package:flutter_instagram_app/utils/global_variables.dart'; import 'package:flutter_svg/flutter_svg.dart'; import '../utils/colors.dart'; class WebSreenLayout extends StatefulWidget { const WebSreenLayout({Key? key}) : super(key: key); @override State<WebSreenLayout> createState() => _WebSreenLayoutState(); } class _WebSreenLayoutState extends State<WebSreenLayout> { int _page = 0; late PageController pageController; @override void initState() { super.initState(); pageController = PageController(); } @override void dispose() { super.dispose(); pageController.dispose(); } void navigationTapped(int page) { pageController.jumpToPage(page); setState(() { _page = page; }); } void onPageChanged(int page) { setState(() { _page = page; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: mobileBackgroundColor, centerTitle: false, title: SvgPicture.asset( "assets/ic_instagram.svg", color: primaryColor, height: 32, ), actions: [ IconButton( onPressed: () => navigationTapped(0), icon: Icon( Icons.home, color: _page == 0 ? primaryColor : secondaryColor, ), ), IconButton( onPressed: () => navigationTapped(1), icon: Icon( Icons.search, color: _page == 1 ? primaryColor : secondaryColor, ), ), IconButton( onPressed: () => navigationTapped(2), icon: Icon( Icons.add_a_photo, color: _page == 2 ? primaryColor : secondaryColor, ), ), IconButton( onPressed: () => navigationTapped(3), icon: Icon( Icons.favorite, color: _page == 3 ? primaryColor : secondaryColor, ), ), IconButton( onPressed: () => navigationTapped(4), icon: Icon( Icons.person, color: _page == 4 ? primaryColor : secondaryColor, ), ), IconButton( onPressed: () => navigationTapped(5), icon: Icon( Icons.messenger_outline, color: _page == 5 ? primaryColor : secondaryColor, ), ) ], ), body: PageView( physics: const NeverScrollableScrollPhysics(), children: homeScreenItems, controller: pageController, onPageChanged: onPageChanged), ); } }
0
mirrored_repositories/Flutter-Instagram-clone-App/lib
mirrored_repositories/Flutter-Instagram-clone-App/lib/responsive/mobile_screen_layout.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_instagram_app/utils/colors.dart'; import '../utils/global_variables.dart'; class MobileScreenLayout extends StatefulWidget { const MobileScreenLayout({Key? key}) : super(key: key); @override State<MobileScreenLayout> createState() => _MobileScreenLayoutState(); } class _MobileScreenLayoutState extends State<MobileScreenLayout> { int _page = 0; late PageController pageController; //It will make so many calls to Database that's why not useful. // String username = ""; // @override // void initState() { // super.initState(); // getUsername(); // } // void getUsername() async { // DocumentSnapshot snapshot = await FirebaseFirestore.instance // .collection('users') // .doc(FirebaseAuth.instance.currentUser!.uid) // .get(); // setState(() { // username = (snapshot.data() as Map<String, dynamic>)['username']; // }); // } @override void initState() { super.initState(); pageController = PageController(); } @override void dispose() { super.dispose(); pageController.dispose(); } void navigationTapped(int page) { pageController.jumpToPage(page); } void onPageChanged(int page) { setState(() { _page = page; }); } @override Widget build(BuildContext context) { //Using Provider: It will make just one call to Database that's why useful. // userModel.User user = Provider.of<UserProvider>(context).getUser; return Scaffold( body: PageView( children: homeScreenItems, physics: const NeverScrollableScrollPhysics(), controller: pageController, onPageChanged: onPageChanged, ), bottomNavigationBar: CupertinoTabBar( backgroundColor: Theme.of(context).scaffoldBackgroundColor, items: [ BottomNavigationBarItem( icon: Icon( Icons.home, color: _page == 0 ? Theme.of(context).primaryColor : secondaryColor, ), backgroundColor: Theme.of(context).primaryColor), BottomNavigationBarItem( icon: Icon( Icons.search, color: _page == 1 ? Theme.of(context).primaryColor : secondaryColor, ), backgroundColor: Theme.of(context).primaryColor), BottomNavigationBarItem( icon: Icon( Icons.add_circle, color: _page == 2 ? Theme.of(context).primaryColor : secondaryColor, ), backgroundColor: Theme.of(context).primaryColor), BottomNavigationBarItem( icon: Icon( Icons.favorite, color: _page == 3 ? Theme.of(context).primaryColor : secondaryColor, ), backgroundColor: Theme.of(context).primaryColor), BottomNavigationBarItem( icon: Icon( Icons.person, color: _page == 4 ? Theme.of(context).primaryColor : secondaryColor, ), backgroundColor: Theme.of(context).primaryColor), ], onTap: navigationTapped, ), ); } }
0
mirrored_repositories/Flutter-Instagram-clone-App/lib
mirrored_repositories/Flutter-Instagram-clone-App/lib/resources/storage_methods.dart
import 'dart:typed_data'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_storage/firebase_storage.dart'; import 'package:flutter/material.dart'; import 'package:uuid/uuid.dart'; class StorageMethods { final FirebaseStorage _storage = FirebaseStorage.instance; final FirebaseAuth _auth = FirebaseAuth.instance; //Adding images to firebase stoarge Future<String> uploadImageToStorage( String childName, Uint8List file, bool isPost) async { Reference ref = _storage.ref().child(childName).child(_auth.currentUser!.uid); if (isPost) { String id = const Uuid().v1(); ref = ref.child(id); } UploadTask uploadTask = ref.putData(file); //Not work for web/ Only for mobile App // ref.putFile(File(_file.path)); TaskSnapshot snap = await uploadTask; String downloadUrl = await snap.ref.getDownloadURL(); return downloadUrl; } }
0
mirrored_repositories/Flutter-Instagram-clone-App/lib
mirrored_repositories/Flutter-Instagram-clone-App/lib/resources/firestore_methods.dart
import 'dart:typed_data'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter_instagram_app/model/posts.dart'; import 'package:flutter_instagram_app/resources/storage_methods.dart'; import 'package:uuid/uuid.dart'; class FirestoreMethods { final FirebaseFirestore _firestore = FirebaseFirestore.instance; //uploadPost Future<String> uploadPost( String description, Uint8List file, String uid, String username, String profImage, ) async { String res = 'some error occurred'; try { String photoUrl = await StorageMethods().uploadImageToStorage('posts', file, true); String postId = const Uuid().v1(); Posts post = Posts( description: description, uid: uid, username: username, postId: postId, datePublished: DateTime.now(), postUrl: photoUrl, profImage: profImage, likes: [], ); _firestore.collection("posts").doc(postId).set(post.toJson()); res = 'success'; } catch (err) { res = err.toString(); } return res; } Future<void> likePost(String postId, String uid, List likes) async { try { if (likes.contains(uid)) { await _firestore.collection("posts").doc(postId).update({ 'likes': FieldValue.arrayRemove([uid]) }); } else { await _firestore.collection("posts").doc(postId).update({ 'likes': FieldValue.arrayUnion([uid]) }); } } catch (e) { print(e.toString()); } } Future<String> postComment(String postId, String text, String uid, String username, String profilePic) async { String res = "some error occurred"; try { if (text.isNotEmpty) { String commentId = const Uuid().v1(); await _firestore .collection("posts") .doc(postId) .collection("comments") .doc(commentId) .set({ 'profilePic': profilePic, 'postId': postId, 'commentText': text, 'uid': uid, 'username': username, 'commentId': commentId, 'datePublished': DateTime.now(), }); res = "success"; } else { res = "Please write something first..."; } } catch (e) { print(e.toString()); } return res; } //Deleting Post Future<String> deletePost(String postId) async { String res = 'some error occurred'; try { await _firestore.collection("posts").doc(postId).delete(); res = 'success'; } catch (e) { print(e.toString()); } return res; } Future<void> followUser(String uid, String followId) async { try { DocumentSnapshot snap = await _firestore.collection("users").doc(uid).get(); List following = (snap.data()! as dynamic)['following']; if (following.contains(followId)) { await _firestore.collection("users").doc(followId).update({ 'followers': FieldValue.arrayRemove([uid]) }); await _firestore.collection("users").doc(uid).update({ 'following': FieldValue.arrayRemove([followId]) }); }else{ await _firestore.collection("users").doc(followId).update({ 'followers': FieldValue.arrayUnion([uid]) }); await _firestore.collection("users").doc(uid).update({ 'following': FieldValue.arrayUnion([followId]) }); } } catch (e) { print(e.toString()); } } }
0
mirrored_repositories/Flutter-Instagram-clone-App/lib
mirrored_repositories/Flutter-Instagram-clone-App/lib/resources/auth_methods.dart
import 'dart:typed_data'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:flutter_instagram_app/model/users.dart' as userModel; import 'package:flutter_instagram_app/resources/storage_methods.dart'; class AuthMethods { final FirebaseAuth _auth = FirebaseAuth.instance; final FirebaseFirestore _firestore = FirebaseFirestore.instance; Future<userModel.User> getUserDetails() async { User currentUser = _auth.currentUser!; DocumentSnapshot snap = await _firestore.collection('users').doc(currentUser.uid).get(); return userModel.User.fromSnap(snap); } //SignUp User Future<String> signUpUser( {required String email, required String password, required String username, required String bio, Uint8List? file}) async { String res = "Some error occurred"; if (file == null) { return res = "Please chosse profile image."; } try { if (email.isNotEmpty || password.isNotEmpty || username.isNotEmpty || bio.isNotEmpty || file != null) { //Register User UserCredential userCredential = await _auth .createUserWithEmailAndPassword(email: email, password: password); String photoUrl = await StorageMethods() .uploadImageToStorage('profilePics', file, false); print(userCredential.user!.uid); //Add user to our database userModel.User user = userModel.User( username: username, email: email, uid: userCredential.user!.uid, bio: bio, followers: [], following: [], phototUrl: photoUrl); //Using this method UsersId and docId would be same await _firestore .collection('users') .doc(userCredential.user!.uid) .set(user.toJson()); //Using this method UsersId and docId would be different // await _firestore.collection('users').add({ // 'username': username, // 'uid': userCredential.user!.uid, // 'email': email, // 'bio': bio, // 'followers': [], // 'following': [], // }); res = "success"; } } on FirebaseAuthException catch (exception, s) { print(exception.toString() + '$s'); switch ((exception).code) { case 'weak-password': return res = 'The password provided is too weak.'; case 'email-already-in-use': return res = 'The account already exists for that email.'; } // return res = 'Unexpected firebase error, Please try again.'; } catch (err) { res = err.toString(); } return res; } //Logging in user Future<String> loginUser( {required String email, required String password}) async { String res = 'Some error occurred'; try { if (email.isNotEmpty && password.isNotEmpty) { await _auth.signInWithEmailAndPassword( email: email, password: password); res = 'success'; } else { res = 'Please enter all the fields'; } } on FirebaseAuthException catch (exception, s) { print(exception.toString() + '$s'); switch ((exception).code) { case 'invalid-email': return res = 'Invalid email address.'; case 'wrong-password': return res = 'Wrong password.'; case 'user-not-found': return res = 'No user corresponding to the given email address.'; case 'user-disabled': return res = 'This user has been disabled.'; case 'too-many-requests': return res = 'Too many attempts to sign in as this user.'; } // return res = 'Unexpected firebase error, Please try again.'; } catch (err) { res = err.toString(); } return res; } Future<void> signOut() async { await _auth.signOut(); } }
0
mirrored_repositories/Flutter-Instagram-clone-App/lib
mirrored_repositories/Flutter-Instagram-clone-App/lib/model/posts.dart
import 'package:cloud_firestore/cloud_firestore.dart'; class Posts { final String description; final String uid; final String username; final String postId; final datePublished; final String postUrl; final String profImage; final likes; Posts({ required this.description, required this.uid, required this.username, required this.postId, required this.datePublished, required this.postUrl, required this.profImage, required this.likes, }); Map<String, dynamic> toJson() => { 'description': description, 'uid': uid, 'username': username, 'postId': postId, 'datePublished': datePublished, 'postUrl': postUrl, 'profImage': profImage, 'likes': likes, }; static Posts fromSnap(DocumentSnapshot snap) { var snapshot = snap.data() as Map<String, dynamic>; return Posts( description: snapshot['description'], uid: snapshot['uid'], username: snapshot['username'], datePublished: snapshot['datePublished'], postId: snapshot['postId'], postUrl: snapshot['postUrl'], profImage: snapshot['profImage'], likes: snapshot['likes'], ); } }
0
mirrored_repositories/Flutter-Instagram-clone-App/lib
mirrored_repositories/Flutter-Instagram-clone-App/lib/model/users.dart
import 'package:cloud_firestore/cloud_firestore.dart'; class User { final String email; final String uid; final String phototUrl; final String username; final String bio; final List followers; final List following; const User({ required this.email, required this.uid, required this.phototUrl, required this.username, required this.bio, required this.followers, required this.following, }); Map<String, dynamic> toJson() => { 'username': username, 'email': email, 'uid': uid, 'photoUrl': phototUrl, 'bio': bio, 'followers': followers, 'following': following }; static User fromSnap(DocumentSnapshot snap) { var snapshot = snap.data() as Map<String, dynamic>; return User( email: snapshot['email'], uid: snapshot['uid'], phototUrl: snapshot['photoUrl'], username: snapshot['username'], bio: snapshot['bio'], followers: snapshot['followers'], following: snapshot['following'], ); } }
0
mirrored_repositories/Flutter-Instagram-clone-App/lib
mirrored_repositories/Flutter-Instagram-clone-App/lib/utils/my_theme.dart
import 'package:flutter/material.dart'; import 'colors.dart'; class ThemeProvider extends ChangeNotifier { ThemeMode themeMode = ThemeMode.system; bool get isDarkMode => themeMode == ThemeMode.dark; void toggleTheme(bool isOn) { themeMode = isOn ? ThemeMode.dark : ThemeMode.light; notifyListeners(); } } class MyTheme { static ThemeData lightTheme() => ThemeData( scaffoldBackgroundColor: lightMobileBackgroundColor, primarySwatch: Colors.grey, primaryColor: const Color.fromARGB(255, 37, 36, 36), brightness: Brightness.light, backgroundColor: Colors.white, textSelectionTheme: const TextSelectionThemeData( cursorColor: Colors.black, selectionColor: Colors.grey, selectionHandleColor: Colors.black, ), colorScheme: ColorScheme.fromSwatch(brightness: Brightness.light) .copyWith(secondary: Colors.grey), ); static ThemeData darkTheme() => ThemeData( scaffoldBackgroundColor: mobileBackgroundColor, colorScheme: ColorScheme.fromSwatch(brightness: Brightness.dark) .copyWith(secondary: Colors.grey), primarySwatch: Colors.grey, primaryColor: Colors.white, brightness: Brightness.dark, backgroundColor: Colors.white, textSelectionTheme: const TextSelectionThemeData( cursorColor: Colors.black, selectionColor: Colors.grey, selectionHandleColor: Colors.black, ), ); // //Colors // static Color creamColor = const Color(0xfff5f5f5); // static Color darkCreamColor = Vx.gray900; // static Color darkBluishColor = const Color(0xff403b58); // static Color lightBluishColor = Vx.indigo500; }
0
mirrored_repositories/Flutter-Instagram-clone-App/lib
mirrored_repositories/Flutter-Instagram-clone-App/lib/utils/global_variables.dart
import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:flutter_instagram_app/screens/add_post_screen.dart'; import 'package:flutter_instagram_app/screens/profile_screen.dart'; import '../screens/feed_screen.dart'; import '../screens/search_screen.dart'; const webScreenSize = 600; List<Widget> homeScreenItems = [ FeedScreen(), SearchScreen(), AddPostScreen(), const Text("Notifications"), ProfileScreen(uid: FirebaseAuth.instance.currentUser!.uid,), ];
0
mirrored_repositories/Flutter-Instagram-clone-App/lib
mirrored_repositories/Flutter-Instagram-clone-App/lib/utils/colors.dart
import 'package:flutter/material.dart'; //DarkColors const mobileBackgroundColor = Color.fromRGBO(0, 0, 0, 1); const webBackgroundColor = Color.fromRGBO(18, 18, 18, 1); const mobileSearchColor = Color.fromRGBO(38, 38, 38, 1); const blueColor = Color.fromRGBO(0, 149, 246, 1); const primaryColor = Colors.white; const secondaryColor = Colors.grey; //LightColors const lightMobileBackgroundColor = Color.fromARGB(255, 255, 255, 255);
0
mirrored_repositories/Flutter-Instagram-clone-App/lib
mirrored_repositories/Flutter-Instagram-clone-App/lib/utils/utils.dart
import 'dart:io'; import 'package:flutter/material.dart'; import 'package:image_picker/image_picker.dart'; pickImage(ImageSource imgSource) async { final ImagePicker _imagePicker = ImagePicker(); XFile? _file = await _imagePicker.pickImage(source: imgSource); if (_file != null) { return await _file.readAsBytes(); } print("No image selected"); } showSnackBar(String content, BuildContext context) { ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(content))); }
0
mirrored_repositories/Flutter-Instagram-clone-App/lib
mirrored_repositories/Flutter-Instagram-clone-App/lib/screens/feed_screen.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:flutter_instagram_app/utils/colors.dart'; import 'package:flutter_instagram_app/utils/global_variables.dart'; import 'package:flutter_instagram_app/utils/my_theme.dart'; import 'package:flutter_svg/flutter_svg.dart'; import '../widgets/change_theme_button_widget.dart'; import '../widgets/post_card.dart'; class FeedScreen extends StatefulWidget { const FeedScreen({Key? key}) : super(key: key); @override State<FeedScreen> createState() => _FeedScreenState(); } class _FeedScreenState extends State<FeedScreen> { @override Widget build(BuildContext context) { final width = MediaQuery.of(context).size.width; return Scaffold( backgroundColor: width > webScreenSize ? webBackgroundColor : Theme.of(context).scaffoldBackgroundColor, appBar: width > webScreenSize ? null : AppBar( backgroundColor: Theme.of(context).scaffoldBackgroundColor, centerTitle: false, title: SvgPicture.asset( "assets/ic_instagram.svg", color: Theme.of(context).primaryColor, height: 32, ), actions: [ const ChangeThemeButtonWidget(), IconButton( color: Theme.of(context).primaryColor, onPressed: () {}, icon: const Icon(Icons.messenger_outline), ) ], ), body: StreamBuilder( stream: FirebaseFirestore.instance.collection('posts').snapshots(), builder: (context, AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>> snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return const Center( child: CircularProgressIndicator(), ); } return ListView.builder( itemCount: snapshot.data!.docs.length, itemBuilder: (context, index) => Container( margin: EdgeInsets.symmetric( horizontal: width > webScreenSize ? width * 0.3 : 0, vertical: width > webScreenSize ? 10 : 0, ), child: PostCard( snap: snapshot.data!.docs[index].data(), ), ), ); }), ); } }
0
mirrored_repositories/Flutter-Instagram-clone-App/lib
mirrored_repositories/Flutter-Instagram-clone-App/lib/screens/profile_screen.dart
import 'dart:io'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:flutter_instagram_app/resources/auth_methods.dart'; import 'package:flutter_instagram_app/resources/firestore_methods.dart'; import 'package:flutter_instagram_app/screens/login_screen.dart'; import 'package:flutter_instagram_app/utils/colors.dart'; import 'package:flutter_instagram_app/utils/utils.dart'; import '../widgets/follow_button.dart'; class ProfileScreen extends StatefulWidget { final String uid; const ProfileScreen({ Key? key, required this.uid, }) : super(key: key); @override _ProfileScreenState createState() => _ProfileScreenState(); } class _ProfileScreenState extends State<ProfileScreen> { var userData = {}; int postLen = 0; int followers = 0; int following = 0; bool isFollowing = false; bool isLoading = false; @override void initState() { super.initState(); getData(); } getData() async { setState(() { isLoading = true; }); try { var userSnapshot = await FirebaseFirestore.instance .collection("users") .doc(widget.uid) .get(); userData = userSnapshot.data()!; followers = userData['followers'].length; following = userData['following'].length; isFollowing = userData['followers'] .contains(FirebaseAuth.instance.currentUser!.uid); //Get post length var postSnap = await FirebaseFirestore.instance .collection("posts") .where('uid', isEqualTo: FirebaseAuth.instance.currentUser!.uid) .get(); postLen = postSnap.docs.length; setState(() {}); } catch (e) { showSnackBar(e.toString(), context); } setState(() { isLoading = false; }); } @override Widget build(BuildContext context) { return isLoading ? const Center( child: CircularProgressIndicator(), ) : Scaffold( appBar: AppBar( iconTheme: IconThemeData(color: Theme.of(context).primaryColor), backgroundColor: Theme.of(context).scaffoldBackgroundColor, title: Text( userData["username"], style: TextStyle(color: Theme.of(context).primaryColor), ), centerTitle: false, ), body: ListView( children: [ Padding( padding: const EdgeInsets.all(16.0), child: Column( children: [ Row( children: [ CircleAvatar( backgroundColor: Colors.grey, backgroundImage: NetworkImage( userData["photoUrl"], ), radius: 40, ), Expanded( flex: 1, child: Column( children: [ Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ buildStatColumn(postLen, 'Posts'), buildStatColumn(followers, 'Followers'), buildStatColumn(following, 'Followings'), ], ), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ FirebaseAuth.instance.currentUser!.uid == widget.uid ? FollowButton( text: 'Sign Out', backgroundColor: Theme.of(context) .scaffoldBackgroundColor, textColor: Theme.of(context).primaryColor, borderColor: Colors.grey, function: () async { AuthMethods().signOut(); Navigator.of(context) .push(MaterialPageRoute( builder: (context) => const LoginScreen(), )); }, ) : isFollowing ? FollowButton( text: 'Unfollow', backgroundColor: Colors.white, textColor: Colors.black, borderColor: Colors.grey, function: () async { await FirestoreMethods() .followUser( FirebaseAuth.instance .currentUser!.uid, userData['uid']); setState(() { isFollowing = false; followers--; }); }, ) : FollowButton( text: 'Follow', backgroundColor: Colors.blue, textColor: primaryColor, borderColor: Colors.blueAccent, function: () async { await FirestoreMethods() .followUser( FirebaseAuth.instance .currentUser!.uid, userData['uid']); setState(() { isFollowing = true; followers++; }); }, ), ], ) ], ), ), ], ), Container( alignment: Alignment.centerLeft, padding: const EdgeInsets.only(top: 15), child: Text( userData["username"], style: const TextStyle(fontWeight: FontWeight.bold), ), ), Container( alignment: Alignment.centerLeft, padding: const EdgeInsets.only(top: 1), child: Text( userData["bio"], ), ) ], ), ), const Divider( color: Colors.grey, height: 5, ), FutureBuilder( future: FirebaseFirestore.instance .collection("posts") .where("uid", isEqualTo: widget.uid) .get(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return const Center( child: CircularProgressIndicator(), ); } return GridView.builder( shrinkWrap: true, itemCount: (snapshot.data! as dynamic).docs.length, gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 3, crossAxisSpacing: 5, mainAxisSpacing: 1.5, childAspectRatio: 1, ), itemBuilder: (context, index) { DocumentSnapshot snap = (snapshot.data! as dynamic).docs[index]; return Container( child: Image( image: NetworkImage(snap['postUrl']), fit: BoxFit.cover, ), ); }); }) ], ), ); } Column buildStatColumn(int num, String label) { return Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, children: [ Text( num.toString(), style: const TextStyle( fontSize: 18, fontWeight: FontWeight.bold, ), ), Container( margin: const EdgeInsets.only(top: 4), child: Text( label, style: const TextStyle( fontSize: 15, fontWeight: FontWeight.w400, color: Colors.grey), ), ) ], ); } }
0
mirrored_repositories/Flutter-Instagram-clone-App/lib
mirrored_repositories/Flutter-Instagram-clone-App/lib/screens/add_post_screen.dart
// ignore_for_file: unused_local_variable, prefer_const_constructors import 'dart:io'; import 'dart:typed_data'; import 'package:flutter/material.dart'; import 'package:flutter_instagram_app/providers/user_provider.dart'; import 'package:flutter_instagram_app/resources/firestore_methods.dart'; import 'package:flutter_instagram_app/utils/colors.dart'; import 'package:flutter_instagram_app/utils/utils.dart'; import 'package:image_picker/image_picker.dart'; import 'package:provider/provider.dart'; class AddPostScreen extends StatefulWidget { const AddPostScreen({Key? key}) : super(key: key); @override _AddPostScreenState createState() => _AddPostScreenState(); } class _AddPostScreenState extends State<AddPostScreen> { Uint8List? _file; final TextEditingController _descriptionController = TextEditingController(); bool isLoading = false; void postImage( String uid, String username, String profImage, ) async { setState(() { isLoading = true; }); try { String res = await FirestoreMethods().uploadPost( _descriptionController.text, _file!, uid, username, profImage, ); if (res == 'success') { setState(() { isLoading = false; }); showSnackBar("Posted!", context); clearImage(); } else { setState(() { isLoading = false; }); showSnackBar(res, context); } } catch (err) { setState(() { isLoading = false; }); showSnackBar(err.toString(), context); } } _selectImage(BuildContext context) async { return showDialog( context: context, builder: (context) { return SimpleDialog( title: const Text("Create a Post"), children: [ SimpleDialogOption( padding: const EdgeInsets.all(20), child: const Text("Take a Photo"), onPressed: () async { Navigator.of(context).pop(); Uint8List file = await pickImage(ImageSource.camera); setState( () { _file = file; }, ); }, ), SimpleDialogOption( padding: const EdgeInsets.all(20), child: const Text("Choose from gallery"), onPressed: () async { Navigator.of(context).pop(); Uint8List file = await pickImage(ImageSource.gallery); setState( () { _file = file; }, ); }, ), SimpleDialogOption( padding: const EdgeInsets.all(20), child: const Text("Cancel"), onPressed: () async { Navigator.of(context).pop(); }, ), ], ); }, ); } void clearImage() { setState(() { _file = null; }); } @override void dispose() { super.dispose(); _descriptionController.dispose(); } @override Widget build(BuildContext context) { //Using Provider: It will make just one call to Database that's why useful. final UserProvider userProvider = Provider.of<UserProvider>(context); return _file == null ? Center( child: IconButton( onPressed: () => _selectImage(context), icon: const Icon(Icons.upload), ), ) : Scaffold( appBar: AppBar( backgroundColor: mobileBackgroundColor, leading: IconButton( onPressed: clearImage, icon: const Icon(Icons.arrow_back), ), title: const Text("Post to"), centerTitle: false, actions: [ TextButton( onPressed: () => postImage( userProvider.getUser.uid, userProvider.getUser.username, userProvider.getUser.phototUrl), child: const Text( "Post", style: TextStyle( color: Colors.blueAccent, fontWeight: FontWeight.bold, fontSize: 16, ), ), ) ], ), body: Column( children: [ isLoading ? const LinearProgressIndicator() : const Padding( padding: EdgeInsets.only(top: 0), ), const Divider(), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, crossAxisAlignment: CrossAxisAlignment.start, children: [ CircleAvatar( backgroundImage: NetworkImage(userProvider.getUser.phototUrl), ), // ignore: duplicate_ignore SizedBox( width: MediaQuery.of(context).size.width * 0.45, // ignore: prefer_const_constructors child: TextField( controller: _descriptionController, decoration: const InputDecoration( hintText: 'Write a caption...', border: InputBorder.none, ), maxLines: 8, ), ), SizedBox( height: 45, width: 45, child: AspectRatio( aspectRatio: 487 / 451, child: Container( decoration: BoxDecoration( // ignore: prefer_const_constructors image: DecorationImage( // ignore: prefer_const_constructors image: MemoryImage(_file!), fit: BoxFit.fill, alignment: FractionalOffset.topCenter, ), ), ), ), ), ], ), const Divider( height: 2, color: primaryColor, ) ], ), ); } }
0
mirrored_repositories/Flutter-Instagram-clone-App/lib
mirrored_repositories/Flutter-Instagram-clone-App/lib/screens/signup_screen.dart
import 'dart:typed_data'; import 'package:flutter/material.dart'; import 'package:flutter_instagram_app/resources/auth_methods.dart'; import 'package:flutter_instagram_app/screens/login_screen.dart'; import 'package:flutter_instagram_app/utils/colors.dart'; import 'package:flutter_instagram_app/utils/utils.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:image_picker/image_picker.dart'; import '../responsive/mobile_screen_layout.dart'; import '../responsive/responsive_layout_screen.dart'; import '../responsive/web_screen_layout.dart'; import '../widgets/text_field_input.dart'; class SignUpScreen extends StatefulWidget { const SignUpScreen({Key? key}) : super(key: key); @override State<SignUpScreen> createState() => _SignUpScreenState(); } class _SignUpScreenState extends State<SignUpScreen> { final TextEditingController _emailController = TextEditingController(); final TextEditingController _passwordController = TextEditingController(); final TextEditingController _bioController = TextEditingController(); final TextEditingController _usernameController = TextEditingController(); Uint8List? _image; bool _isLoading = false; @override void dispose() { super.dispose(); _emailController.dispose(); _passwordController.dispose(); _bioController.dispose(); _usernameController.dispose(); } selectImage() async { Uint8List img = await pickImage(ImageSource.gallery); setState(() { _image = img; }); } void signupUser() async { setState(() { _isLoading = true; }); String res = await AuthMethods().signUpUser( email: _emailController.text, password: _passwordController.text, username: _usernameController.text, bio: _bioController.text, file: _image, ); if (res == "success") { setState(() { _isLoading = false; }); Navigator.of(context).pushReplacement(MaterialPageRoute( builder: (context) => const ResponsiveLayout( webScreenLayout: WebSreenLayout(), mobileScreenLayout: MobileScreenLayout()), )); } else { setState(() { _isLoading = false; }); // show the error showSnackBar(res, context); } } void navigateToLogin() { Navigator.of(context).push(MaterialPageRoute( builder: (context) => const LoginScreen(), )); } @override Widget build(BuildContext context) { return Scaffold( body: SafeArea( child: Container( padding: const EdgeInsets.symmetric(horizontal: 32), width: double.infinity, child: Center( child: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ // Flexible(child: Container(), flex: 2), //SVG image SvgPicture.asset( "assets/ic_instagram.svg", color: Theme.of(context).primaryColor, height: 64, ), const SizedBox(height: 64), //Circuler widget to accept and show user profile image Stack( children: [ _image != null ? CircleAvatar( radius: 64, backgroundImage: MemoryImage(_image!)) : const CircleAvatar( radius: 64, backgroundImage: AssetImage('assets/profile_pic.png'), ), Positioned( bottom: -10, left: 80, child: IconButton( onPressed: () => selectImage(), icon: const Icon(Icons.add_a_photo), color: blueColor, )) ], ), const SizedBox(height: 24), //Text field input for username TextFieldInput( textEditingController: _usernameController, hintText: "Enter your username", textInputType: TextInputType.text), const SizedBox(height: 24), //Text field input for email TextFieldInput( textEditingController: _emailController, hintText: "Enter your email", textInputType: TextInputType.emailAddress), //Text filed input for password const SizedBox(height: 24), TextFieldInput( textEditingController: _passwordController, hintText: "Enter your password", textInputType: TextInputType.text, isPass: true, ), const SizedBox(height: 24), //Text field input for bio TextFieldInput( textEditingController: _bioController, hintText: "Enter your bio", textInputType: TextInputType.text), const SizedBox(height: 24), //Button Login InkWell( onTap: () => signupUser(), child: Container( child: _isLoading ? const Center( child: CircularProgressIndicator( color: primaryColor, ), ) : const Text("Sign up"), width: double.infinity, alignment: Alignment.center, padding: const EdgeInsets.symmetric(vertical: 12), decoration: const ShapeDecoration( shape: RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(4))), color: blueColor), ), ), const SizedBox(height: 12), // Flexible(child: Container(), flex: 2), //Transitioning to Signing Up Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Container( child: const Text("Already have an account?"), padding: const EdgeInsets.symmetric(vertical: 8), ), GestureDetector( onTap: () => navigateToLogin(), child: Container( child: const Text( " Login.", style: TextStyle(fontWeight: FontWeight.bold), ), padding: const EdgeInsets.symmetric(vertical: 8), ), ) ], ) ], ), ), ), )), ); } }
0
mirrored_repositories/Flutter-Instagram-clone-App/lib
mirrored_repositories/Flutter-Instagram-clone-App/lib/screens/comments_screen.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:flutter_instagram_app/model/users.dart'; import 'package:flutter_instagram_app/providers/user_provider.dart'; import 'package:flutter_instagram_app/resources/firestore_methods.dart'; import 'package:flutter_instagram_app/utils/colors.dart'; import 'package:flutter_instagram_app/utils/utils.dart'; import 'package:provider/provider.dart'; import '../widgets/comment_card.dart'; class CommentsScreen extends StatefulWidget { final snap; const CommentsScreen({Key? key, required this.snap}) : super(key: key); @override _CommentsScreenState createState() => _CommentsScreenState(); } class _CommentsScreenState extends State<CommentsScreen> { final TextEditingController _commentController = TextEditingController(); @override void dispose() { super.dispose(); _commentController.dispose(); } @override Widget build(BuildContext context) { final User user = Provider.of<UserProvider>(context).getUser; return Scaffold( appBar: AppBar( foregroundColor: Theme.of(context).primaryColor, elevation: 0, iconTheme: IconThemeData(color: Theme.of(context).primaryColor), backgroundColor: Theme.of(context).scaffoldBackgroundColor, title: const Text("Comments"), centerTitle: false, ), body: StreamBuilder( stream: FirebaseFirestore.instance .collection("posts") .doc(widget.snap['postId']) .collection("comments") .orderBy("datePublished", descending: true) .snapshots(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return const Center( child: CircularProgressIndicator(), ); } return ListView.builder( itemCount: (snapshot.data! as dynamic).docs.length, itemBuilder: (context, index) => CommentCard( snap: (snapshot.data! as dynamic).docs[index].data(), ), ); }), bottomNavigationBar: SafeArea( child: Container( height: kToolbarHeight, margin: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom), padding: const EdgeInsets.only(left: 16, right: 8), child: Row( children: [ CircleAvatar( backgroundImage: NetworkImage(user.phototUrl), radius: 18, ), Expanded( child: Padding( padding: const EdgeInsets.only(left: 16, right: 8.0), child: TextField( controller: _commentController, decoration: InputDecoration( hintText: 'Comment as ${user.username}', border: InputBorder.none, ), ), ), ), InkWell( onTap: () async { String res = await FirestoreMethods().postComment( widget.snap['postId'], _commentController.text, user.uid, user.username, user.phototUrl); if (res == 'success') { showSnackBar('Comment posted.', context); } else { showSnackBar(res, context); } setState(() { _commentController.text = ""; }); }, child: Container( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8), child: const Text( "Post", style: TextStyle(color: Colors.blueAccent), ), ), ) ], ), )), ); } }
0
mirrored_repositories/Flutter-Instagram-clone-App/lib
mirrored_repositories/Flutter-Instagram-clone-App/lib/screens/search_screen.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:flutter_instagram_app/screens/profile_screen.dart'; import 'package:flutter_instagram_app/utils/colors.dart'; import 'package:flutter_instagram_app/utils/global_variables.dart'; import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart'; class SearchScreen extends StatefulWidget { const SearchScreen({Key? key}) : super(key: key); @override _SearchScreenState createState() => _SearchScreenState(); } class _SearchScreenState extends State<SearchScreen> { final TextEditingController _searchController = TextEditingController(); bool isShowUsers = false; bool isLoading = false; @override void dispose() { super.dispose(); _searchController.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Theme.of(context).scaffoldBackgroundColor, title: TextFormField( controller: _searchController, decoration: const InputDecoration( labelText: 'Search for a user', ), onFieldSubmitted: (String _) { setState(() { isShowUsers = true; }); }, ), ), body: isShowUsers ? FutureBuilder( future: FirebaseFirestore.instance .collection("users") .where("username", isGreaterThanOrEqualTo: _searchController.text) .get(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return const Center( child: CircularProgressIndicator(), ); } return ListView.builder( itemCount: (snapshot.data! as dynamic).docs.length, itemBuilder: (context, index) { return InkWell( onTap: () => Navigator.of(context).push(MaterialPageRoute( builder: (context) => ProfileScreen( uid: (snapshot.data! as dynamic).docs[index] ['uid']), )), child: ListTile( leading: CircleAvatar( backgroundImage: NetworkImage( (snapshot.data! as dynamic).docs[index] ['photoUrl']), ), title: Text((snapshot.data! as dynamic).docs[index] ['username']), ), ); }, ); }, ) : FutureBuilder( future: FirebaseFirestore.instance.collection("posts").get(), builder: (context, snapshot) { if (!snapshot.hasData) { return const Center( child: CircularProgressIndicator(), ); } return StaggeredGridView.countBuilder( crossAxisCount: 3, itemCount: (snapshot.data! as dynamic).docs.length, itemBuilder: (context, index) => Image.network( (snapshot.data! as dynamic).docs[index]['postUrl']), staggeredTileBuilder: (index) => MediaQuery.of(context).size.width > webScreenSize ? StaggeredTile.count( (index % 7 == 0) ? 1 : 1, (index % 7 == 0) ? 1 : 1, ) : StaggeredTile.count( (index % 7 == 0) ? 2 : 1, (index % 7 == 0) ? 2 : 1, ), mainAxisSpacing: 8, crossAxisSpacing: 9, ); }), ); } }
0
mirrored_repositories/Flutter-Instagram-clone-App/lib
mirrored_repositories/Flutter-Instagram-clone-App/lib/screens/login_screen.dart
import 'package:flutter/material.dart'; import 'package:flutter_instagram_app/resources/auth_methods.dart'; import 'package:flutter_instagram_app/screens/signup_screen.dart'; import 'package:flutter_instagram_app/utils/colors.dart'; import 'package:flutter_instagram_app/utils/global_variables.dart'; import 'package:flutter_instagram_app/utils/utils.dart'; import 'package:flutter_instagram_app/widgets/text_field_input.dart'; import 'package:flutter_svg/flutter_svg.dart'; import '../responsive/mobile_screen_layout.dart'; import '../responsive/responsive_layout_screen.dart'; import '../responsive/web_screen_layout.dart'; class LoginScreen extends StatefulWidget { const LoginScreen({Key? key}) : super(key: key); @override State<LoginScreen> createState() => _LoginScreenState(); } class _LoginScreenState extends State<LoginScreen> { final TextEditingController _emailController = TextEditingController(); final TextEditingController _passwordController = TextEditingController(); bool _isLoading = false; @override void dispose() { super.dispose(); _emailController.dispose(); _passwordController.dispose(); } void loginUser() async { setState(() { _isLoading = true; }); String res = await AuthMethods().loginUser( email: _emailController.text, password: _passwordController.text); if (res == 'success') { //Move to homescreen Navigator.of(context).pushAndRemoveUntil( MaterialPageRoute( builder: (context) => const ResponsiveLayout( webScreenLayout: WebSreenLayout(), mobileScreenLayout: MobileScreenLayout()), ), (route) => false); setState(() { _isLoading = false; }); } else { setState(() { _isLoading = false; }); showSnackBar(res, context); } setState(() { _isLoading = false; }); } void navigateToSignup() { Navigator.of(context).push(MaterialPageRoute( builder: (context) => const SignUpScreen(), )); } @override Widget build(BuildContext context) { return Scaffold( body: SafeArea( child: Container( padding: MediaQuery.of(context).size.width > webScreenSize ? EdgeInsets.symmetric( horizontal: MediaQuery.of(context).size.width / 3) : const EdgeInsets.symmetric(horizontal: 32), width: double.infinity, child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ Flexible(child: Container(), flex: 2), //SVG image SvgPicture.asset( "assets/ic_instagram.svg", color: Theme.of(context).primaryColor, height: 64, ), const SizedBox(height: 64), //Text filed input for email TextFieldInput( textEditingController: _emailController, hintText: "Enter your email", textInputType: TextInputType.emailAddress), //Text filed input for password const SizedBox(height: 24), TextFieldInput( textEditingController: _passwordController, hintText: "Enter your password", textInputType: TextInputType.text, isPass: true, ), const SizedBox(height: 24), //Button Login InkWell( onTap: () => loginUser(), child: Container( child: _isLoading ? const Center( child: CircularProgressIndicator( color: primaryColor, ), ) : const Text("Login"), width: double.infinity, alignment: Alignment.center, padding: const EdgeInsets.symmetric(vertical: 12), decoration: const ShapeDecoration( shape: RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(4))), color: blueColor), ), ), const SizedBox(height: 12), Flexible(child: Container(), flex: 2), //Transitioning to Signing Up Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Container( child: const Text("Don't have an account?"), padding: const EdgeInsets.symmetric(vertical: 8), ), GestureDetector( onTap: () => navigateToSignup(), child: Container( child: const Text( " Sign up.", style: TextStyle(fontWeight: FontWeight.bold), ), padding: const EdgeInsets.symmetric(vertical: 8), ), ) ], ), const SizedBox(height: 12), ], ), )), ); } }
0
mirrored_repositories/Flutter-Instagram-clone-App/lib
mirrored_repositories/Flutter-Instagram-clone-App/lib/providers/user_provider.dart
import 'package:flutter/material.dart'; import 'package:flutter_instagram_app/model/users.dart'; import 'package:flutter_instagram_app/resources/auth_methods.dart'; class UserProvider with ChangeNotifier { User? _user; //Must be private variable tp prevent bugs final AuthMethods _authMethods = AuthMethods(); User get getUser => _user!; Future<void> refreshUser() async { User user = await _authMethods.getUserDetails(); _user = user; notifyListeners(); } }
0
mirrored_repositories/Flutter-Instagram-clone-App
mirrored_repositories/Flutter-Instagram-clone-App/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_instagram_app/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/flutterspotifyui
mirrored_repositories/flutterspotifyui/lib/main.dart
import 'dart:io'; import 'package:desktop_window/desktop_window.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_spotify_ui/data/data.dart'; import 'package:flutter_spotify_ui/models/current_track_model.dart'; import 'package:flutter_spotify_ui/screens/playlist_screen.dart'; import 'package:flutter_spotify_ui/widgets/widgets.dart'; import 'package:provider/provider.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); if (!kIsWeb && (Platform.isMacOS || Platform.isLinux || Platform.isWindows)) { await DesktopWindow.setMinWindowSize(const Size(600, 800)); } runApp( ChangeNotifierProvider( create: (context) => CurrentTrackModel(), child: MyApp(), ), ); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Spotify UI', debugShowCheckedModeBanner: false, darkTheme: ThemeData( brightness: Brightness.dark, appBarTheme: const AppBarTheme(backgroundColor: Colors.black), scaffoldBackgroundColor: const Color(0xFF121212), backgroundColor: const Color(0xFF121212), primaryColor: Colors.black, accentColor: const Color(0xFF1DB954), iconTheme: const IconThemeData().copyWith(color: Colors.white), fontFamily: 'Montserrat', textTheme: TextTheme( headline2: const TextStyle( color: Colors.white, fontSize: 32.0, fontWeight: FontWeight.bold, ), headline4: TextStyle( fontSize: 12.0, color: Colors.grey[300], fontWeight: FontWeight.w500, letterSpacing: 2.0, ), bodyText1: TextStyle( color: Colors.grey[300], fontSize: 14.0, fontWeight: FontWeight.w600, letterSpacing: 1.0, ), bodyText2: TextStyle( color: Colors.grey[300], letterSpacing: 1.0, ), ), ), home: Shell(), ); } } class Shell extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: Column( children: [ Expanded( child: Row( children: [ if (MediaQuery.of(context).size.width > 800) SideMenu(), const Expanded( child: PlaylistScreen(playlist: lofihiphopPlaylist), ), ], ), ), CurrentTrack(), ], ), ); } }
0
mirrored_repositories/flutterspotifyui/lib
mirrored_repositories/flutterspotifyui/lib/widgets/current_track.dart
import 'package:flutter/material.dart'; import 'package:flutter_spotify_ui/models/current_track_model.dart'; import 'package:provider/provider.dart'; class CurrentTrack extends StatelessWidget { @override Widget build(BuildContext context) { return Container( height: 84.0, width: double.infinity, color: Colors.black87, child: Padding( padding: const EdgeInsets.all(12.0), child: Row( children: [ _TrackInfo(), const Spacer(), _PlayerControls(), const Spacer(), if (MediaQuery.of(context).size.width > 800) _MoreControls(), ], ), ), ); } } class _TrackInfo extends StatelessWidget { @override Widget build(BuildContext context) { final selected = context.watch<CurrentTrackModel>().selected; if (selected == null) return const SizedBox.shrink(); return Row( children: [ Image.asset( 'assets/lofigirl.jpg', height: 60.0, width: 60.0, fit: BoxFit.cover, ), const SizedBox(width: 12.0), Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( selected.title, style: Theme.of(context).textTheme.bodyText1, ), const SizedBox(height: 4.0), Text( selected.artist, style: Theme.of(context) .textTheme .subtitle1! .copyWith(color: Colors.grey[300], fontSize: 12.0), ) ], ), const SizedBox(width: 12.0), IconButton( icon: const Icon(Icons.favorite_border), onPressed: () {}, ), ], ); } } class _PlayerControls extends StatelessWidget { @override Widget build(BuildContext context) { final selected = context.watch<CurrentTrackModel>().selected; return Column( children: [ Row( children: [ IconButton( padding: const EdgeInsets.only(), icon: const Icon(Icons.shuffle), iconSize: 20.0, onPressed: () {}, ), IconButton( padding: const EdgeInsets.only(), icon: const Icon(Icons.skip_previous_outlined), iconSize: 20.0, onPressed: () {}, ), IconButton( padding: const EdgeInsets.only(), icon: const Icon(Icons.play_circle_outline), iconSize: 34.0, onPressed: () {}, ), IconButton( padding: const EdgeInsets.only(), icon: const Icon(Icons.skip_next_outlined), iconSize: 20.0, onPressed: () {}, ), IconButton( padding: const EdgeInsets.only(), icon: const Icon(Icons.repeat), iconSize: 20.0, onPressed: () {}, ), ], ), const SizedBox(height: 4.0), Row( children: [ Text('0:00', style: Theme.of(context).textTheme.caption), const SizedBox(width: 8.0), Container( height: 5.0, width: MediaQuery.of(context).size.width * 0.3, decoration: BoxDecoration( color: Colors.grey[800], borderRadius: BorderRadius.circular(2.5), ), ), const SizedBox(width: 8.0), Text( selected?.duration ?? '0:00', style: Theme.of(context).textTheme.caption, ), ], ), ], ); } } class _MoreControls extends StatelessWidget { @override Widget build(BuildContext context) { return Row( children: [ IconButton( icon: const Icon(Icons.devices_outlined), iconSize: 20.0, onPressed: () {}, ), Row( children: [ IconButton( icon: const Icon(Icons.volume_up_outlined), onPressed: () {}, ), Container( height: 5.0, width: 70.0, decoration: BoxDecoration( color: Colors.grey[800], borderRadius: BorderRadius.circular(2.5), ), ), ], ), IconButton( icon: const Icon(Icons.fullscreen_outlined), onPressed: () {}, ), ], ); } }
0
mirrored_repositories/flutterspotifyui/lib
mirrored_repositories/flutterspotifyui/lib/widgets/playlist_header.dart
import 'package:flutter/material.dart'; import 'package:flutter_spotify_ui/data/data.dart'; class PlaylistHeader extends StatelessWidget { final Playlist playlist; const PlaylistHeader({ Key? key, required this.playlist, }) : super(key: key); @override Widget build(BuildContext context) { return Column( children: [ Row( children: [ Image.asset( playlist.imageURL, height: 200.0, width: 200.0, fit: BoxFit.cover, ), const SizedBox(width: 16.0), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'PLAYLIST', style: Theme.of(context) .textTheme .overline! .copyWith(fontSize: 12.0), ), const SizedBox(height: 12.0), Text(playlist.name, style: Theme.of(context).textTheme.headline2), const SizedBox(height: 16.0), Text( playlist.description, style: Theme.of(context).textTheme.subtitle1, ), const SizedBox(height: 16.0), Text( 'Created by ${playlist.creator} • ${playlist.songs.length} songs, ${playlist.duration}', style: Theme.of(context).textTheme.subtitle1, ), ], ), ), ], ), const SizedBox(height: 20.0), _PlaylistButtons(followers: playlist.followers), ], ); } } class _PlaylistButtons extends StatelessWidget { final String followers; const _PlaylistButtons({ Key? key, required this.followers, }) : super(key: key); @override Widget build(BuildContext context) { return Row( children: [ TextButton( style: TextButton.styleFrom( padding: const EdgeInsets.symmetric( vertical: 20.0, horizontal: 48.0, ), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20.0), ), backgroundColor: Theme.of(context).accentColor, primary: Theme.of(context).iconTheme.color, textStyle: Theme.of(context) .textTheme .caption! .copyWith(fontSize: 12.0, letterSpacing: 2.0), ), onPressed: () {}, child: const Text('PLAY'), ), const SizedBox(width: 8.0), IconButton( icon: const Icon(Icons.favorite_border), iconSize: 30.0, onPressed: () {}, ), IconButton( icon: const Icon(Icons.more_horiz), iconSize: 30.0, onPressed: () {}, ), const Spacer(), Text( 'FOLLOWERS\n$followers', style: Theme.of(context).textTheme.overline!.copyWith(fontSize: 12.0), textAlign: TextAlign.right, ) ], ); } }
0
mirrored_repositories/flutterspotifyui/lib
mirrored_repositories/flutterspotifyui/lib/widgets/widgets.dart
export 'side_menu.dart'; export 'playlist_header.dart'; export 'tracks_list.dart'; export 'current_track.dart';
0
mirrored_repositories/flutterspotifyui/lib
mirrored_repositories/flutterspotifyui/lib/widgets/side_menu.dart
import 'package:flutter/material.dart'; import 'package:flutter_spotify_ui/data/data.dart'; class SideMenu extends StatelessWidget { @override Widget build(BuildContext context) { return Container( height: double.infinity, width: 280.0, color: Theme.of(context).primaryColor, child: Column( children: [ Row( children: [ Padding( padding: const EdgeInsets.all(16.0), child: Image.asset( 'assets/spotify_logo.png', height: 55.0, filterQuality: FilterQuality.high, ), ), ], ), _SideMenuIconTab( iconData: Icons.home, title: 'Home', onTap: () {}, ), _SideMenuIconTab( iconData: Icons.search, title: 'Search', onTap: () {}, ), _SideMenuIconTab( iconData: Icons.audiotrack, title: 'Radio', onTap: () {}, ), const SizedBox(height: 12.0), _LibraryPlaylists(), ], ), ); } } class _SideMenuIconTab extends StatelessWidget { final IconData iconData; final String title; final VoidCallback onTap; const _SideMenuIconTab({ Key? key, required this.iconData, required this.title, required this.onTap, }) : super(key: key); @override Widget build(BuildContext context) { return ListTile( leading: Icon( iconData, color: Theme.of(context).iconTheme.color, size: 28.0, ), title: Text( title, style: Theme.of(context).textTheme.bodyText1, overflow: TextOverflow.ellipsis, ), onTap: onTap, ); } } class _LibraryPlaylists extends StatefulWidget { @override __LibraryPlaylistsState createState() => __LibraryPlaylistsState(); } class __LibraryPlaylistsState extends State<_LibraryPlaylists> { ScrollController? _scrollController; @override void initState() { super.initState(); _scrollController = ScrollController(); } @override void dispose() { _scrollController?.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Expanded( child: Scrollbar( isAlwaysShown: true, controller: _scrollController, child: ListView( controller: _scrollController, padding: const EdgeInsets.symmetric(vertical: 12.0), physics: const ClampingScrollPhysics(), children: [ Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.symmetric( vertical: 8.0, horizontal: 16.0, ), child: Text( 'YOUR LIBRARY', style: Theme.of(context).textTheme.headline4, overflow: TextOverflow.ellipsis, ), ), ...yourLibrary .map((e) => ListTile( dense: true, title: Text( e, style: Theme.of(context).textTheme.bodyText2, overflow: TextOverflow.ellipsis, ), onTap: () {}, )) .toList(), ], ), const SizedBox(height: 24.0), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.symmetric( vertical: 8.0, horizontal: 16.0, ), child: Text( 'PLAYLISTS', style: Theme.of(context).textTheme.headline4, overflow: TextOverflow.ellipsis, ), ), ...playlists .map((e) => ListTile( dense: true, title: Text( e, style: Theme.of(context).textTheme.bodyText2, overflow: TextOverflow.ellipsis, ), onTap: () {}, )) .toList(), ], ) ], ), ), ); } }
0
mirrored_repositories/flutterspotifyui/lib
mirrored_repositories/flutterspotifyui/lib/widgets/tracks_list.dart
import 'package:flutter/material.dart'; import 'package:flutter_spotify_ui/models/current_track_model.dart'; import 'package:provider/provider.dart'; import 'package:flutter_spotify_ui/data/data.dart'; class TracksList extends StatelessWidget { final List<Song> tracks; const TracksList({ Key? key, required this.tracks, }) : super(key: key); @override Widget build(BuildContext context) { return DataTable( headingTextStyle: Theme.of(context).textTheme.overline!.copyWith(fontSize: 12.0), dataRowHeight: 54.0, showCheckboxColumn: false, columns: const [ DataColumn(label: Text('TITLE')), DataColumn(label: Text('ARTIST')), DataColumn(label: Text('ALBUM')), DataColumn(label: Icon(Icons.access_time)), ], rows: tracks.map((e) { final selected = context.watch<CurrentTrackModel>().selected?.id == e.id; final textStyle = TextStyle( color: selected ? Theme.of(context).accentColor : Theme.of(context).iconTheme.color, ); return DataRow( cells: [ DataCell( Text(e.title, style: textStyle), ), DataCell( Text(e.artist, style: textStyle), ), DataCell( Text(e.album, style: textStyle), ), DataCell( Text(e.duration, style: textStyle), ), ], selected: selected, onSelectChanged: (_) => context.read<CurrentTrackModel>().selectTrack(e), ); }).toList(), ); } }
0
mirrored_repositories/flutterspotifyui/lib
mirrored_repositories/flutterspotifyui/lib/models/current_track_model.dart
import 'package:flutter/material.dart'; import 'package:flutter_spotify_ui/data/data.dart'; class CurrentTrackModel extends ChangeNotifier { Song? selected; void selectTrack(Song track) { selected = track; notifyListeners(); } }
0
mirrored_repositories/flutterspotifyui/lib
mirrored_repositories/flutterspotifyui/lib/data/data.dart
const yourLibrary = [ 'Made For You', 'Recently Played', 'Liked Songs', 'Albums', 'Artists', 'Podcasts', ]; const playlists = [ 'Today\'s Top Hits', 'Discover Weekly', 'Release Radar', 'Chill', 'Background', 'lofi hip hop music - beats to relax/study to', 'Vibes Right Now', 'Time Capsule', 'On Repeat', 'Summer Rewind', 'Dank Doggo Tunes', 'Sleepy Doge', ]; class Song { final String id; final String title; final String artist; final String album; final String duration; const Song({ required this.id, required this.title, required this.artist, required this.album, required this.duration, }); } const _lofihiphopMusic = [ Song( id: '0', title: 'Snowman', artist: 'WYS', album: '1 Am. Study Session', duration: '3:15', ), Song( id: '1', title: 'Healthy Distraction', artist: 'less.people', album: 'One Day It\'s Over', duration: '2:18', ), Song( id: '2', title: 'Far Away', artist: 'Mila Coolness', album: 'Silent River', duration: '2:39', ), Song( id: '3', title: 'Call You Soon', artist: 'Louk, Glimlip', album: 'Can We Talk', duration: '2:35', ), Song( id: '4', title: 'Winter Sun', artist: 'Bcalm, Banks', album: 'Feelings', duration: '2:15', ), Song( id: '5', title: 'Hope', artist: 'No Spirit', album: 'Memories We Made', duration: '1:57', ), Song( id: '6', title: 'A Better Place', artist: 'Project AER, cxit.', album: 'Growth Patterns', duration: '2:00', ), Song( id: '7', title: 'Misty Dawn', artist: 'BluntOne', album: 'Autumn in Budapest', duration: '2:34', ), Song( id: '8', title: 'Hourglass', artist: 'Thaehan', album: 'Hourglass', duration: '1:43', ), Song( id: '9', title: 'After Sunset', artist: 'Project AER, WYS', album: '3 Am. Study Session', duration: '2:41', ), Song( id: '10', title: 'Child', artist: 'Ambulo', album: 'Polar', duration: '2:12', ), Song( id: '11', title: 'Arizona Zero', artist: 'WYS, Sweet Medicine', album: 'Evermore', duration: '2:31', ), ]; class Playlist { final String id; final String name; final String imageURL; final String description; final String creator; final String duration; final String followers; final List<Song> songs; const Playlist({ required this.id, required this.name, required this.imageURL, required this.description, required this.creator, required this.duration, required this.followers, required this.songs, }); } const lofihiphopPlaylist = Playlist( id: '5-playlist', name: 'lofi hip hop music - beats to relax/study to', imageURL: 'assets/lofigirl.jpg', description: 'A daily selection of chill beats - perfect to help you relax & study 📚', creator: 'Lofi Girl', duration: '28 min', followers: '5,351,685', songs: _lofihiphopMusic, );
0
mirrored_repositories/flutterspotifyui/lib
mirrored_repositories/flutterspotifyui/lib/screens/playlist_screen.dart
import 'package:flutter/material.dart'; import 'package:flutter_spotify_ui/data/data.dart'; import 'package:flutter_spotify_ui/widgets/widgets.dart'; class PlaylistScreen extends StatefulWidget { final Playlist playlist; const PlaylistScreen({ Key? key, required this.playlist, }) : super(key: key); @override _PlaylistScreenState createState() => _PlaylistScreenState(); } class _PlaylistScreenState extends State<PlaylistScreen> { ScrollController? _scrollController; @override void initState() { super.initState(); _scrollController = ScrollController(); } @override void dispose() { _scrollController?.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( extendBodyBehindAppBar: true, appBar: AppBar( backgroundColor: Colors.transparent, elevation: 0, leadingWidth: 140.0, leading: Padding( padding: const EdgeInsets.symmetric(horizontal: 16.0), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ InkWell( customBorder: const CircleBorder(), onTap: () {}, child: Container( padding: const EdgeInsets.all(6.0), decoration: const BoxDecoration( color: Colors.black26, shape: BoxShape.circle, ), child: const Icon(Icons.chevron_left, size: 28.0), ), ), const SizedBox(width: 16.0), InkWell( customBorder: const CircleBorder(), onTap: () {}, child: Container( padding: const EdgeInsets.all(6.0), decoration: const BoxDecoration( color: Colors.black26, shape: BoxShape.circle, ), child: const Icon(Icons.chevron_right, size: 28.0), ), ), ], ), ), actions: [ TextButton.icon( style: TextButton.styleFrom( primary: Theme.of(context).iconTheme.color, ), onPressed: () {}, icon: const Icon( Icons.account_circle_outlined, size: 30.0, ), label: const Text('Ravindra Nakarni'), ), const SizedBox(width: 8.0), IconButton( padding: const EdgeInsets.only(), icon: const Icon(Icons.keyboard_arrow_down, size: 30.0), onPressed: () {}, ), const SizedBox(width: 20.0), ], ), body: Container( width: double.infinity, decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [ const Color(0xFFAF1018), Theme.of(context).backgroundColor, ], stops: const [0, 0.3], ), ), child: Scrollbar( isAlwaysShown: true, controller: _scrollController, child: ListView( controller: _scrollController, padding: const EdgeInsets.symmetric( horizontal: 20.0, vertical: 60.0, ), children: [ PlaylistHeader(playlist: widget.playlist), TracksList(tracks: widget.playlist.songs), ], ), ), ), ); } }
0
mirrored_repositories/flutterspotifyui
mirrored_repositories/flutterspotifyui/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_spotify_ui/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/Qify
mirrored_repositories/Qify/lib/register.dart
import 'dart:io'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_storage/firebase_storage.dart'; import 'package:flutter/material.dart'; import 'package:image_cropper/image_cropper.dart'; import 'package:image_picker/image_picker.dart'; import 'package:modal_progress_hud/modal_progress_hud.dart'; import 'package:provider/provider.dart'; import 'package:qifyadmin/verification_screen.dart'; import 'current_user.dart'; import 'home_screen.dart'; class Register extends StatefulWidget { @override _RegisterState createState() => _RegisterState(); } class _RegisterState extends State<Register> { TextEditingController _addressController = TextEditingController(); TextEditingController _phoneController = TextEditingController(); final FirebaseAuth _auth = FirebaseAuth.instance; final Firestore _firestore = Firestore.instance; final Firestore _db = Firestore.instance; FirebaseUser _user; var _mailController = TextEditingController(); var _passwordController = TextEditingController(); var _nameController = TextEditingController(); var _civilIdController = TextEditingController(); var _ageController = TextEditingController(); var _specialityController = TextEditingController(); final FocusNode _mailFocus = FocusNode(); final FocusNode _passwordFocus = FocusNode(); String errorText; String mailErrorText; bool isSwitched = false; bool validateMail = false; bool validatePassword = false; bool _loading = false; _fieldFocusChange(BuildContext context, FocusNode currentFocus,FocusNode nextFocus) { currentFocus.unfocus(); FocusScope.of(context).requestFocus(nextFocus); } File _image; String _uploadedFileURL; String imgUrl; var croppedImage; Future getImage() async { setState(() { _loading = true; }); var image = await ImagePicker.pickImage(source: ImageSource.gallery); if (image != null) { croppedImage = await ImageCropper.cropImage( sourcePath: image.path, aspectRatio: CropAspectRatio(ratioX: 1, ratioY: 1), compressQuality: 100, maxWidth: 512, maxHeight: 512, compressFormat: ImageCompressFormat.jpg, androidUiSettings: AndroidUiSettings( toolbarColor: Colors.deepPurple, toolbarTitle: 'Crop Image', backgroundColor: Colors.white, ), ); setState(() { _loading = false; _image = croppedImage; print('image: $croppedImage'); }); } else { setState(() { _loading = false; }); } } Future uploadFile(c) async { StorageReference storageReference = FirebaseStorage.instance.ref().child( 'profile/${_mailController.text}'); StorageUploadTask uploadTask = storageReference.putFile(croppedImage); await uploadTask.onComplete; print('File Uploaded'); storageReference.getDownloadURL().then((fileURL) async{ await signUp(c, fileURL); setState(() { _uploadedFileURL = fileURL; imgUrl = fileURL; }); }); } Future signUp(c, url) async{ setState(() { _loading=true; }); try { if (_mailController.text==null || _mailController.text.length < 1) { setState(() { validateMail=true; mailErrorText='Enter a valid e-mail!'; _loading=false; }); } else if (_passwordController.text==null || _passwordController.text.length < 8) { setState(() { validatePassword=true; validateMail=false; errorText='Password should contain at least 8 characters!'; _loading=false; }); } else { setState(() { validatePassword=false; validateMail=false; }); var user = await _auth.createUserWithEmailAndPassword(email: _mailController.text, password: _passwordController.text); setState(() { _loading=false; }); if (user != null) { _user=await _auth.currentUser(); await _firestore .collection('users') .document(_user.uid) .setData({ 'uid': _user.uid, 'displayName': _nameController.text, 'civilId': _civilIdController.text, 'age':_ageController.text, 'phone':_phoneController.text, 'address':_addressController.text, 'speciality':_specialityController.text, 'isDoctor':isSwitched, 'isVerified':isSwitched?false:null, 'profile':url, 'indexList':isSwitched?indexing(_nameController.text):null, 'specialityIndex':isSwitched?indexing(_specialityController.text):null, 'timestamp': FieldValue.serverTimestamp(), }); await Provider.of<CurrentUser>(c, listen: false).getCurrentUser(); Navigator.of(context).popUntil((route) => route.isFirst); if (isSwitched) { Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context) { return VerificationScreen(false); })); } else { Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context) { return HomePage(); })); } } } } catch (PlatformException) { setState(() { _loading=false; errorText='Check your email/password combination!'; mailErrorText=null; }); print(PlatformException.code); switch (PlatformException.code) { case "ERROR_INVALID_EMAIL": setState(() { mailErrorText = "Your email address appears to be malformed."; errorText=null; validateMail=true; validatePassword=false; }); break; case "ERROR_EMAIL_ALREADY_IN_USE": setState(() { mailErrorText = "The email address is already in use by another account."; errorText=null; validateMail=true; validatePassword=false; }); break; case "ERROR_USER_DISABLED": setState(() { mailErrorText = "User with this email has been disabled."; errorText=null; validateMail=true; validatePassword=false; }); break; case "ERROR_TOO_MANY_REQUESTS": setState(() { errorText = "Too many requests. Try again later."; mailErrorText=null; validateMail=false; validatePassword=true; }); break; case "ERROR_NETWORK_REQUEST_FAILED": setState(() { errorText='The internet connection appears to be offline'; mailErrorText=null; validateMail=false; validatePassword=true; }); break; } } } List indexing(name) { List<String> splitList = name.split(" "); List<String> indexList=[]; for (var i=0; i<splitList.length; i++) { for(var y=1; y<splitList[i].length + 1; y++) { indexList.add(splitList[i].substring(0, y).toLowerCase()); } } return indexList; } @override Widget build(BuildContext context) { return GestureDetector( onTap: () { FocusScope.of(context).unfocus(); }, child: ModalProgressHUD( inAsyncCall: _loading, child: Scaffold( appBar: AppBar( backgroundColor: Color(0xFF0A0E21), ), backgroundColor: Color(0xFF0A0E21), body: Container( child: ListView( shrinkWrap: true, padding: const EdgeInsets.all(20.0), children: <Widget>[ Text( ' Registration', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 40, color: Colors.white, fontFamily: 'Notable', ), ), SizedBox( height: 20, ), Visibility( visible: isSwitched, child: Column( children: <Widget>[ Padding( padding: EdgeInsets.only(top: 20), child: CircleAvatar( backgroundColor: Colors.white, radius: 50, child: ClipRRect( borderRadius: BorderRadius.circular(50), child: _image != null ? Image.file( _image, fit: BoxFit.cover, ) : Icon( Icons.supervised_user_circle, size: 50, color: Colors.deepPurple, ), ), ), ), FlatButton( child: Text( 'Change profile photo', style: TextStyle(color: Colors.white, fontSize: 15), ), onPressed: () { getImage(); }, ), SizedBox( height: 10, ), ], ), ), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('Patient', style: TextStyle(color: Colors.white),), Switch( value: isSwitched, onChanged: (value) { setState(() { isSwitched = value; }); }, activeTrackColor: Colors.deepPurpleAccent, activeColor: Colors.deepPurple, ), Text('Doctor', style: TextStyle(color: Colors.white),), ], ), Container( padding: EdgeInsets.fromLTRB(10, 10, 10, 0), child: TextField( controller: _nameController, textInputAction: TextInputAction.next, onSubmitted: (_) => FocusScope.of(context).nextFocus(), style: TextStyle( color: Colors.white, ), //controller: passwordController, decoration: InputDecoration( enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(20.0)), borderSide: BorderSide(width: 1,color: Colors.white10), ), prefixIcon: Icon(Icons.perm_contact_calendar, color: Colors.white), border: OutlineInputBorder( borderRadius: BorderRadius.circular(20.0), ), //labelText: 'Password', hintText: 'Name', hintStyle: TextStyle(color: Colors.grey), ), ), ), Container( padding: EdgeInsets.fromLTRB(10, 10, 10, 0), child: TextField( controller: _ageController, textInputAction: TextInputAction.next, onSubmitted: (_) => FocusScope.of(context).nextFocus(), style: TextStyle( color: Colors.white, ), keyboardType: TextInputType.number, //controller: passwordController, decoration: InputDecoration( enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(20.0)), borderSide: BorderSide(width: 1,color: Colors.white10), ), prefixIcon: Icon(Icons.cake, color: Colors.white), border: OutlineInputBorder( borderSide: BorderSide(color: Colors.white), borderRadius: BorderRadius.circular(20.0), ), //labelText: 'Password', hintText: 'Age', hintStyle: TextStyle(color: Colors.grey), ), ), ), Container( padding: EdgeInsets.fromLTRB(10, 10, 10, 0), child: TextField( controller: _phoneController, textInputAction: TextInputAction.next, onSubmitted: (_) => FocusScope.of(context).nextFocus(), style: TextStyle( color: Colors.white, ), keyboardType: TextInputType.number, //controller: passwordController, decoration: InputDecoration( enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(20.0)), borderSide: BorderSide(width: 1,color: Colors.white10), ), prefixIcon: Icon(Icons.phone, color: Colors.white), border: OutlineInputBorder( borderSide: BorderSide(color: Colors.white), borderRadius: BorderRadius.circular(20.0), ), //labelText: 'Password', hintText: 'Phone Number', hintStyle: TextStyle(color: Colors.grey), ), ), ), Container( padding: EdgeInsets.fromLTRB(10, 10, 10, 0), child: TextField( controller: _addressController, textInputAction: TextInputAction.next, onSubmitted: (_) => FocusScope.of(context).nextFocus(), style: TextStyle( color: Colors.white, ), //controller: passwordController, decoration: InputDecoration( enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(20.0)), borderSide: BorderSide(width: 1,color: Colors.white10), ), prefixIcon: Icon(Icons.markunread_mailbox, color: Colors.white), border: OutlineInputBorder( borderSide: BorderSide(color: Colors.white), borderRadius: BorderRadius.circular(20.0), ), //labelText: 'Password', hintText: 'Address', hintStyle: TextStyle(color: Colors.grey), ), ), ), Visibility( visible: isSwitched, child: Container( padding: EdgeInsets.fromLTRB(10, 10, 10, 0), child: TextField( controller: _specialityController, textInputAction: TextInputAction.next, onSubmitted: (_) => FocusScope.of(context).nextFocus(), style: TextStyle( color: Colors.white, ), keyboardType: TextInputType.number, //controller: passwordController, decoration: InputDecoration( enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(20.0)), borderSide: BorderSide(width: 1,color: Colors.white10), ), prefixIcon: Icon(Icons.content_paste, color: Colors.white), border: OutlineInputBorder( borderSide: BorderSide(color: Colors.white), borderRadius: BorderRadius.circular(20.0), ), //labelText: 'Password', hintText: 'Speciality', hintStyle: TextStyle(color: Colors.grey), ), ), ), ), Container( padding: EdgeInsets.fromLTRB(10, 10, 10, 0), child: TextField( controller: _mailController, focusNode: _mailFocus, keyboardType: TextInputType.emailAddress, textInputAction: TextInputAction.next, onSubmitted: (_) => FocusScope.of(context).nextFocus(), style: TextStyle( color: Colors.white, ), //controller: passwordController, decoration: InputDecoration( enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(20.0)), borderSide: BorderSide(width: 1,color: Colors.white10), ), border: OutlineInputBorder( borderRadius: BorderRadius.circular(20.0), ), prefixIcon: Icon(Icons.email, color: Colors.white), //labelText: 'Password', hintText: 'Email', errorText: validateMail ? mailErrorText : null, hintStyle: TextStyle(color: Colors.grey), ), ), ), Container( padding: EdgeInsets.fromLTRB(10, 10, 10, 0), child: TextField( style: TextStyle( color: Colors.white, ), controller: _passwordController, focusNode: _passwordFocus, obscureText: true, //controller: passwordController, decoration: InputDecoration( enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(20.0)), borderSide: BorderSide(width: 1,color: Colors.white10), ), prefixIcon: Icon(Icons.lock, color: Colors.white), border: OutlineInputBorder( borderRadius: BorderRadius.circular(20.0), ), //labelText: 'Password', hintText: 'Password', errorText: errorText, hintStyle: TextStyle(color: Colors.grey), ), textInputAction: TextInputAction.done, onSubmitted: (value) { signUp(context, null); }, ), ), SizedBox( height: 27, ), Container( height: 50, padding: EdgeInsets.fromLTRB(10, 0, 10, 0), child: RaisedButton( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20.0), //side: BorderSide(color: Colors.red) ), textColor: Colors.white, color: Color(0xFF4440D9), child: Text('Register'), onPressed: () async => await isSwitched?uploadFile(context):signUp(context, null), )), FlatButton( textColor: Colors.white, onPressed: () { Navigator.pop(context); }, child: Text( 'Already have an account? Go back!', style: TextStyle(fontSize: 16),), ), ], ), ), ), ), ); } }
0
mirrored_repositories/Qify
mirrored_repositories/Qify/lib/view_windows.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:qifyadmin/book_appointment.dart'; import 'package:qifyadmin/schedule_tile.dart'; import 'current_user.dart'; class ViewWindows extends StatefulWidget { final uid; final name; ViewWindows({this.name, this.uid}); @override _ViewWindowsState createState() => _ViewWindowsState(); } class _ViewWindowsState extends State<ViewWindows> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("${widget.name}'s available windows"), backgroundColor: Color(0xFF0A0E21), ), body: SafeArea( child: Consumer<CurrentUser>( builder: (context, userData, child) { return Padding( padding: EdgeInsets.symmetric(vertical: 10, horizontal: 10), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( 'Available Appointment Windows', style: TextStyle( fontSize: 20, fontWeight: FontWeight.bold, fontFamily: 'Helvetica Neue', letterSpacing: 0.2, ), ), SizedBox( height: 20, ), StreamBuilder<QuerySnapshot>( stream: Firestore.instance .collection('windows') // .orderBy('date') .where('uid', isEqualTo: widget.uid) .snapshots(), builder: (context, snapshot) { if (!snapshot.hasData || snapshot.data.documents.length == 0) { return Padding( padding: EdgeInsets.only(top: 15), child: Text( "We're getting your scheduled appointment windows ready!", style: TextStyle(fontSize: 16), ), ); } final windows = snapshot.data.documents; List<ScheduleTile> tiles = []; for (var window in windows) { final title = window.data['title']; final startTime = window.data['startTime']; final endTime = window.data['endTime']; final date = window.data['date']; final docID = window.documentID; print(window.data); tiles.add( ScheduleTile( title: title, startTime: startTime, endTime: endTime, date: date, docId: docID, onPress: () { Navigator.push(context, MaterialPageRoute(builder: (context) { return BookAppointment( docId: docID, ); })); }, ), ); } return Expanded( child: tiles.length != 0 ? ListView( children: tiles, ) : Padding( padding: EdgeInsets.symmetric(vertical: 10), child: Text('No appointment windows found'), ), ); }, ), SizedBox( height: 30, ), ], ), ); }, ), ), ); } }
0
mirrored_repositories/Qify
mirrored_repositories/Qify/lib/user_tile.dart
import 'package:flutter/material.dart'; class UserTile extends StatelessWidget { final String photoUrl; final String userName; final Function onPress; final bool request; final Function accept; final Function decline; UserTile( {this.photoUrl, this.userName, this.onPress, this.accept, this.decline, this.request = false}); @override Widget build(BuildContext context) { return ListTile( title: Row( children: <Widget>[ CircleAvatar( radius: 24, child: ClipRRect( borderRadius: BorderRadius.circular(50), child: photoUrl!=null?FadeInImage( image: NetworkImage(photoUrl), placeholder: AssetImage('images/placeholder.png'), ):Image.asset('images/placeholder.png'), ), ), SizedBox( width: 15, ), Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Row( children: <Widget>[ Text( '$userName', ), SizedBox( width: 10, ), ], ), Visibility( visible: request, child: Row( mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ GestureDetector( onTap: accept, child: CircleAvatar( radius: 18, backgroundColor: Color(0xFF0A0E21), child: Icon( Icons.check, color: Colors.white, ), ), ), SizedBox( width: 18, ), GestureDetector( onTap: decline, child: CircleAvatar( radius: 18, backgroundColor: Colors.grey.withOpacity(0.2), child: Icon( Icons.close, color: Colors.black54, ), ), ) ], ), ) ], ), ], ), onTap: onPress, ); } }
0
mirrored_repositories/Qify
mirrored_repositories/Qify/lib/book_appointment.dart
import 'dart:io'; import 'package:bot_toast/bot_toast.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_storage/firebase_storage.dart'; import 'package:flutter/material.dart'; import 'package:image_cropper/image_cropper.dart'; import 'package:image_picker/image_picker.dart'; import 'package:modal_progress_hud/modal_progress_hud.dart'; import 'package:provider/provider.dart'; import 'package:http/http.dart' as http; import 'current_user.dart'; class BookAppointment extends StatefulWidget { final String docId; BookAppointment({this.docId}); @override _BookAppointmentState createState() => _BookAppointmentState(); } class _BookAppointmentState extends State<BookAppointment> { bool inProgress = false; String text; String imgUrl; List groups; List groupNames; String groupId; double minPrice; double maxPrice; File postImage; TextEditingController textEditingController = TextEditingController(); TextEditingController minPriceController = TextEditingController(); TextEditingController maxPriceController = TextEditingController(); TextEditingController titleEditingController = TextEditingController(); String _uploadedFileURL; BottomNavigationBar navigationBar; Future uploadFile() async { StorageReference storageReference = FirebaseStorage.instance.ref().child( 'posts/${Provider.of<CurrentUser>(context, listen: false).loggedInUser.uid} ${DateTime.now().toIso8601String()}'); StorageUploadTask uploadTask = storageReference.putFile(postImage); await uploadTask.onComplete; print('File Uploaded'); storageReference.getDownloadURL().then((fileURL) async { await pushData(fileURL); setState(() { _uploadedFileURL = fileURL; imgUrl = fileURL; }); }); } Future pushData(url) async { try { if (((textEditingController.text == "" || textEditingController.text == null) && url == null)) { setState(() { inProgress = false; }); BotToast.showSimpleNotification(title: 'Nothing to post!'); } else { DocumentReference reference = await Firestore.instance.collection('appointments').add({ 'description': textEditingController.text, 'image': url != null ? url : null, 'appointmentStatus': 'Approval Pending', 'uid': Provider.of<CurrentUser>(context, listen: false).loggedInUser.uid, 'name': Provider.of<CurrentUser>(context, listen: false).displayName, 'doctorWindowID': widget.docId, 'time': FieldValue.serverTimestamp(), }); print(Provider.of<CurrentUser>(context, listen: false).loggedInUser.email); http.Response _response = await http .get("https://us-central1-qify-931a1.cloudfunctions.net/sendMail?dest=${Provider.of<CurrentUser>(context, listen: false).loggedInUser.email}"); if (_response.statusCode == 200) { print('sent'); } else { print("Something went wrong!"); } postImage = null; textEditingController.clear(); Navigator.pop(context); setState(() { inProgress = false; }); } } catch (e) { print(e); setState(() { inProgress = false; }); } } File _image; var croppedImage; Future getImage() async { setState(() { inProgress = true; }); var image = await ImagePicker.pickImage(source: ImageSource.gallery); if (image != null) { croppedImage = await ImageCropper.cropImage( sourcePath: image.path, aspectRatio: CropAspectRatio(ratioX: 16, ratioY: 9), compressQuality: 100, maxWidth: 512, maxHeight: 512, compressFormat: ImageCompressFormat.jpg, androidUiSettings: AndroidUiSettings( toolbarColor: Color(0xFF0A0E21), toolbarTitle: 'Crop Image', backgroundColor: Colors.white, ), ); setState(() { inProgress = false; _image = croppedImage; postImage = _image; print('image: $croppedImage'); }); } else { setState(() { inProgress = false; }); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Book Your Appointment'), backgroundColor: Color(0xFF0A0E21), ), body: GestureDetector( onTap: () { FocusScope.of(context).unfocus(); }, child: ModalProgressHUD( inAsyncCall: inProgress, child: SafeArea( child: SingleChildScrollView( child: Column( mainAxisSize: MainAxisSize.max, children: <Widget>[ Padding( padding: EdgeInsets.symmetric(horizontal: 15), child: TextField( textCapitalization: TextCapitalization.sentences, keyboardType: TextInputType.multiline, maxLines: null, controller: textEditingController, onChanged: (value) { setState(() { text = value; }); }, decoration: InputDecoration( border: InputBorder.none, focusedBorder: InputBorder.none, enabledBorder: InputBorder.none, errorBorder: InputBorder.none, disabledBorder: InputBorder.none, contentPadding: EdgeInsets.only( left: 15, bottom: 11, top: 11, right: 15), hintText: 'Problem Description', ), ), ), SizedBox( height: 15, ), Align( alignment: Alignment.centerLeft, child: Padding( padding: EdgeInsets.symmetric(horizontal: 13), child: Container( child: FlatButton( color: Color(0xFF0A0E21), child: Row( mainAxisSize: MainAxisSize.min, children: <Widget>[ Icon( Icons.camera, color: Colors.white, ), SizedBox( width: 10, ), Text( 'Pick Image', style: TextStyle( color: Colors.white, fontSize: 18, ), ), ], ), onPressed: () async { await getImage(); }), ), ), ), SizedBox( height: 10, ), Column( children: <Widget>[ SizedBox( height: 15, ), SizedBox( height: 15, ), Padding( padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10), child: Visibility( visible: postImage != null ? true : false, child: Stack( children: <Widget>[ Container( height: 256, width: 512, child: postImage != null ? ClipRRect( borderRadius: BorderRadius.all( Radius.circular(10)), child: Image.file( postImage, fit: BoxFit.cover, ), ) : null, decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(10)), ), ), Align( alignment: Alignment.topRight, child: Padding( padding: EdgeInsets.symmetric( vertical: 6, horizontal: 6), child: GestureDetector( onTap: () { setState(() { postImage = null; }); }, child: CircleAvatar( radius: 14, backgroundColor: Color(0x00000000), child: Icon(Icons.close, color: Colors.white), ), ), ), ), ], ), ), ), Align( alignment: Alignment.centerLeft, child: Padding( padding: EdgeInsets.symmetric(horizontal: 13), child: Container( child: FlatButton( color: Color(0xFF0A0E21), child: Row( //mainAxisSize: MainAxisSize.min, children: <Widget>[ Icon( Icons.add, color: Colors.white, ), SizedBox( width: 10, ), Text( 'Book your appointment', style: TextStyle( color: Colors.white, fontSize: 18, ), ), ], ), onPressed: () async { setState(() { inProgress = true; }); FocusScope.of(context).unfocus(); if (postImage != null) { await uploadFile(); } else { await pushData(null); } }), ), ), ), ], ), ], ), ), ), ), ), ); } }
0
mirrored_repositories/Qify
mirrored_repositories/Qify/lib/forward_windows.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:qifyadmin/book_appointment.dart'; import 'package:qifyadmin/schedule_tile.dart'; import 'current_user.dart'; class ForwardWindows extends StatefulWidget { final uid; final name; final docID; ForwardWindows({this.name, this.uid, this.docID}); @override _ForwardWindowsState createState() => _ForwardWindowsState(); } class _ForwardWindowsState extends State<ForwardWindows> { Future update(docID) async { DocumentReference doctorRef = Firestore.instance .document('appointments/' + widget.docID); await Firestore.instance .runTransaction((transaction) async { DocumentSnapshot freshSnap1 = await transaction.get(doctorRef); await transaction.update(freshSnap1.reference, { 'appointmentStatus': 'Forwarded to ${widget.name}', 'doctorWindowID': docID, }); }); Navigator.pop(context); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("${widget.name}'s available windows"), backgroundColor: Color(0xFF0A0E21), ), body: SafeArea( child: Consumer<CurrentUser>( builder: (context, userData, child) { return Padding( padding: EdgeInsets.symmetric(vertical: 10, horizontal: 10), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( 'Available Appointment Windows', style: TextStyle( fontSize: 20, fontWeight: FontWeight.bold, fontFamily: 'Helvetica Neue', letterSpacing: 0.2, ), ), SizedBox( height: 20, ), StreamBuilder<QuerySnapshot>( stream: Firestore.instance .collection('windows') // .orderBy('date') .where('uid', isEqualTo: widget.uid) .snapshots(), builder: (context, snapshot) { if (!snapshot.hasData || snapshot.data.documents.length == 0) { return Padding( padding: EdgeInsets.only(top: 15), child: Text( "We're getting your scheduled appointment windows ready!", style: TextStyle(fontSize: 16), ), ); } final windows = snapshot.data.documents; List<ScheduleTile> tiles = []; for (var window in windows) { final title = window.data['title']; final startTime = window.data['startTime']; final endTime = window.data['endTime']; final date = window.data['date']; final docID = window.documentID; print(window.data); tiles.add( ScheduleTile( title: title, startTime: startTime, endTime: endTime, date: date, docId: docID, onPress: () async { await update(docID); // print(docID); // print(widget.name); // print(widget.docID); }, ), ); } return Expanded( child: tiles.length != 0 ? ListView( children: tiles, ) : Padding( padding: EdgeInsets.symmetric(vertical: 10), child: Text('No appointment windows found'), ), ); }, ), SizedBox( height: 30, ), ], ), ); }, ), ), ); } }
0
mirrored_repositories/Qify
mirrored_repositories/Qify/lib/appointment_windows.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:modal_progress_hud/modal_progress_hud.dart'; import 'package:provider/provider.dart'; import 'package:qifyadmin/add_window.dart'; import 'package:qifyadmin/pending_requests.dart'; import 'package:qifyadmin/schedule_tile.dart'; import 'current_user.dart'; class AppointmentWindows extends StatefulWidget { @override _AppointmentWindowsState createState() => _AppointmentWindowsState(); } class _AppointmentWindowsState extends State<AppointmentWindows> { bool loading = false; @override Widget build(BuildContext context) { return ModalProgressHUD( inAsyncCall: loading, child: SafeArea( child: Consumer<CurrentUser>( builder: (context, userData, child) { return Padding( padding: EdgeInsets.symmetric(vertical: 10, horizontal: 10), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( 'Scheduled Appointment Windows', style: TextStyle( fontSize: 20, fontWeight: FontWeight.bold, fontFamily: 'Helvetica Neue', letterSpacing: 0.2, ), ), SizedBox( height: 20, ), StreamBuilder<QuerySnapshot>( stream: Firestore.instance .collection('windows') // .orderBy('date') .where('uid', isEqualTo: Provider.of<CurrentUser>(context, listen: false) .loggedInUser .uid) .snapshots(), builder: (context, snapshot) { if (!snapshot.hasData || snapshot.data.documents.length == 0) { return Padding( padding: EdgeInsets.only(top: 15), child: Text( "We're getting your scheduled appointment windows ready!", style: TextStyle(fontSize: 16), ), ); } final windows = snapshot.data.documents; List<ScheduleTile> tiles = []; for (var window in windows) { final title = window.data['title']; final startTime = window.data['startTime']; final endTime = window.data['endTime']; final date = window.data['date']; final docID = window.documentID; print(window.data); tiles.add( ScheduleTile( title: title, startTime: startTime, endTime: endTime, date: date, docId: docID, onPress: () { Navigator.push(context, MaterialPageRoute(builder: (context) { return PendingRequests(title: title, windowID: docID,); })); }, onLongPress: () { Navigator.push(context, MaterialPageRoute(builder: (context) { return AddWindow( title: title, startTime: startTime, endTime: endTime, date: date, docId: docID, editState: true, ); })); }), ); } return Expanded( child: tiles.length != 0 ? ListView( children: tiles, ) : Padding( padding: EdgeInsets.symmetric(vertical: 10), child: Text('No appointment windows found'), ), ); }, ), SizedBox( height: 30, ), ], ), ); }, ), ), ); } }
0
mirrored_repositories/Qify
mirrored_repositories/Qify/lib/forward_screen.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:qifyadmin/forward_windows.dart'; import 'package:qifyadmin/user_tile.dart'; import 'package:qifyadmin/view_windows.dart'; import 'current_user.dart'; String currentText = ""; class ForwardScreen extends StatefulWidget { final String docID; ForwardScreen({this.docID}); @override _ForwardScreenState createState() => _ForwardScreenState(); } class _ForwardScreenState extends State<ForwardScreen> { String placeholderText = 'Choose a doctor to forward the case'; bool searchState = false; Color c1 = Colors.grey; Color c2 = Colors.grey; Color activeC = Colors.pink; Color inactiveC = Colors.grey; String speciality = ''; @override Widget build(BuildContext context) { return GestureDetector( onTap: () { FocusScope.of(context).unfocus(); }, child: Scaffold( appBar: AppBar( title: Text('Forward Case'), backgroundColor: Color(0xFF0A0E21), ), backgroundColor: Colors.white, body: Consumer<CurrentUser>( builder: (context, userData, child) { return SafeArea( child: Column( children: <Widget>[ Padding( padding: EdgeInsets.only(top: 4, left: 4, right: 4), child: TextField( textCapitalization: TextCapitalization.sentences, decoration: InputDecoration( hintStyle: TextStyle(color: Colors.grey), hintText: 'Search', prefixIcon: Icon( Icons.search, color: Colors.black54, ), prefixStyle: TextStyle(color: Color(0xFF0A0E21)), contentPadding: EdgeInsets.only( top: 14.0, ), border: OutlineInputBorder( //borderRadius: BorderRadius.all(Radius.circular(32.0)), ), enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: Color(0xFF0A0E21), width: 1.0), ), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Color(0xFF0A0E21), width: 2.0), ), ), // decoration: kTextFieldDecoration.copyWith( // ), onChanged: (value) { placeholderText = 'No doctor found!'; setState(() { currentText = value.toLowerCase(); if (!searchState) { searchState = true; } else if (value == "") { searchState = false; } }); }, ), ), Padding( padding: EdgeInsets.symmetric(vertical: 8, horizontal: 10), child: Row( children: <Widget>[ Expanded( child: GestureDetector( onTap: () { setState(() { if (c1 == activeC) { c1 = inactiveC; speciality = ''; } else { c1 = activeC; c2 = inactiveC; speciality = 'false'; } }); }, child: Container( height: 40, child: Center( child: Text( 'Doctor', ), ), decoration: BoxDecoration( border: Border.all(color: c1), borderRadius: BorderRadius.all(Radius.circular(10)), ), ), ), ), SizedBox( width: 10, ), Expanded( child: GestureDetector( onTap: () { setState(() { if (c2 == activeC) { c2 = inactiveC; speciality = ''; } else { c1 = inactiveC; c2 = activeC; speciality = 'true'; } }); }, child: Container( height: 40, child: Center( child: Text( 'Speciality', ), ), decoration: BoxDecoration( border: Border.all(color: c2), borderRadius: BorderRadius.all(Radius.circular(10)), ), ), ), ), SizedBox( width: 10, ), ], ), ), StreamBuilder<QuerySnapshot>( stream: speciality == 'false' ? Firestore.instance .collection('users') .where('indexList', arrayContains: currentText) .snapshots() : Firestore.instance .collection('users') .where('specialityIndex', arrayContains: currentText) .snapshots(), builder: (context, snapshot) { if (!snapshot.hasData || snapshot.data.documents.length == 0) { return Padding( padding: EdgeInsets.only(top: 15), child: Text( '$placeholderText', style: TextStyle(fontSize: 16), ), ); } final users = snapshot.data.documents; List<UserTile> userList = []; for (var user in users) { final userName = user.data['displayName']; final photoUrl = user.data['profile']; final uid = user.documentID; userList.add( UserTile( photoUrl: photoUrl, userName: userName, onPress: () { Navigator.push(context, MaterialPageRoute(builder: (context) { return ForwardWindows( name: userName, uid: uid, docID: widget.docID, ); })); }, ), ); } return Expanded( child: userList.length != 0 ? ListView( children: userList, ) : Padding( padding: EdgeInsets.symmetric(vertical: 10), child: Text('No results found for $speciality'), ), ); }, ), ], ), ); }, ), ), ); } }
0
mirrored_repositories/Qify
mirrored_repositories/Qify/lib/doctor_screen.dart
import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:qifyadmin/add_window.dart'; import 'package:qifyadmin/appointment_windows.dart'; import 'login_screen.dart'; import 'dart:io'; class DoctorScreen extends StatelessWidget { static const String _title = 'Flutter Code Sample'; @override Widget build(BuildContext context) { return MaterialApp( title: _title, home: MyStatefulWidget(), ); } } class MyStatefulWidget extends StatefulWidget { MyStatefulWidget({Key key}) : super(key: key); @override _MyStatefulWidgetState createState() => _MyStatefulWidgetState(); } class _MyStatefulWidgetState extends State<MyStatefulWidget> { int _selectedIndex = 0; static const TextStyle optionStyle = TextStyle(fontSize: 30, fontWeight: FontWeight.bold); final List<Widget> _widgetOptions = <Widget>[ AppointmentWindows(), Text( 'Branches will be displayed here', style: optionStyle, ), Text( 'Services here', style: optionStyle, ), ]; void _onItemTapped(int index) { setState(() { _selectedIndex = index; }); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, appBar: AppBar( backgroundColor: Color(0xFF0A0E21), title: const Text('Qify', style: TextStyle( color: Colors.white, ),), actions: <Widget>[ // action button IconButton( icon: Icon(Icons.person), onPressed: () { Navigator.push( context, MaterialPageRoute(builder: (context) => LoginPage()), ); }, ), // action button IconButton( icon: Icon(Icons.exit_to_app), onPressed: () async { await FirebaseAuth.instance.signOut().then((value) { Navigator.of(context).popUntil((route) => route.isFirst); Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) { return LoginPage(); })); }); }, ), // overflow menu ], ), floatingActionButton: FloatingActionButton( backgroundColor: Colors.pink, child: Icon(Icons.add, color: Colors.white, size: 28,), onPressed: () { Navigator.push(context, MaterialPageRoute(builder: (context) { return AddWindow(editState: false,); })); }, ), body: Center( child: _widgetOptions.elementAt(_selectedIndex), ), bottomNavigationBar: BottomNavigationBar( backgroundColor: Color(0xFF0A0E21), items: const <BottomNavigationBarItem>[ BottomNavigationBarItem( backgroundColor: Colors.white, icon: Icon(Icons.content_paste ), title: Text('Windows'), ), BottomNavigationBarItem( icon: Icon(Icons.business), title: Text('Placeholder'), ), BottomNavigationBarItem( icon: Icon(Icons.help), title: Text('Placeholder'), ), ], unselectedItemColor: Colors.white, currentIndex: _selectedIndex, selectedItemColor: Colors.pink, onTap: _onItemTapped, ), ); } }
0
mirrored_repositories/Qify
mirrored_repositories/Qify/lib/video_call.dart
import 'dart:io'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:jitsi_meet/jitsi_meet.dart'; import 'package:jitsi_meet/jitsi_meeting_listener.dart'; import 'package:jitsi_meet/room_name_constraint.dart'; import 'package:jitsi_meet/room_name_constraint_type.dart'; import 'package:jitsi_meet/feature_flag/feature_flag_enum.dart'; import 'package:provider/provider.dart'; import 'current_user.dart'; class VideoCall extends StatefulWidget { @override _VideoCallState createState() => _VideoCallState(); } class _VideoCallState extends State<VideoCall> { static String username; static String mail; final serverText = TextEditingController(); final roomText = TextEditingController(text: "team-macbytes-quify"); final subjectText = TextEditingController(text: 'Quify'); final nameText = TextEditingController(); final emailText = TextEditingController(); final iosAppBarRGBAColor = TextEditingController(text: "#0080FF80");//transparent blue var isAudioOnly = true; var isAudioMuted = true; var isVideoMuted = true; @override void initState() { super.initState(); username= Provider.of<CurrentUser>(context, listen: false).displayName; mail= Provider.of<CurrentUser>(context, listen: false).loggedInUser.email; JitsiMeet.addListener(JitsiMeetingListener( onConferenceWillJoin: _onConferenceWillJoin, onConferenceJoined: _onConferenceJoined, onConferenceTerminated: _onConferenceTerminated, onError: _onError)); } @override void dispose() { super.dispose(); JitsiMeet.removeAllListeners(); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Qifiy'), backgroundColor: Color(0xFF0A0E21), ), body: Container( padding: const EdgeInsets.symmetric( horizontal: 16.0, ), child: SingleChildScrollView( child: Column( children: <Widget>[ SizedBox( height: 24.0, ), // TextField( // controller: serverText, // decoration: InputDecoration( // border: OutlineInputBorder(), // labelText: "Server URL", // hintText: "Hint: Leave empty for meet.jitsi.si"), // ), SizedBox( height: 16.0, ), TextField( controller: roomText, decoration: InputDecoration( border: OutlineInputBorder(), labelText: "Room", ), ), SizedBox( height: 16.0, ), TextField( controller: subjectText, decoration: InputDecoration( border: OutlineInputBorder(), labelText: "Subject", ), ), SizedBox( height: 16.0, ), TextField( controller: nameText, decoration: InputDecoration( border: OutlineInputBorder(), labelText: "Display Name", ), ), SizedBox( height: 16.0, ), TextField( controller: emailText, decoration: InputDecoration( border: OutlineInputBorder(), labelText: "Email", ), ), SizedBox( height: 16.0, ), // TextField( // controller: iosAppBarRGBAColor, // decoration: InputDecoration( // border: OutlineInputBorder(), // labelText: "AppBar Color(IOS only)", // hintText: "Hint: This HAS to be in HEX RGBA format"), // ), SizedBox( height: 16.0, ), CheckboxListTile( title: Text("Audio Only"), value: isAudioOnly, onChanged: _onAudioOnlyChanged, activeColor: Color(0xFF0A0E21), ), SizedBox( height: 16.0, ), CheckboxListTile( title: Text("Audio Muted"), value: isAudioMuted, onChanged: _onAudioMutedChanged, activeColor: Color(0xFF0A0E21), ), SizedBox( height: 16.0, ), CheckboxListTile( title: Text("Video Muted"), value: isVideoMuted, onChanged: _onVideoMutedChanged, activeColor: Color(0xFF0A0E21), ), Divider( height: 48.0, thickness: 2.0, ), SizedBox( height: 64.0, width: double.maxFinite, child: RaisedButton( onPressed: () { _joinMeeting(); }, child: Text( "Join Meeting", style: TextStyle(color: Colors.white), ), color: Color(0xFF0A0E21), ), ), SizedBox( height: 48.0, ), ], ), ), ), ), ); } _onAudioOnlyChanged(bool value) { setState(() { isAudioOnly = value; }); } _onAudioMutedChanged(bool value) { setState(() { isAudioMuted = value; }); } _onVideoMutedChanged(bool value) { setState(() { isVideoMuted = value; }); } _joinMeeting() async { String serverUrl = serverText.text?.trim()?.isEmpty ?? "" ? null : serverText.text; try { // Enable or disable any feature flag here // If feature flag are not provided, default values will be used // Full list of feature flags (and defaults) available in the README Map<FeatureFlagEnum, bool> featureFlags = { FeatureFlagEnum.WELCOME_PAGE_ENABLED : false, }; // Here is an example, disabling features for each platform if (Platform.isAndroid) { // Disable ConnectionService usage on Android to avoid issues (see README) featureFlags[FeatureFlagEnum.CALL_INTEGRATION_ENABLED] = false; } else if (Platform.isIOS) { // Disable PIP on iOS as it looks weird featureFlags[FeatureFlagEnum.PIP_ENABLED] = false; } // Define meetings options here var options = JitsiMeetingOptions() ..room = roomText.text ..serverURL = serverUrl ..subject = subjectText.text ..userDisplayName = nameText.text ..userEmail = emailText.text ..iosAppBarRGBAColor = iosAppBarRGBAColor.text ..audioOnly = isAudioOnly ..audioMuted = isAudioMuted ..videoMuted = isVideoMuted ..featureFlags.addAll({FeatureFlagEnum.INVITE_ENABLED:false}); debugPrint("JitsiMeetingOptions: $options"); await JitsiMeet.joinMeeting(options, listener: JitsiMeetingListener(onConferenceWillJoin: ({message}) { debugPrint("${options.room} will join with message: $message"); }, onConferenceJoined: ({message}) { debugPrint("${options.room} joined with message: $message"); }, onConferenceTerminated: ({message}) { debugPrint("${options.room} terminated with message: $message"); }), // by default, plugin default constraints are used //roomNameConstraints: new Map(), // to disable all constraints //roomNameConstraints: customContraints, // to use your own constraint(s) ); } catch (error) { debugPrint("error: $error"); } } static final Map<RoomNameConstraintType, RoomNameConstraint> customContraints = { RoomNameConstraintType.MAX_LENGTH : new RoomNameConstraint( (value) { return value.trim().length <= 50; }, "Maximum room name length should be 30."), RoomNameConstraintType.FORBIDDEN_CHARS : new RoomNameConstraint( (value) { return RegExp(r"[$€£]+", caseSensitive: false, multiLine: false).hasMatch(value) == false; }, "Currencies characters aren't allowed in room names."), }; void _onConferenceWillJoin({message}) { debugPrint("_onConferenceWillJoin broadcasted with message: $message"); } void _onConferenceJoined({message}) { debugPrint("_onConferenceJoined broadcasted with message: $message"); } void _onConferenceTerminated({message}) { debugPrint("_onConferenceTerminated broadcasted with message: $message"); } _onError(error) { debugPrint("_onError broadcasted: $error"); } }
0
mirrored_repositories/Qify
mirrored_repositories/Qify/lib/home_screen.dart
import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:qifyadmin/search_screen.dart'; import 'package:qifyadmin/view_history.dart'; import 'package:qifyadmin/view_profile.dart'; import 'login_screen.dart'; import 'dart:io'; /// This Widget is the main application widget. class HomePage extends StatelessWidget { static const String _title = 'Flutter Code Sample'; @override Widget build(BuildContext context) { return MaterialApp( title: _title, home: MyStatefulWidget(), ); } } class MyStatefulWidget extends StatefulWidget { MyStatefulWidget({Key key}) : super(key: key); @override _MyStatefulWidgetState createState() => _MyStatefulWidgetState(); } class _MyStatefulWidgetState extends State<MyStatefulWidget> { int _selectedIndex = 0; static const TextStyle optionStyle = TextStyle(fontSize: 30, fontWeight: FontWeight.bold); final List<Widget> _widgetOptions = <Widget>[ ViewHistory(), SearchScreen(), ]; void _onItemTapped(int index) { setState(() { _selectedIndex = index; }); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, appBar: AppBar( backgroundColor: Color(0xFF0A0E21), title: const Text('Qify', style: TextStyle( color: Colors.white, ),), actions: <Widget>[ // action button IconButton( icon: Icon(Icons.person), onPressed: () { Navigator.push( context, MaterialPageRoute(builder: (context) => ViewProfile()), ); }, ), // action button IconButton( icon: Icon(Icons.exit_to_app), onPressed: () async { await FirebaseAuth.instance.signOut().then((value) { Navigator.of(context).popUntil((route) => route.isFirst); Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) { return LoginPage(); })); }); }, ), // overflow menu ], ), body: Center( child: _widgetOptions.elementAt(_selectedIndex), ), bottomNavigationBar: BottomNavigationBar( backgroundColor: Color(0xFF0A0E21), items: const <BottomNavigationBarItem>[ BottomNavigationBarItem( backgroundColor: Colors.white, icon: Icon(Icons.calendar_today), title: Text('Appointments'), ), BottomNavigationBarItem( icon: Icon(Icons.search), title: Text('Search Doctors'), ), ], unselectedItemColor: Colors.white, currentIndex: _selectedIndex, selectedItemColor: Colors.pink, onTap: _onItemTapped, ), ); } }
0
mirrored_repositories/Qify
mirrored_repositories/Qify/lib/view_profile.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:modal_progress_hud/modal_progress_hud.dart'; import 'package:provider/provider.dart'; import 'package:qifyadmin/current_user.dart'; import 'package:qifyadmin/main.dart'; import 'package:qifyadmin/med_profile.dart'; import 'package:qifyadmin/video_call.dart'; import 'appointment_tile.dart'; class ViewProfile extends StatefulWidget { final uid; final name; ViewProfile({this.uid, this.name}); @override _ViewProfileState createState() => _ViewProfileState(); } class _ViewProfileState extends State<ViewProfile> { bool loading = false; @override Widget build(BuildContext context) { return ModalProgressHUD( inAsyncCall: loading, child: Scaffold( appBar: AppBar( title: Text('Medical Profile'), backgroundColor: Color(0xFF0A0E21), actions: <Widget>[ Visibility( visible: widget.name==null?false:true, child: IconButton( icon: Icon(Icons.videocam), onPressed: () { Navigator.push(context, MaterialPageRoute(builder: (context) { return VideoCall(); } )); }, ), ) ], ), body: Padding( padding: EdgeInsets.only(top: 10, left: 8, right: 8), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( widget.name==null?'${Provider.of<CurrentUser>(context, listen: false).displayName}':widget.name, style: TextStyle( fontSize: 20, fontWeight: FontWeight.bold, color: Color(0xFF0A0E21), fontFamily: 'Helvetica Neue', letterSpacing: 0.2, ), ), SizedBox(height: 5,), Visibility( visible: widget.name!=null?false:true, child: Align( alignment: Alignment.centerLeft, child: Container( child: FlatButton( color: Color(0xFF0A0E21), child: Row( mainAxisSize: MainAxisSize.min, children: <Widget>[ Icon( Icons.lock_open, color: Colors.white, ), SizedBox( width: 10, ), Text( 'Update', style: TextStyle( color: Colors.white, fontSize: 18, ), ), ], ), onPressed: () async { FocusScope.of(context).unfocus(); Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) { return MedicalProfile(); })); }), ), ), ), SizedBox( height: 10, ), StreamBuilder<QuerySnapshot>( stream: Firestore.instance .collection('medicalRec') .orderBy('time',descending: true) .where('uid', isEqualTo: widget.uid==null?'${Provider.of<CurrentUser>(context, listen: false).loggedInUser.uid}':widget.uid) .snapshots(), builder: (context, snapshot) { if (!snapshot.hasData || snapshot.data.documents.length == 0) { return Padding( padding: EdgeInsets.only(top: 15), child: Text( "We're getting your medical records ready!", style: TextStyle(fontSize: 16), ), ); } final windows = snapshot.data.documents; List<AppointmentTile> tiles = []; for (var window in windows) { final name = window.data['name']; final content = window.data['description']; String status = window.data['appointmentStatus']; final image = window.data['image']; final docID = window.documentID; print(window.data); bool cancelAp; try { cancelAp = (status=="Approval Pending" || status.substring(0, 9)=="Forwarded")?true:false; } catch (e) { cancelAp=false; } tiles.add( AppointmentTile( userName: name, content: content, postImage: image, status: status, docId: docID, changeStatus: false, cancelAp: cancelAp, ), ); } return Expanded( child: tiles.length != 0 ? ListView( children: tiles, ) : Padding( padding: EdgeInsets.symmetric(vertical: 10), child: Text('No appointment windows found'), ), ); }, ), ], ), ), ), ); } }
0
mirrored_repositories/Qify
mirrored_repositories/Qify/lib/med_profile.dart
import 'dart:io'; import 'package:bot_toast/bot_toast.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_storage/firebase_storage.dart'; import 'package:flutter/material.dart'; import 'package:image_cropper/image_cropper.dart'; import 'package:image_picker/image_picker.dart'; import 'package:modal_progress_hud/modal_progress_hud.dart'; import 'package:provider/provider.dart'; import 'current_user.dart'; class MedicalProfile extends StatefulWidget { final String docId; MedicalProfile({this.docId}); @override _MedicalProfileState createState() => _MedicalProfileState(); } class _MedicalProfileState extends State<MedicalProfile> { bool inProgress = false; String text; String imgUrl; List groups; List groupNames; String groupId; double minPrice; double maxPrice; File postImage; TextEditingController textEditingController = TextEditingController(); TextEditingController minPriceController = TextEditingController(); TextEditingController maxPriceController = TextEditingController(); TextEditingController titleEditingController = TextEditingController(); String _uploadedFileURL; BottomNavigationBar navigationBar; Future uploadFile() async { StorageReference storageReference = FirebaseStorage.instance.ref().child( 'posts/${Provider.of<CurrentUser>(context, listen: false).loggedInUser.uid} ${DateTime.now().toIso8601String()}'); StorageUploadTask uploadTask = storageReference.putFile(postImage); await uploadTask.onComplete; print('File Uploaded'); storageReference.getDownloadURL().then((fileURL) async { await pushData(fileURL); setState(() { _uploadedFileURL = fileURL; imgUrl = fileURL; }); }); } Future pushData(url) async { try { if (((textEditingController.text == "" || textEditingController.text == null) && url == null)) { setState(() { inProgress = false; }); BotToast.showSimpleNotification(title: 'Nothing to post!'); } else { DocumentReference reference = await Firestore.instance.collection('medicalRec').add({ 'description': textEditingController.text, 'image': url != null ? url : null, 'appointmentStatus': 'Done', 'uid': Provider.of<CurrentUser>(context, listen: false).loggedInUser.uid, 'name': Provider.of<CurrentUser>(context, listen: false).displayName, 'time': FieldValue.serverTimestamp(), }); postImage = null; textEditingController.clear(); Navigator.pop(context); setState(() { inProgress = false; }); } } catch (e) { print(e); setState(() { inProgress = false; }); } } File _image; var croppedImage; Future getImage() async { setState(() { inProgress = true; }); var image = await ImagePicker.pickImage(source: ImageSource.gallery); if (image != null) { croppedImage = await ImageCropper.cropImage( sourcePath: image.path, aspectRatio: CropAspectRatio(ratioX: 16, ratioY: 9), compressQuality: 100, maxWidth: 512, maxHeight: 512, compressFormat: ImageCompressFormat.jpg, androidUiSettings: AndroidUiSettings( toolbarColor: Color(0xFF0A0E21), toolbarTitle: 'Crop Image', backgroundColor: Colors.white, ), ); setState(() { inProgress = false; _image = croppedImage; postImage = _image; print('image: $croppedImage'); }); } else { setState(() { inProgress = false; }); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Upload Medical Profile'), backgroundColor: Color(0xFF0A0E21), ), body: GestureDetector( onTap: () { FocusScope.of(context).unfocus(); }, child: ModalProgressHUD( inAsyncCall: inProgress, child: SafeArea( child: SingleChildScrollView( child: Column( mainAxisSize: MainAxisSize.max, children: <Widget>[ Padding( padding: EdgeInsets.symmetric(horizontal: 15), child: TextField( textCapitalization: TextCapitalization.sentences, keyboardType: TextInputType.multiline, maxLines: null, controller: textEditingController, onChanged: (value) { setState(() { text = value; }); }, decoration: InputDecoration( border: InputBorder.none, focusedBorder: InputBorder.none, enabledBorder: InputBorder.none, errorBorder: InputBorder.none, disabledBorder: InputBorder.none, contentPadding: EdgeInsets.only( left: 15, bottom: 11, top: 11, right: 15), hintText: 'Problem Description', ), ), ), SizedBox( height: 15, ), Align( alignment: Alignment.centerLeft, child: Padding( padding: EdgeInsets.symmetric(horizontal: 13), child: Container( child: FlatButton( color: Color(0xFF0A0E21), child: Row( mainAxisSize: MainAxisSize.min, children: <Widget>[ Icon( Icons.camera, color: Colors.white, ), SizedBox( width: 10, ), Text( 'Pick Image', style: TextStyle( color: Colors.white, fontSize: 18, ), ), ], ), onPressed: () async { await getImage(); }), ), ), ), SizedBox( height: 10, ), Column( children: <Widget>[ SizedBox( height: 15, ), SizedBox( height: 15, ), Padding( padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10), child: Visibility( visible: postImage != null ? true : false, child: Stack( children: <Widget>[ Container( height: 256, width: 512, child: postImage != null ? ClipRRect( borderRadius: BorderRadius.all( Radius.circular(10)), child: Image.file( postImage, fit: BoxFit.cover, ), ) : null, decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(10)), ), ), Align( alignment: Alignment.topRight, child: Padding( padding: EdgeInsets.symmetric( vertical: 6, horizontal: 6), child: GestureDetector( onTap: () { setState(() { postImage = null; }); }, child: CircleAvatar( radius: 14, backgroundColor: Color(0x00000000), child: Icon(Icons.close, color: Colors.white), ), ), ), ), ], ), ), ), Align( alignment: Alignment.centerLeft, child: Padding( padding: EdgeInsets.symmetric(horizontal: 13), child: Container( child: FlatButton( color: Color(0xFF0A0E21), child: Row( //mainAxisSize: MainAxisSize.min, children: <Widget>[ Icon( Icons.add, color: Colors.white, ), SizedBox( width: 10, ), Text( 'Upload', style: TextStyle( color: Colors.white, fontSize: 18, ), ), ], ), onPressed: () async { setState(() { inProgress = true; }); FocusScope.of(context).unfocus(); if (postImage != null) { await uploadFile(); } else { await pushData(null); } }), ), ), ), ], ), ], ), ), ), ), ), ); } }
0
mirrored_repositories/Qify
mirrored_repositories/Qify/lib/view_history.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:qifyadmin/appointment_tile.dart'; import 'package:qifyadmin/schedule_tile.dart'; import 'current_user.dart'; class ViewHistory extends StatefulWidget { final String title; final String windowID; ViewHistory({this.title, this.windowID}); @override _ViewHistoryState createState() => _ViewHistoryState(); } class _ViewHistoryState extends State<ViewHistory> { @override Widget build(BuildContext context) { return Padding( padding: EdgeInsets.only(top: 10, left: 8, right: 8), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text( 'Appointments History', style: TextStyle( fontSize: 20, fontWeight: FontWeight.bold, color: Color(0xFF0A0E21), fontFamily: 'Helvetica Neue', letterSpacing: 0.2, ), ), SizedBox( height: 10, ), StreamBuilder<QuerySnapshot>( stream: Firestore.instance .collection('appointments') // .orderBy('date') .where('uid', isEqualTo: Provider.of<CurrentUser>(context, listen: false).loggedInUser.uid) .snapshots(), builder: (context, snapshot) { if (!snapshot.hasData || snapshot.data.documents.length == 0) { return Padding( padding: EdgeInsets.only(top: 15), child: Text( "We're getting your pending appointment history ready!", style: TextStyle(fontSize: 16), ), ); } final windows = snapshot.data.documents; List<AppointmentTile> tiles = []; for (var window in windows) { final name = window.data['name']; final content = window.data['description']; final windowID = window.data['doctorWindowID']; String status = window.data['appointmentStatus']; final image = window.data['image']; final docID = window.documentID; print(window.data); bool cancelAp; try { cancelAp = (status=="Approval Pending" || status.substring(0, 9)=="Forwarded")?true:false; } catch (e) { cancelAp=false; } tiles.add( AppointmentTile( userName: name, content: content, postImage: image, status: status, docId: docID, changeStatus: false, cancelAp: cancelAp, ), ); } return Expanded( child: tiles.length != 0 ? ListView( children: tiles, ) : Padding( padding: EdgeInsets.symmetric(vertical: 10), child: Text('No appointment windows found'), ), ); }, ), ], ), ); } }
0
mirrored_repositories/Qify
mirrored_repositories/Qify/lib/current_user.dart
import 'dart:io'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:qifyadmin/user.dart'; class CurrentUser extends ChangeNotifier { FirebaseUser loggedInUser; FirebaseAuth auth = FirebaseAuth.instance; Firestore firestore = Firestore.instance; String displayName; String photoUrl; String phoneNumber; String address; bool isDoctor; List<User> requests = []; Future getCurrentUser() async { try { var user = await auth.currentUser(); if (user != null) { loggedInUser = user; displayName = loggedInUser.displayName; await getInfo(); } } catch (e) { print(e); } } Future getInfo({bool update}) async { print('updating..'); displayName = loggedInUser.displayName; await firestore .collection('users') .document(loggedInUser.uid) .get() .then((document) { print(document.data['photoUrl']); displayName = document.data['displayName']; photoUrl = document.data['photoUrl']; isDoctor = document.data['isDoctor']; phoneNumber = document.data['number']; address = document.data['address']; print(displayName); notifyListeners(); }); } // Future getUsersInfo(String uid) async { // Map doc; // await firestore.collection('users').document('$uid').get().then((document) { // String url = document['photoUrl']; // String name = document['displayName']; // bool isPandit = document['isPandit']; // doc = {'photoUrl': url, 'displayName': name, 'isPandit': isPandit}; // }); // return doc; // } // // Future getUserInfo(String uid) async { // Map doc; // await firestore.collection('users').document('$uid').get().then((document) { // int numConn = document['numConn']; // doc = {'numConn': numConn}; // }); // return doc; // } Future getRequests() async { requests.clear(); await firestore .collection('users') .where('isVerified', isEqualTo: false).getDocuments() .then((document) async { List<DocumentSnapshot> incomingRequests = document.documents; for (var request in incomingRequests) { print(request.data); requests.add(User( name: request.data['displayName'], photoUrl: request.data['profile'], uid: request.data['uid'], isDoctor: request.data['isDoctor'], )); } }); notifyListeners(); } Future acceptRequest(uid, index) async { DocumentReference doctorRef = Firestore.instance.document('users/' + uid); var val = ['$uid']; await firestore.runTransaction((transaction) async { DocumentSnapshot freshSnap1 = await transaction.get(doctorRef); await transaction.update(freshSnap1.reference, { 'isVerified': true, }); }); requests.removeAt(index); notifyListeners(); } Future declineRequest(uid, index) async { DocumentReference doctorRef = Firestore.instance.document('users/' + uid); var val = ['$uid']; await firestore.runTransaction((transaction) async { DocumentSnapshot freshSnap1 = await transaction.get(doctorRef); await transaction.update(freshSnap1.reference, { 'isVerified': null, }); }); requests.removeAt(index); notifyListeners(); } }
0