repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/flutter-bloc-hackathon-starter/test
mirrored_repositories/flutter-bloc-hackathon-starter/test/helpers/helpers.dart
// Copyright (c) 2021, Very Good Ventures // https://verygood.ventures // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file or at // https://opensource.org/licenses/MIT. export 'pump_app.dart';
0
mirrored_repositories/flutter-bloc-hackathon-starter/test
mirrored_repositories/flutter-bloc-hackathon-starter/test/helpers/pump_app.dart
// Copyright (c) 2021, Very Good Ventures // https://verygood.ventures // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file or at // https://opensource.org/licenses/MIT. import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_bloc_hackathon_starter/l10n/l10n.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_test/flutter_test.dart'; extension PumpApp on WidgetTester { Future<void> pumpApp(Widget widget) { return pumpWidget( MaterialApp( localizationsDelegates: const [ AppLocalizations.delegate, GlobalMaterialLocalizations.delegate, ], supportedLocales: AppLocalizations.supportedLocales, home: widget, ), ); } }
0
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_storage
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_storage/lib/cs_storage.dart
library cs_storage; export './src/cs_storage.dart';
0
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_storage/lib
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_storage/lib/src/cs_storage.dart
import 'package:shared_preferences/shared_preferences.dart'; /// {@template cs_coder} /// Cscoder for local storage of the app using key and value /// {@endtemplate} class CsStorage { CsStorage({this.prefs}); final SharedPreferences? prefs; Object? read(String key) async { final pref = prefs; return pref!.get(key); } Future<String?> readString(String key) async { final pref = prefs; return pref!.getString(key); } Future<void> saveString({String? key, String? value}) async { final pref = prefs; pref!.setString(key!, value!); } Future<void> saveBool({String? key, bool? value}) async { final pref = prefs; pref!.setBool(key!, value!); } Future<bool> clear({String? key, String? value}) async { final pref = prefs; return pref!.clear(); } Future<bool> remove(String key) async { final pref = prefs; return pref!.remove(key); } Future<bool> check(String key) async { final pref = prefs; return pref!.containsKey(key); } }
0
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_storage
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_storage/test/cs_storage_test.dart
import 'package:flutter_test/flutter_test.dart'; import 'package:cs_storage/cs_storage.dart'; void main() { test('adds one to input values', () { // final calculator = Calculator(); // expect(calculator.addOne(2), 3); // expect(calculator.addOne(-7), -6); // expect(calculator.addOne(0), 1); }); }
0
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/cs_ui.dart
library cs_ui; export 'src/colors.dart'; export 'src/extension/extension.dart'; export 'src/navigation/navigation.dart'; export 'src/theme.dart'; export 'src/typography/typography.dart'; export 'src/widgets/widget.dart';
0
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/src/colors.dart
import 'package:flutter/material.dart'; class CsColors { static const primary = Color(0xFF00AB54); static const secondary = Color(0xFF1C1469); static const secondary2 = Color(0xFFEFEFEF); static const primaryIcon = Color(0xFF342774); static const secondaryIcon = Color(0xFF727AEF); static const scaffold = Color(0xFFFFFFFF); static const scaffold2 = Color(0xFFE5F4FF); static const secondaryButton = Color(0xFF3277D8); static const white = Color(0xFFFFFFFF); static const grey = Color(0xFFCECECE); static const black = Color(0xFF000000); static const danger = Color(0xFFFF0000); // const kBackgroundColor = Color(0xFFEFEFEF); static const background = Color(0xFFEAE9F1); static const background2 = Color(0xFFEFEFEF); static const primaryText = Color(0xFF343747); static const secondaryText = Color(0xFFEEEEEE); static const secondaryText2 = Color(0xFF262626); static const primaryBorder = Color(0xFFE5F4FF); static const secondaryBorder = Color(0xFFBCD3F5); static const secondaryBorder2 = Color(0xFF707070); }
0
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/src/theme.dart
import 'package:cs_ui/cs_ui.dart'; import 'package:flutter/material.dart'; class CsTheme { static final light = ThemeData.light().copyWith( scaffoldBackgroundColor: CsColors.scaffold, ); }
0
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/src
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/src/widgets/widget.dart
export 'date_input_box.dart'; export 'input_box.dart'; export 'loader_button.dart'; export 'phone_number_input.dart'; export 'select_box.dart'; export 'solid_button.dart'; export 'text_area.dart'; export 'utils.dart';
0
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/src
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/src/widgets/phone_number_input.dart
import 'package:cs_ui/cs_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_svg/flutter_svg.dart'; class PhoneNumberInput extends StatelessWidget { const PhoneNumberInput({ Key? key, this.controller, this.validator, this.hintText, this.labelText, this.icon, this.leadingIcon, this.leadingColor = CsColors.primary, this.fillColor = CsColors.white, this.maxLength, this.maxLines = 1, this.inputFormat, this.inputType, this.onChanged, this.isPassword = false, this.raduis = 10.0, this.isSuffixCustomIcon = false, this.suffixCustomIcon, this.errorText, this.borderSide = const BorderSide(color: Color(0xFFE5EFFF)), this.iconSize = 24.0, this.isWritable = true, this.enablePrefix = true, this.countryCode = '+234', this.onIconClick, }); final TextEditingController? controller; final FormFieldValidator<String>? validator; final String? hintText; final String? labelText; final IconData? icon; final IconData? leadingIcon; final int? maxLength; final List<TextInputFormatter>? inputFormat; final TextInputType? inputType; final bool isPassword; final double raduis; final BorderSide borderSide; final double iconSize; final bool isWritable; final VoidCallback? onIconClick; final Color leadingColor; final Color fillColor; final int maxLines; final bool enablePrefix; final bool isSuffixCustomIcon; final String? suffixCustomIcon; final String? errorText; final String? countryCode; final ValueChanged<String>? onChanged; @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( decoration: BoxDecoration( border: Border.all( color: CsColors.primaryBorder, ), borderRadius: BorderRadius.only( topLeft: Radius.circular(raduis), bottomLeft: Radius.circular(raduis), ), ), child: Row( textDirection: TextDirection.ltr, mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.center, children: [ Column( mainAxisSize: MainAxisSize.min, children: [ Container( padding: const EdgeInsets.all(10.0), decoration: BoxDecoration( border: Border( right: borderSide, ), ), child: Row( children: [ Text( countryCode!, style: CsTextStyle.caption, ), ], ), ), ], ), Flexible( child: TextFormField( enableInteractiveSelection: true, enabled: isWritable, // validator: validator, inputFormatters: inputFormat, controller: controller, onChanged: onChanged, // autovalidateMode: AutovalidateMode.onUserInteraction, keyboardType: TextInputType.number, maxLength: 10, maxLines: maxLines, style: CsTextStyle.caption.copyWith( color: CsColors.black, ), decoration: InputDecoration( hintStyle: CsTextStyle.caption.copyWith( color: const Color(0xFFDEDEDE), ), hintText: hintText, counterText: '', // labelText: labelText, labelStyle: CsTextStyle.caption.copyWith(color: CsColors.secondary), // counterText: '', fillColor: fillColor, filled: true, focusedBorder: InputBorder.none, enabledBorder: InputBorder.none, border: InputBorder.none, contentPadding: const EdgeInsets.only( left: 10.0, bottom: 5.0, top: 15.0, //right: 25.0, ), suffixIcon: Padding( padding: EdgeInsets.only( right: 5.0, top: isSuffixCustomIcon ? 15.0 : 0.0, bottom: isSuffixCustomIcon ? 15.0 : 0.0, ), child: GestureDetector( onTap: onIconClick, child: isSuffixCustomIcon ? SvgPicture.asset( suffixCustomIcon!, color: const Color(0xFFACACAC), height: 2, width: 2, ) : Icon( icon, color: CsColors.primary, size: iconSize, ), ), ), ), ), ), ], ), ), Padding( padding: const EdgeInsets.only( left: 10, top: 5, ), child: Text( errorText ?? '', style: CsTextStyle.caption.copyWith( color: const Color(0xFFD42531), fontSize: 12, fontWeight: CsFontWeight.regular, ), ), ), ], ); } }
0
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/src
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/src/widgets/solid_button.dart
import 'package:cs_ui/cs_ui.dart'; import 'package:flutter/material.dart'; class SolidButton extends StatelessWidget { const SolidButton({ Key? key, this.text, this.onPressed, this.color = CsColors.primary, this.textColor = CsColors.white, this.textSize = 18.0, this.elevation = 0.0, this.border = const BorderSide(color: CsColors.primary), }) : super(key: key); final String? text; final VoidCallback? onPressed; final Color color; final Color textColor; final double textSize; final double elevation; final BorderSide border; @override Widget build(BuildContext context) { return MaterialButton( color: color, minWidth: double.infinity, onPressed: onPressed, elevation: elevation, disabledColor: color.withOpacity(0.6), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular( 12, ), side: onPressed == null ? const BorderSide(color: Colors.transparent) : border, ), child: Padding( padding: const EdgeInsets.all( 15, ), child: Text( text!, style: CsTextStyle.overline.copyWith( color: textColor, fontSize: textSize, fontWeight: CsFontWeight.semiBold, ), ), ), ); } }
0
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/src
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/src/widgets/text_area.dart
import 'package:cs_ui/cs_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; class TextArea extends StatelessWidget { const TextArea( {Key? key, this.controller, this.validator, this.hintText, this.labelText, this.errorText, this.icon, this.leadingIcon, this.leadingColor = CsColors.primaryText, this.fillColor = CsColors.white, this.maxLength, this.maxLines = 4, this.inputFormat, this.inputType, this.isPassword = false, this.raduis = 10.0, this.isSuffixCustomIcon = false, this.suffixCustomIcon, this.borderSide = const BorderSide(color: Color(0xFFF6F6F6)), this.iconSize = 24.0, this.isWritable = true, this.enablePrefix = true, this.onChanged, this.onIconClick}) : super(key: key); final TextEditingController? controller; final FormFieldValidator<String>? validator; final String? hintText; final String? labelText; final String? errorText; final IconData? icon; final IconData? leadingIcon; final int? maxLength; final List<TextInputFormatter>? inputFormat; final TextInputType? inputType; final bool isPassword; final double raduis; final BorderSide borderSide; final double iconSize; final bool isWritable; final VoidCallback? onIconClick; final Color leadingColor; final Color fillColor; final int maxLines; final bool enablePrefix; final bool isSuffixCustomIcon; final String? suffixCustomIcon; final ValueChanged<String>? onChanged; @override Widget build(BuildContext context) { return TextFormField( enabled: isWritable, validator: validator, inputFormatters: inputFormat, onChanged: onChanged, controller: controller, autovalidateMode: AutovalidateMode.onUserInteraction, keyboardType: inputType, maxLength: maxLength, maxLines: maxLines, obscureText: isPassword, style: const TextStyle( color: CsColors.black, fontSize: 15, fontWeight: FontWeight.w500, ), decoration: InputDecoration( hintStyle: CsTextStyle.caption.copyWith( color: const Color(0xFFDEDEDE), ), hintText: hintText, labelStyle: CsTextStyle.caption.copyWith( color: CsColors.secondaryText2, ), // counterText: '', fillColor: const Color(0xFFF6F6F6), filled: true, errorText: errorText, focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular( raduis, ), borderSide: borderSide, ), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular( raduis, ), borderSide: borderSide, ), border: OutlineInputBorder( borderRadius: BorderRadius.circular( raduis, ), borderSide: borderSide, ), contentPadding: const EdgeInsets.only( left: 20, bottom: 20, top: 20, ), suffixIcon: GestureDetector( onTap: onIconClick, child: Icon( icon, color: CsColors.primaryIcon, ), ), ), ); } }
0
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/src
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/src/widgets/utils.dart
import 'dart:io'; import 'package:cs_ui/cs_ui.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class Utils { static void showErrorMessage(BuildContext context, {String? error}) async { ScaffoldMessenger.of(context).showSnackBar( SnackBar( backgroundColor: Colors.redAccent, content: Row( children: [ const Icon(Icons.error_outline, color: CsColors.white), const SizedBox( width: 7, ), Expanded( child: Text( error!, style: CsTextStyle.smallText.copyWith( fontSize: 16, color: CsColors.white, ), ), ) ], ), dismissDirection: DismissDirection.startToEnd, margin: const EdgeInsets.all(15), behavior: SnackBarBehavior.floating, duration: const Duration(milliseconds: 1000), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12), ), ), ); } static void showSuccessMessage(BuildContext context, {String? message}) async { ScaffoldMessenger.of(context).showSnackBar( SnackBar( backgroundColor: const Color(0xFF20BD2C), content: Row( children: [ const Icon( Icons.check_circle_outline, color: CsColors.white, ), const SizedBox( width: 7, ), Text( message!, style: CsTextStyle.smallText.copyWith( fontSize: 16, color: CsColors.white, ), ) ], ), dismissDirection: DismissDirection.startToEnd, behavior: SnackBarBehavior.floating, margin: const EdgeInsets.all(15), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12), ), duration: const Duration(milliseconds: 1000), ), ); } static Future<void> showLoadingDialog(BuildContext context) { return showDialog<void>( context: context, // for testing, for now this will be true, should be changed to false later barrierDismissible: true, builder: (BuildContext context) { return WillPopScope( // for testing, for now this will be true, should be changed to false later onWillPop: () async => true, child: SimpleDialog( //key: key ?? const Key('0'), elevation: 0, backgroundColor: Colors.transparent, children: <Widget>[ if (Platform.isIOS) Center( child: Theme( data: ThemeData( cupertinoOverrideTheme: const CupertinoThemeData(brightness: Brightness.dark), ), child: const CupertinoActivityIndicator( radius: 18, ), ), ) else const Center( child: CircularProgressIndicator( backgroundColor: CsColors.primary, strokeWidth: 1.3, ), ), ], ), ); }, ); } }
0
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/src
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/src/widgets/date_input_box.dart
import 'package:cs_ui/cs_ui.dart'; import 'package:date_field/date_field.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; enum DateInputMode { date, datetime, time, } class DateInputBox extends StatelessWidget { ///@macro TextBox Constructor const DateInputBox( {Key? key, this.controller, this.validator, this.hintText, this.labelText, this.errorText, this.icon, this.value = '', this.leadingIcon, this.leadingColor = CsColors.primaryText, this.fillColor = const Color(0xFFF6F6F6), this.maxLength, this.inputFormat, this.inputType, this.isPassword = false, this.raduis = 10.0, this.borderSide = const BorderSide(color: Color(0xFFF6F6F6)), this.iconSize = 24.0, this.isWritable = true, this.enablePrefix = true, this.mode = DateInputMode.date, //DateTimeFieldPickerMode.date, this.onChanged, this.focus, this.onIconClick}) : super(key: key); ///@macro TextEditingController fields final TextEditingController? controller; ///@macro Validator fields final FormFieldValidator<DateTime?>? validator; final DateInputMode? mode; ///@macro HintText final String? hintText; ///@macro Label Text final String? labelText; ///@macro Error Text final String? errorText; ///@macro Icon final IconData? icon; ///@macro value final String? value; ///@macro Leading Icon final IconData? leadingIcon; ///@macro Max Length final int? maxLength; ///@macro InputForm final List<TextInputFormatter>? inputFormat; ///@macro Input Type final TextInputType? inputType; ///@macro IsPassword either true/false final bool isPassword; ///@macro InputBox Border Raduis final double raduis; ///@macro BorderSide final BorderSide borderSide; ///@macro Icon Size final double iconSize; ///@macro Iswritable true/false final bool isWritable; ///@macro onIconClick final VoidCallback? onIconClick; ///@macro LeadingIcon Color final Color leadingColor; ///@macro TextBox Background Color final Color fillColor; ///@macro Enable Prefix Icon true/false final bool enablePrefix; ///@macro OnChange function final ValueChanged<DateTime>? onChanged; ///@macro TextBox Focus final FocusNode? focus; @override Widget build(BuildContext context) { return DateTimeFormField( decoration: InputDecoration( hintStyle: CsTextStyle.caption.copyWith( color: const Color(0xFFA8AAB8), ), hintText: hintText, labelStyle: CsTextStyle.caption.copyWith( color: CsColors.secondary, ), fillColor: fillColor, filled: true, errorText: errorText, focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular( raduis, ), borderSide: borderSide, ), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular( raduis, ), borderSide: borderSide, ), border: OutlineInputBorder( borderRadius: BorderRadius.circular( raduis, ), borderSide: borderSide, ), contentPadding: const EdgeInsets.only( left: 20, bottom: 20, top: 20, ), suffixIcon: const Icon(Icons.event_note), ), mode: mode!.toDateTimePickerMode(), //DateTimeFieldPickerMode firstDate: DateTime.now(), initialDate: DateTime.now().subtract(const Duration(days: 10000)), autovalidateMode: AutovalidateMode.always, validator: validator, onDateSelected: onChanged, ); } } extension Modes on DateInputMode { DateTimeFieldPickerMode toDateTimePickerMode() { if (this == DateInputMode.date) { return DateTimeFieldPickerMode.date; } else if (this == DateInputMode.time) { return DateTimeFieldPickerMode.time; } else { return DateTimeFieldPickerMode.dateAndTime; } } }
0
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/src
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/src/widgets/input_box.dart
import 'package:cs_ui/cs_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; /// {@template input_box} /// InputBox similar to textfield /// {@endtemplate} class InputBox extends StatelessWidget { ///@macro TextBox Constructor const InputBox( {Key? key, this.controller, this.validator, this.hintText, this.labelText, this.errorText, this.icon, this.value = '', this.leadingIcon, this.leadingColor = CsColors.primaryText, this.fillColor = const Color(0xFFF6F6F6), this.maxLength, this.inputFormat, this.inputType, this.isPassword = false, this.raduis = 10.0, this.borderSide = const BorderSide(color: Color(0xFFF6F6F6)), this.iconSize = 24.0, this.isWritable = true, this.enablePrefix = true, this.onChanged, this.focus, this.onIconClick}) : super(key: key); ///@macro TextEditingController fields final TextEditingController? controller; ///@macro Validator fields final FormFieldValidator<String>? validator; ///@macro HintText final String? hintText; ///@macro Label Text final String? labelText; ///@macro Error Text final String? errorText; ///@macro Icon final IconData? icon; ///@macro value final String? value; ///@macro Leading Icon final IconData? leadingIcon; ///@macro Max Length final int? maxLength; ///@macro InputForm final List<TextInputFormatter>? inputFormat; ///@macro Input Type final TextInputType? inputType; ///@macro IsPassword either true/false final bool isPassword; ///@macro InputBox Border Raduis final double raduis; ///@macro BorderSide final BorderSide borderSide; ///@macro Icon Size final double iconSize; ///@macro Iswritable true/false final bool isWritable; ///@macro onIconClick final VoidCallback? onIconClick; ///@macro LeadingIcon Color final Color leadingColor; ///@macro TextBox Background Color final Color fillColor; ///@macro Enable Prefix Icon true/false final bool enablePrefix; ///@macro OnChange function final ValueChanged<String>? onChanged; ///@macro TextBox Focus final FocusNode? focus; @override Widget build(BuildContext context) { return TextFormField( enabled: isWritable, validator: validator, inputFormatters: inputFormat, onChanged: onChanged, controller: controller, autovalidateMode: AutovalidateMode.onUserInteraction, keyboardType: inputType, maxLength: maxLength, focusNode: focus, obscureText: isPassword, style: const TextStyle( color: CsColors.black, fontSize: 15, fontWeight: FontWeight.w500, ), decoration: InputDecoration( hintStyle: CsTextStyle.caption.copyWith( color: const Color(0xFFA8AAB8), ), hintText: hintText, labelStyle: CsTextStyle.caption.copyWith( color: CsColors.secondary, ), fillColor: fillColor, filled: true, errorText: errorText, focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular( raduis, ), borderSide: borderSide, ), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular( raduis, ), borderSide: borderSide, ), border: OutlineInputBorder( borderRadius: BorderRadius.circular( raduis, ), borderSide: borderSide, ), contentPadding: const EdgeInsets.only( left: 20, bottom: 20, top: 20, ), suffixIcon: GestureDetector( onTap: onIconClick, child: Icon( icon, color: CsColors.primaryIcon, ), ), ), ); } }
0
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/src
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/src/widgets/loader_button.dart
import 'package:cs_ui/cs_ui.dart'; import 'package:flutter/material.dart'; class LoaderButton extends StatelessWidget { const LoaderButton({ Key? key, this.text, this.onPressed, this.color = CsColors.primary, this.textColor = CsColors.white, this.textSize = 18.0, this.elevation = 0.0, this.isLoading = false, this.loaderColor = Colors.white, this.border = const BorderSide(color: CsColors.primary), }) : super(key: key); final String? text; final VoidCallback? onPressed; final Color color; final Color textColor; final double textSize; final double elevation; final BorderSide border; final bool isLoading; final Color loaderColor; @override Widget build(BuildContext context) { return MaterialButton( color: color, minWidth: double.infinity, onPressed: onPressed, elevation: elevation, disabledColor: color.withOpacity(0.6), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular( 12, ), side: onPressed == null ? const BorderSide(color: Colors.transparent) : border, ), child: Padding( padding: const EdgeInsets.all( 15, ), child: isLoading ? CircularProgressIndicator( backgroundColor: loaderColor, ) : Text( text!, style: CsTextStyle.caption.copyWith( color: textColor, fontSize: textSize, ), ), ), ); } }
0
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/src
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/src/widgets/select_box.dart
import 'package:cs_ui/cs_ui.dart'; import 'package:flutter/material.dart'; class SelectBox<T> extends StatelessWidget { const SelectBox({ Key? key, @required this.items, this.validator, this.radius = 8.0, this.value, this.onChanged, this.icon, this.borderSide = const BorderSide(color: Color(0xFFF6F6F6)), }) : super(key: key); final List<DropdownMenuItem<T>>? items; final FormFieldValidator<dynamic>? validator; final double radius; final dynamic value; final ValueSetter<T?>? onChanged; final BorderSide borderSide; final Widget? icon; @override Widget build(BuildContext context) { return DropdownButtonFormField<T>( value: value as T, items: items, isExpanded: true, validator: validator, decoration: InputDecoration( hintStyle: CsTextStyle.smallText.copyWith( color: CsColors.black, ), filled: true, fillColor: const Color(0xFFF6F6F6), labelStyle: CsTextStyle.smallText.copyWith( color: CsColors.secondary, ), prefixIcon: icon, focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular( radius, ), borderSide: borderSide, ), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular( radius, ), borderSide: borderSide, ), border: OutlineInputBorder( borderRadius: BorderRadius.circular( radius, ), borderSide: borderSide, ), contentPadding: const EdgeInsets.only( left: 10, bottom: 15, top: 15, right: 10, ), ), onChanged: onChanged, dropdownColor: CsColors.white, style: CsTextStyle.smallText.copyWith( color: CsColors.black, ), iconEnabledColor: CsColors.black, icon: const Icon( Icons.keyboard_arrow_down, size: 25, color: CsColors.secondaryBorder, ), ); } }
0
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/src
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/src/navigation/app_bottom_navigation.dart
import 'package:cs_ui/cs_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; class AppBottomNavigationBar extends StatelessWidget { const AppBottomNavigationBar({ Key? key, @required this.items, this.onTap, this.currentIndex, this.selectedItemColor, this.unselectedItemColor, this.iconSize = 50, }) : super(key: key); final ValueChanged<int>? onTap; final int? currentIndex; final List<AppBottomNavigationBarItem>? items; final Color? selectedItemColor; final Color? unselectedItemColor; final double iconSize; @override Widget build(BuildContext context) { List<Widget> _tile = <Widget>[]; for (int i = 0; i < items!.length; i++) { _tile.add( _AppBottomNavigationBarItemTile( items![i], onItemTap: () { if (onTap != null) onTap!(i); }, selected: i == currentIndex!, ), ); } return BottomAppBar( color: const Color( 0XFFFFFFFF, ), child: Material( color: const Color(0xFFFBFBFB), elevation: 0.0, child: Row( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.spaceAround, children: _tile, ), ), ); } } class _AppBottomNavigationBarItemTile extends StatelessWidget { const _AppBottomNavigationBarItemTile( this.item, { this.onItemTap, this.selected, }); final AppBottomNavigationBarItem item; final VoidCallback? onItemTap; final bool? selected; @override Widget build(BuildContext context) { return Expanded( child: SizedBox( height: 80, child: GestureDetector( onTap: onItemTap, child: Container( color: Colors.white, child: Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, children: [ AppBottomIcon( imageName: item.customIcon, isActive: selected, hasCustomIcon: item.useCustomIcon, icon: item.icon, ), const SizedBox( height: 2, ), Text( item.label!, style: CsTextStyle.caption.copyWith( color: selected! ? CsColors.primary : CsColors.primaryText, fontSize: 12, ), ) ], ), ), ), ), ); } } class AppBottomIcon extends StatelessWidget { const AppBottomIcon({ Key? key, this.imageName, this.isActive, this.hasCustomIcon, this.icon, }) : super(key: key); final String? imageName; final bool? isActive; final bool? hasCustomIcon; final IconData? icon; @override Widget build(BuildContext context) { if (hasCustomIcon!) { return SvgPicture.asset( imageName!, width: 24, height: 24, fit: BoxFit.cover, color: isActive! ? CsColors.primary : const Color(0xFFB1B1B1), ); } else { return Icon( icon, size: 27, color: isActive! ? CsColors.primary : const Color(0xFFB1B1B1), ); } } } class AppBottomNavigationBarItem { AppBottomNavigationBarItem({ this.customIcon, String? label, this.icon, this.useCustomIcon = true, }) : label = label ?? ''; final String? customIcon; final bool? useCustomIcon; final String? label; final IconData? icon; }
0
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/src
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/src/navigation/navigation.dart
export './app_bottom_navigation.dart';
0
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/src
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/src/typography/font_weights.dart
import 'package:flutter/material.dart'; class CsFontWeight { /// FontWeight value of `w900` static const FontWeight black = FontWeight.w900; /// FontWeight value of `w800` static const FontWeight extraBold = FontWeight.w800; /// FontWeight value of `w700` static const FontWeight bold = FontWeight.w700; /// FontWeight value of `w600` static const FontWeight semiBold = FontWeight.w600; /// FontWeight value of `w500` static const FontWeight medium = FontWeight.w500; /// FontWeight value of `w400` static const FontWeight regular = FontWeight.w400; /// FontWeight value of `w300` static const FontWeight light = FontWeight.w300; /// FontWeight value of `w200` static const FontWeight extraLight = FontWeight.w200; /// FontWeight value of `w100` static const FontWeight thin = FontWeight.w100; }
0
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/src
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/src/typography/text_styles.dart
import 'package:cs_ui/cs_ui.dart'; import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; class CsTextStyle { static final TextStyle _textStyle = GoogleFonts.poppins( color: CsColors.primaryText, fontWeight: CsFontWeight.regular, ); /// Headline 1 Text Style static TextStyle get headline1 { return _textStyle.copyWith( fontSize: 56, fontWeight: CsFontWeight.medium, ); } /// Headline 2 Text Style static TextStyle get headline2 { return _textStyle.copyWith( fontSize: 30, fontWeight: CsFontWeight.regular, ); } /// Headline 3 Text Style static TextStyle get headline3 { return _textStyle.copyWith( fontSize: 24, fontWeight: CsFontWeight.regular, ); } /// Headline 4 Text Style static TextStyle get headline4 { return _textStyle.copyWith( fontSize: 22, fontWeight: CsFontWeight.bold, ); } /// Headline 5 Text Style static TextStyle get headline5 { return _textStyle.copyWith( fontSize: 22, fontWeight: CsFontWeight.medium, ); } /// Headline 6 Text Style static TextStyle get headline6 { return _textStyle.copyWith( fontSize: 22, fontWeight: CsFontWeight.bold, ); } /// Subtitle 1 Text Style static TextStyle get subtitle1 { return _textStyle.copyWith( fontSize: 16, fontWeight: CsFontWeight.bold, ); } /// Subtitle 2 Text Style static TextStyle get subtitle2 { return _textStyle.copyWith( fontSize: 14, fontWeight: CsFontWeight.bold, ); } /// Body Text 1 Text Style static TextStyle get bodyText1 { return _textStyle.copyWith( fontSize: 18, fontWeight: CsFontWeight.medium, ); } /// Body Text 2 Text Style (the default) static TextStyle get bodyText2 { return _textStyle.copyWith( fontSize: 16, fontWeight: CsFontWeight.regular, ); } /// Caption Text Style static TextStyle get caption { return _textStyle.copyWith( fontSize: 14, fontWeight: CsFontWeight.regular, ); } /// Overline Text Style static TextStyle get overline { return _textStyle.copyWith( fontSize: 16, fontWeight: CsFontWeight.regular, ); } /// Button Text Style static TextStyle get button { return _textStyle.copyWith( fontSize: 18, fontWeight: CsFontWeight.medium, ); } /// Text Button Text Style static TextStyle get textButton { return _textStyle.copyWith( fontSize: 16, fontWeight: CsFontWeight.medium, ); } ///Big Text static TextStyle get bigText => _textStyle.copyWith( fontSize: 27, fontWeight: CsFontWeight.black, ); ///Small Text static TextStyle get smallText => _textStyle.copyWith( fontSize: 14, fontWeight: CsFontWeight.regular, ); }
0
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/src
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/src/typography/typography.dart
export './font_weights.dart'; export './text_styles.dart';
0
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/src
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/src/extension/extension.dart
export 'size.dart'; export 'stringx.dart';
0
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/src
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/src/extension/stringx.dart
extension StringX on String { String get svg => 'assets/svgs/$this.svg'; String get pngImage => 'assets/images/$this.png'; String get capitalizeFirst => isNotEmpty && [0].isNotEmpty ? '${this[0].toUpperCase()}${substring(1)}' : ''; String get capitalize => trim().split(' ').map((e) => e.capitalizeFirst).join(' '); }
0
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/src
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/lib/src/extension/size.dart
import 'dart:io'; import 'package:cs_ui/cs_ui.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; extension SizeX on BuildContext { double get screenWidth => MediaQuery.of(this).size.width; double get screenHeight => MediaQuery.of(this).size.height; double get minScreenWidth => screenWidth / 100; double get minScreenHeight => screenHeight / 100; double get screenSymmetricHorizontal => MediaQuery.of(this).padding.left + MediaQuery.of(this).padding.right; double get screenSymmetricVertical => MediaQuery.of(this).padding.top + MediaQuery.of(this).padding.bottom; double get minBlockHorizontal => (screenWidth - screenSymmetricHorizontal) / 100; double get minBlockVertical => (screenHeight - screenSymmetricVertical) / 100; void back() => Navigator.maybePop(this); void showErrorMessage(String error) { ScaffoldMessenger.of(this).showSnackBar( SnackBar( backgroundColor: Colors.redAccent, content: Row( children: [ const Icon(Icons.error_outline, color: CsColors.white), const SizedBox( width: 7, ), Expanded( child: Text( error, style: CsTextStyle.smallText.copyWith( fontSize: 16, color: CsColors.white, ), ), ) ], ), dismissDirection: DismissDirection.startToEnd, margin: const EdgeInsets.all(15), behavior: SnackBarBehavior.floating, duration: const Duration(milliseconds: 1500), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12), ), ), ); } void showSuccessMessage(String message) { ScaffoldMessenger.of(this).showSnackBar( SnackBar( backgroundColor: Colors.green, content: Row( children: [ const Icon(Icons.check_circle_outline, color: CsColors.white), const SizedBox( width: 7, ), Expanded( child: Text( message, style: CsTextStyle.smallText.copyWith( fontSize: 16, color: CsColors.white, ), ), ) ], ), dismissDirection: DismissDirection.startToEnd, margin: const EdgeInsets.all(15), behavior: SnackBarBehavior.floating, duration: const Duration(milliseconds: 1500), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(12), ), ), ); } Future<void> showDeleteDialog( String title, String message, VoidCallback onPressed, ) { return showDialog<void>( context: this, barrierDismissible: true, builder: (BuildContext context) { return SimpleDialog( backgroundColor: CsColors.white, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(15), ), contentPadding: const EdgeInsets.all(20), children: <Widget>[ Text( title, style: CsTextStyle.headline4.copyWith( fontWeight: CsFontWeight.bold, ), ), const SizedBox(height: 10), Text(message, style: CsTextStyle.bodyText1), const SizedBox(height: 10), Row( mainAxisAlignment: MainAxisAlignment.end, children: [ TextButton( onPressed: back, child: Text( 'Cancel', style: CsTextStyle.headline5.copyWith( fontWeight: CsFontWeight.semiBold, fontSize: 20, color: CsColors.danger, ), ), ), TextButton( onPressed: onPressed, child: Text( 'Delete', style: CsTextStyle.headline5.copyWith( fontWeight: CsFontWeight.semiBold, fontSize: 20, color: CsColors.primary, ), ), ), ], ) ], ); }, ); } Future<void> showLoadingDialog() { return showDialog<void>( context: this, // for testing, for now this will be true, should be changed to false later barrierDismissible: true, builder: (BuildContext context) { return WillPopScope( // for testing, for now this will be true, should be changed to false later onWillPop: () async => true, child: SimpleDialog( //key: key ?? const Key('0'), elevation: 0, backgroundColor: Colors.transparent, children: <Widget>[ if (Platform.isIOS) Center( child: Theme( data: ThemeData( cupertinoOverrideTheme: const CupertinoThemeData( brightness: Brightness.dark), ), child: const CupertinoActivityIndicator( radius: 18, )), ) else const Center( child: CircularProgressIndicator( backgroundColor: CsColors.primary, strokeWidth: 1.3, ), ), ], ), ); }, ); } }
0
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/test
mirrored_repositories/flutter-bloc-hackathon-starter/packages/cs_ui/test/src/cs_ui_test.dart
// ignore_for_file: prefer_const_constructors import 'package:cs_ui/cs_ui.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('CsUi', () { test('can be instantiated', () { //expect(CsUi(), isNotNull); }); }); }
0
mirrored_repositories/flutter-bloc-hackathon-starter/packages/auth_api
mirrored_repositories/flutter-bloc-hackathon-starter/packages/auth_api/lib/auth_api.dart
library auth_api; export './src/auth_api_client.dart'; export 'src/auth_api_client.dart';
0
mirrored_repositories/flutter-bloc-hackathon-starter/packages/auth_api/lib
mirrored_repositories/flutter-bloc-hackathon-starter/packages/auth_api/lib/src/api_interceptor.dart
import 'dart:async'; import 'dart:developer'; import 'package:dio/dio.dart'; import 'package:shared_preferences/shared_preferences.dart'; ///Api interceptor class class ApiInterceptor extends Interceptor { @override Future<dynamic> onRequest( RequestOptions options, RequestInterceptorHandler handler) async { final prefs = await SharedPreferences.getInstance(); final token = prefs.getString('token'); if (options.headers['hasToken'] == true) { options.headers.addAll( <String, dynamic>{'Authorization': 'Bearer $token'}, ); options.headers.remove('hasToken'); } else { options.headers.remove('hasToken'); } return super.onRequest(options, handler); } } @override Future onResponse(Response response, ResponseInterceptorHandler handler) async { log('Response: ${response.data}'); return handler.next(response); }
0
mirrored_repositories/flutter-bloc-hackathon-starter/packages/auth_api/lib
mirrored_repositories/flutter-bloc-hackathon-starter/packages/auth_api/lib/src/auth_api_client.dart
// ignore_for_file: avoid_print import 'dart:convert'; import 'dart:developer'; import 'dart:io'; import 'package:auth_api/src/api_interceptor.dart'; import 'package:dio/dio.dart'; //Exception thrown when user registration fails class RegistrationRequestFailure implements Exception { const RegistrationRequestFailure(this.statusCode, {this.message}); final int statusCode; final String? message; @override String toString() { log('$statusCode:::$message'); return message ?? ''; } } //Exception thrown when user unknown error occur class RegistrationError implements Exception {} //Exception thrown when user login fails class HttpRequestFailure implements Exception { const HttpRequestFailure(this.statusCode, {this.message}); final int statusCode; final String? message; @override String toString() { return message ?? ''; } } //Exception thrown when user unknown error occur class HttpError implements Exception {} class AuthApiClient { AuthApiClient({Dio? dio}) : _dio = (dio ?? Dio( BaseOptions( followRedirects: false, validateStatus: (status) { return status! < 500; }, ), )) ..interceptors.add(ApiInterceptor()) ..options.followRedirects = true ..options.baseUrl = 'https://cdashboard-api-ooemp.ondigitalocean.app/'; final Dio _dio; Future<Map<String, dynamic>> login({String? email, String? password}) async { try { Response response = await _dio.post( 'auth/login', data: jsonEncode({'email': email, 'password': password}), ); if (response.statusCode == 400 || response.statusCode == 401) { throw HttpRequestFailure(response.statusCode!, message: response.data['message']); } if (response.statusCode == 200 || response.statusCode == 201) { return response.data as Map<String, dynamic>; } throw HttpRequestFailure(response.statusCode!); } on DioError catch (e) { if (e.response != null) { if (e.response!.statusCode == HttpStatus.badRequest || e.response!.statusCode == HttpStatus.unauthorized) { throw HttpRequestFailure(e.response!.statusCode!, message: e.response!.data['message']); } else { throw HttpError(); } } throw HttpError(); } } Future<Map<String, dynamic>> changePassword( {String? currentPassword, String? newPassword}) async { try { Response response = await _dio.patch( 'auth/users/update-password', options: Options( headers: <String, dynamic>{'hasToken': true}, ), data: jsonEncode( {'currentPassword': currentPassword, 'password': newPassword}), ); print(response.data); if (response.statusCode == 400 || response.statusCode == 401) { throw HttpRequestFailure(response.statusCode!, message: response.data['message']); } if (response.statusCode == 200 || response.statusCode == 201) { return response.data as Map<String, dynamic>; } throw HttpRequestFailure(response.statusCode!); } on DioError catch (e) { print(e.response); if (e.response != null) { if (e.response!.statusCode == HttpStatus.badRequest || e.response!.statusCode == HttpStatus.unauthorized) { throw HttpRequestFailure(e.response!.statusCode!, message: e.response!.data['message']); } else { throw HttpError(); } } throw HttpError(); } } Future<Map<String, dynamic>> getUserProfile() async { try { Response response = await _dio.get( 'auth/profile/get-profile', options: Options( headers: <String, dynamic>{'hasToken': true}, ), ); if (response.statusCode == 400 || response.statusCode == 401) { throw HttpRequestFailure(response.statusCode!, message: response.data['message']); } if (response.statusCode == 200 || response.statusCode == 201) { return response.data as Map<String, dynamic>; } throw HttpRequestFailure(response.statusCode!); } on DioError catch (e) { print(e.response); if (e.response != null) { if (e.response!.statusCode == HttpStatus.badRequest || e.response!.statusCode == HttpStatus.unauthorized) { throw HttpRequestFailure(e.response!.statusCode!, message: e.response!.data['message']); } else { throw HttpError(); } } throw HttpError(); } } }
0
mirrored_repositories/flutter-bloc-hackathon-starter/packages/auth_api
mirrored_repositories/flutter-bloc-hackathon-starter/packages/auth_api/test/auth_api_test.dart
import 'package:flutter_test/flutter_test.dart'; import 'package:auth_api/auth_api.dart'; void main() { test('adds one to input values', () { // final calculator = Calculator(); // expect(calculator.addOne(2), 3); // expect(calculator.addOne(-7), -6); // expect(calculator.addOne(0), 1); }); }
0
mirrored_repositories/flutter-bloc-hackathon-starter/packages/auth_repository
mirrored_repositories/flutter-bloc-hackathon-starter/packages/auth_repository/lib/auth_repository.dart
library auth_repository; export 'src/auth_repository.dart'; export 'src/models/user.dart';
0
mirrored_repositories/flutter-bloc-hackathon-starter/packages/auth_repository/lib
mirrored_repositories/flutter-bloc-hackathon-starter/packages/auth_repository/lib/src/auth_repository.dart
import 'dart:async'; import 'dart:convert'; import 'package:auth_api/auth_api.dart'; import 'package:auth_repository/auth_repository.dart'; import 'package:cs_storage/cs_storage.dart'; //Exception thrown when user login fails class LoginRequestFailure implements Exception { const LoginRequestFailure({this.message}); final String? message; @override String toString() { return message ?? ''; } } //Exception thrown when user unknown error occur class LoginFailure implements Exception {} //Exception thrown when user login fails class ChangePasswordRequestFailure implements Exception { const ChangePasswordRequestFailure({this.message}); final String? message; @override String toString() { return message ?? ''; } } //Exception thrown when user unknown error occur class ChangePasswordFailure implements Exception {} enum AuthStatus { unknown, intial, authenticated, unauthenticated, } class AuthRepository { AuthRepository({ AuthApiClient? authApiClient, CsStorage? csStorage, }) : _authApiClient = authApiClient ?? AuthApiClient(), _csStorage = csStorage ?? CsStorage(); final AuthApiClient _authApiClient; final CsStorage _csStorage; final _controller = StreamController<AuthStatus>(); Stream<AuthStatus> get status async* { final hasUser = await _csStorage.check('user'); final hasToken = await _csStorage.check('token'); if (hasUser && hasToken) { yield AuthStatus.authenticated; } else if (!hasUser && !hasToken) { yield AuthStatus.unauthenticated; } else { yield AuthStatus.unknown; } // yield* _controller.stream; } Future<User> login({ required String? email, required String? password, }) async { try { final response = await _authApiClient.login(email: email, password: password); _csStorage.saveString(key: 'token', value: 'your token '); _controller.add(AuthStatus.authenticated); return User.fromJson(response); } on HttpRequestFailure catch (e) { throw LoginRequestFailure(message: e.toString()); } on HttpError { throw LoginFailure(); } } Future<User> get user async { final response = await _csStorage.readString('user'); final user = jsonDecode(response!); return User.fromJson(user); } Future<void> logOut() async { await _csStorage.remove('user'); await _csStorage.remove('token'); _controller.add(AuthStatus.unauthenticated); } void dispose() => _controller.close(); }
0
mirrored_repositories/flutter-bloc-hackathon-starter/packages/auth_repository/lib/src
mirrored_repositories/flutter-bloc-hackathon-starter/packages/auth_repository/lib/src/models/user.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'user.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** User _$UserFromJson(Map<String, dynamic> json) => User( id: json['id'] as String?, email: json['email'] as String?, roles: (json['roles'] as List<dynamic>?)?.map((e) => e as String).toList(), firstName: json['firstName'] as String?, lastName: json['lastName'] as String?, ); Map<String, dynamic> _$UserToJson(User instance) => <String, dynamic>{ 'id': instance.id, 'email': instance.email, 'roles': instance.roles, 'firstName': instance.firstName, 'lastName': instance.lastName, };
0
mirrored_repositories/flutter-bloc-hackathon-starter/packages/auth_repository/lib/src
mirrored_repositories/flutter-bloc-hackathon-starter/packages/auth_repository/lib/src/models/user.dart
import 'package:json_annotation/json_annotation.dart'; part 'user.g.dart'; @JsonSerializable() class User { final String? id; final String? email; final List<String>? roles; final String? firstName; final String? lastName; const User({ this.id, this.email, this.roles, this.firstName, this.lastName, }); factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json); }
0
mirrored_repositories/flutter-bloc-hackathon-starter/packages/auth_repository
mirrored_repositories/flutter-bloc-hackathon-starter/packages/auth_repository/test/auth_repository_test.dart
import 'package:flutter_test/flutter_test.dart'; import 'package:auth_repository/auth_repository.dart'; void main() { test('adds one to input values', () { // final calculator = Calculator(); // expect(calculator.addOne(2), 3); // expect(calculator.addOne(-7), -6); // expect(calculator.addOne(0), 1); }); }
0
mirrored_repositories/progress_indicator
mirrored_repositories/progress_indicator/lib/main.dart
import 'package:flutter/material.dart'; import 'dart:async'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: HomePage(), ); } } class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { double _initial = 0.0; double _start = 0.0; // TODO Create updateIndicator Function // which update the indicator periodically void updateIndicator() { Timer.periodic(Duration(milliseconds: 100), (timer) { setState(() { _initial = _initial + 0.01; }); }); } // TODO Create stepIndicator Widget Widget _stepIndicator() { // As we have 5 steps so we multiply 5 with initial value // [0] mean we want just first value (not in points) String value = (_start * 5).toString()[0]; return Column( children: [ Text('Step $value of 5 Completed'), SizedBox(height: 25.0), LinearProgressIndicator( value: _start, minHeight: 15.0, backgroundColor: Colors.black, valueColor: AlwaysStoppedAnimation(Colors.green), ), SizedBox(height: 25.0), RaisedButton( onPressed: () { setState(() { _start = _start + 0.2; }); }, child: Text('Next'), ) ], ); } @override Widget build(BuildContext context) { return Scaffold( floatingActionButton: FloatingActionButton( backgroundColor: Colors.purple, onPressed: () {}, child: Icon(Icons.file_download, color: Colors.black, size: 35.0), ), body: Center( child: Padding( padding: const EdgeInsets.all(12.0), child: Column( mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.max, children: [ ////////////////// CHECK Using STEP ////////////////////////// _stepIndicator(), ////////////////////////////////////////////////////////////// SizedBox(height: 50.0), Divider(thickness: 1.5, color: Colors.black), SizedBox(height: 50.0), ////////////////// CHECK PERIODICALLY ////////////////////////// LinearProgressIndicator( value: _initial, minHeight: 15.0, backgroundColor: Colors.black, valueColor: AlwaysStoppedAnimation(Colors.green), ), SizedBox(height: 25.0), CircularProgressIndicator( value: _initial, backgroundColor: Colors.black, valueColor: AlwaysStoppedAnimation(Colors.green), ), SizedBox(height: 25.0), RaisedButton( onPressed: () { // here updateIndicator Function call updateIndicator(); }, child: Text('Check Periodically'), ) ], ), ), ), ); } }
0
mirrored_repositories/progress_indicator
mirrored_repositories/progress_indicator/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:progress_indicator/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/felexo-app
mirrored_repositories/felexo-app/lib/main.dart
import 'dart:io'; import 'package:felexo/Screens/splash-screen.dart'; import 'package:felexo/theme/app-theme.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:provider/provider.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'Services/ad-services.dart'; void main() async { var appDirectory = Directory("storage/emulated/0/Pictures/FELEXO/"); if (!(await appDirectory.exists())) { appDirectory.create(recursive: true); } WidgetsFlutterBinding.ensureInitialized(); // Required by FlutterConfig SystemChrome.setEnabledSystemUIOverlays([SystemUiOverlay.top]).then((_) { SharedPreferences.getInstance().then((themePrefs) async { String theme = themePrefs.getString("appTheme"); ThemeMode prefTheme; if (theme == "ThemeMode.system") { prefTheme = ThemeMode.system; } if (theme == "ThemeMode.dark") { prefTheme = ThemeMode.dark; } if (theme == "ThemeMode.light") { prefTheme = ThemeMode.light; } await Firebase.initializeApp(); WidgetsFlutterBinding.ensureInitialized(); AdServices.intialize(); runApp( ChangeNotifierProvider<ThemeModeNotifier>( create: (_) => ThemeModeNotifier(prefTheme), child: MyApp(), ), ); }); }); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { // final themeModeNotifier = Provider.of<ThemeModeNotifier>(context); return MaterialApp( debugShowCheckedModeBanner: false, title: 'Felexo', darkTheme: darkTheme, theme: lightTheme, // themeMode: themeModeNotifier.getMode(), themeMode: ThemeMode.system, home: SplashScreen()); } }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Data/favorites-data.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:felexo/Services/favorites-list.dart'; import 'package:flutter/material.dart'; class DatabaseService { final String uid; DatabaseService({@required this.uid}); // List<Favorites> _favoriteListfromSnapshot(QuerySnapshot snapshot) { // return snapshot.docs.map((doc) { // return Favorites( // imgUrl: doc.data()['imgUrl'] ?? '', // originalUrl: doc.data()['originalUrl'] ?? '', // photoID: doc.data()['photoID'] ?? '', // photographer: doc.data()['photographer'] ?? '', // photographerID: doc.data()['photographerID'] ?? '', // avgColor: doc.data()['avgColor'], // photographerUrl: doc.data()['photographerUrl'] ?? ''); // }).toList(); // } List<Favorites> _favoriteListfromSnapshot(QuerySnapshot snapshot) { return snapshot.docs.map((doc) { return Favorites( imgUrl: doc.get('imgUrl') ?? '', originalUrl: doc.get('originalUrl') ?? '', photoID: doc.get('photoID') ?? '', photographer: doc.get('photographer') ?? '', photographerID: doc.get('photographerID') ?? '', avgColor: doc.get('avgColor'), photographerUrl: doc.get('photographerUrl') ?? ''); }).toList(); } Stream<List<Favorites>> get favorites { return FirebaseFirestore.instance .collection("User") .doc(uid) .collection("Favorites") .snapshots() .map((_favoriteListfromSnapshot)); } }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Data/categories-data.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:felexo/Services/categories-list.dart'; class CategoryService { // List<Categories> _favoriteListfromSnapshot(QuerySnapshot snapshot) { // return snapshot.docs.map((doc) { // return Categories( // imgUrl: doc.data()['imgUrl'], // categoryName: doc.data()['CategoryName']); // }).toList(); // } List<Categories> _favoriteListfromSnapshot(QuerySnapshot snapshot) { return snapshot.docs.map((doc) { return Categories( imgUrl: doc.get('imgUrl'), categoryName: doc.get('CategoryName')); }).toList(); } Stream<List<Categories>> get categories { return FirebaseFirestore.instance .collection("Categories") .snapshots() .map((_favoriteListfromSnapshot)); } }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Screens/splash-screen.dart
import 'dart:async'; import 'package:cached_network_image/cached_network_image.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:felexo/Services/authentication-service.dart'; import 'package:felexo/Services/push-notifications.dart'; import 'package:felexo/Views/main-view.dart'; import 'package:felexo/theme/app-theme.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_storage/firebase_storage.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:permission/permission.dart'; import 'package:provider/provider.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:shimmer_animation/shimmer_animation.dart'; class SplashScreen extends StatefulWidget { @override _SplashScreenState createState() => _SplashScreenState(); } class _SplashScreenState extends State<SplashScreen> with SingleTickerProviderStateMixin { final FirebaseAuth _auth = FirebaseAuth.instance; AnimationController controller; double elevationValue = 15; bool darkMode = false; bool visibility = false; User user; String _systemTheme; bool isDark = true; final fsref = FirebaseStorage.instance.ref(); PushNotificationService fcmNotification; var googleIcon; @override initState() { super.initState(); fcmNotification = PushNotificationService(); fcmNotification.initialize(); getIcon(); handleAsync(); setState(() {}); askPermission(); Timer(Duration(seconds: 3), () async { if (_auth.currentUser != null) { FirebaseFirestore.instance .collection("User") .doc(_auth.currentUser.uid) .snapshots() .forEach((element) { setState(() { if (element.data()["subscribedToNotifications"].toString() == "null") { FirebaseFirestore.instance .collection("User") .doc(_auth.currentUser.uid) .update({"subscribedToNotifications": true}); } if (element.data()["subscribedToNotifications"].toString() == null) { FirebaseFirestore.instance .collection("User") .doc(_auth.currentUser.uid) .update({"subscribedToNotifications": true}); } }); Navigator.pushAndRemoveUntil( context, CupertinoPageRoute(builder: (context) => MainView()), (route) => false); }); } else { visibility = true; setState(() {}); } }); } handleAsync() async { String _token = await fcmNotification.getToken(); print("FCM TOKEN: " + _token); fcmNotification.subscribeToTopic('curated'); } getIcon() async { await fsref.child('googleIcon.png').getDownloadURL().then((value) { setState(() { googleIcon = value; }); }); } @override void dispose() { super.dispose(); } askPermission() async { List<Permissions> permissionNames = await Permission.requestPermissions([PermissionName.Storage]); return permissionNames; } @override Widget build(BuildContext context) { SystemChrome.setPreferredOrientations([ DeviceOrientation.portraitUp, ]); final themeModeNotifier = Provider.of<ThemeModeNotifier>(context); if (MediaQuery.of(context).platformBrightness == Brightness.light) { isDark = false; } _systemTheme = (themeModeNotifier.getMode().toString()); if (_systemTheme == "") { SharedPreferences.getInstance().then((themePrefs) async { String theme = themePrefs.getString("appTheme"); if (theme == "ThemeMode.system") { _systemTheme = "ThemeMode.system"; } if (theme == "ThemeMode.dark") { _systemTheme = "ThemeMode.dark"; } if (theme == "ThemeMode.light") { _systemTheme = "ThemeMode.light"; } }); } if (_systemTheme != "") { SharedPreferences.getInstance().then((themePrefs) async { String theme = themePrefs.getString("appTheme"); if (theme == "ThemeMode.system") { _systemTheme = "ThemeMode.system"; } if (theme == "ThemeMode.dark") { _systemTheme = "ThemeMode.dark"; } if (theme == "ThemeMode.light") { _systemTheme = "ThemeMode.light"; } }); } print(_systemTheme); return Scaffold( backgroundColor: Theme.of(context).cardColor, body: SafeArea( child: Stack(children: [ Align( alignment: Alignment.center, child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Container( width: MediaQuery.of(context).size.width, height: 150, decoration: BoxDecoration( color: Theme.of(context).colorScheme.primary), child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Text("FELEXO", style: TextStyle( fontFamily: 'Theme Black', color: Theme.of(context).colorScheme.secondary, fontSize: 80)), ], )), SizedBox( height: 50, ), Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Visibility( visible: visibility, child: Container( width: 230, height: 60, child: ElevatedButton.icon( style: ElevatedButton.styleFrom( primary: Theme.of(context).colorScheme.primary, onPrimary: Theme.of(context).colorScheme.secondary, elevation: 0, padding: EdgeInsets.fromLTRB(15, 15, 15, 15), shape: RoundedRectangleBorder( borderRadius: BorderRadius.zero), shadowColor: Theme.of(context) .colorScheme .primary .withOpacity(1), onSurface: Theme.of(context).colorScheme.secondary), icon: CachedNetworkImage( placeholder: (context, googleIcon) { return Container( width: 24, height: 24, ); }, imageUrl: googleIcon.toString(), height: 24, fadeInCurve: Curves.easeIn, fadeInDuration: const Duration(milliseconds: 500), ), label: Row(children: [ SizedBox( width: 10, ), Text("SIGN IN WITH GOOGLE") ]), onPressed: () { showDialog( useSafeArea: true, context: context, builder: (context) => AlertDialog( backgroundColor: Colors.transparent, content: Container( width: MediaQuery.of(context) .size .width, height: 70, decoration: BoxDecoration( border: Border.all( color: Theme.of(context) .accentColor .withOpacity(0.5)), shape: BoxShape.rectangle, color: Theme.of(context) .backgroundColor, ), child: Shimmer( child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Padding( padding: const EdgeInsets.only( top: 20.0), child: Text( "VERIFYING CREDENTIALS", style: Theme.of(context) .textTheme .button, ), ), SizedBox( height: 23, ), ], ), ), ), )); signInWithGoogle(context); }, ), ), ), ], ), SizedBox( height: 20, ), // Row( // crossAxisAlignment: CrossAxisAlignment.center, // mainAxisAlignment: MainAxisAlignment.center, // children: [ // Visibility( // visible: visibility, // child: Container( // width: 230, // height: 60, // child: ElevatedButton.icon( // style: ElevatedButton.styleFrom( // primary: Theme.of(context).colorScheme.secondary, // onSurface: Theme.of(context).colorScheme.primary, // elevation: 15, // padding: EdgeInsets.fromLTRB(15, 15, 15, 15), // shape: RoundedRectangleBorder( // borderRadius: BorderRadius.zero), // shadowColor: Theme.of(context) // .colorScheme // .primary // .withOpacity(1), // ), // icon: Text( // "F", // style: TextStyle( // fontSize: 24, // fontFamily: 'Theme Black', // color: Theme.of(context).colorScheme.primary), // ), // label: Row( // children: [ // SizedBox( // width: 10, // ), // Text( // "SIGN IN WITH FELEXO", // style: TextStyle( // fontFamily: 'Theme Bold', // color: // Theme.of(context).colorScheme.primary), // ), // ], // ), // onPressed: () {}, // ), // ), // ), // ], // ), ], )), ]), )); } void onThemeChanged(String val, ThemeModeNotifier themeModeNotifier) async { var themeModePrefs = await SharedPreferences.getInstance(); if (val == "ThemeMode.system") { themeModeNotifier.setMode(ThemeMode.system); } if (val == "ThemeMode.dark") { themeModeNotifier.setMode(ThemeMode.dark); } if (val == "ThemeMode.light") { themeModeNotifier.setMode(ThemeMode.light); } themeModePrefs.setString("appTheme", val); } }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Screens/landing-page.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:felexo/Services/authentication-service.dart'; import 'package:firebase_storage/firebase_storage.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:permission/permission.dart'; import 'package:shimmer_animation/shimmer_animation.dart'; class LandingPage extends StatefulWidget { @override _LandingPageState createState() => _LandingPageState(); } class _LandingPageState extends State<LandingPage> with SingleTickerProviderStateMixin { AnimationController controller; bool darkMode = false; final fsref = FirebaseStorage.instance.ref(); String googleIcon; @override void initState() { getIcon(); askStoragePermission(); super.initState(); } getIcon() async { await fsref.child('googleIcon.png').getDownloadURL().then((value) { setState(() { googleIcon = value; }); }); } @override void dispose() { controller.dispose(); super.dispose(); } @override void didChangeDependencies() { super.didChangeDependencies(); if (MediaQuery.platformBrightnessOf(context) == Brightness.dark) { darkMode = true; setState(() {}); } if (MediaQuery.platformBrightnessOf(context) == Brightness.light) { darkMode = false; setState(() {}); } } askStoragePermission() async { List<Permissions> permissionStorage = await Permission.requestPermissions([PermissionName.Storage]); print(permissionStorage.map((e) { print("StoragePermission " + e.permissionStatus.toString()); })); } @override Widget build(BuildContext context) { SystemChrome.setPreferredOrientations([ DeviceOrientation.portraitUp, ]); return Scaffold( backgroundColor: Theme.of(context).cardColor, body: SafeArea( child: Stack(children: [ Align( alignment: Alignment.center, child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Container( width: MediaQuery.of(context).size.width, height: 150, decoration: BoxDecoration( color: Theme.of(context).colorScheme.primary), child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Text("FELEXO", style: TextStyle( fontFamily: 'Theme Black', color: Theme.of(context).colorScheme.secondary, fontSize: 80)), ], )), SizedBox( height: 50, ), Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Container( width: 230, height: 60, child: ElevatedButton.icon( style: ElevatedButton.styleFrom( onPrimary: Theme.of(context).colorScheme.background, elevation: 0, padding: EdgeInsets.fromLTRB(15, 15, 15, 15), shape: RoundedRectangleBorder( borderRadius: BorderRadius.zero), shadowColor: Theme.of(context) .colorScheme .primary .withOpacity(1), onSurface: Theme.of(context).colorScheme.secondary), icon: CachedNetworkImage( placeholder: (context, googleIcon) { return Container( width: 24, height: 24, ); }, imageUrl: googleIcon, height: 24, fadeInCurve: Curves.easeIn, fadeInDuration: const Duration(milliseconds: 500), ), label: Row(children: [ SizedBox( width: 10, ), Text("SIGN IN WITH GOOGLE") ]), onPressed: () { showDialog( context: context, builder: (context) => AlertDialog( backgroundColor: Colors.transparent, content: Container( width: MediaQuery.of(context).size.width, height: 70, decoration: BoxDecoration( border: Border.all( color: Theme.of(context) .accentColor .withOpacity(0.5)), shape: BoxShape.rectangle, color: Theme.of(context) .backgroundColor, ), child: Shimmer( child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Padding( padding: const EdgeInsets.only( top: 20.0), child: Text( "VERIFYING CREDENTIALS", style: Theme.of(context) .textTheme .button, ), ), SizedBox( height: 23, ), ], ), ), ), )); signInWithGoogle(context); }, ), ), ], ), SizedBox( height: 20, ), // Row( // crossAxisAlignment: CrossAxisAlignment.center, // mainAxisAlignment: MainAxisAlignment.center, // children: [ // Visibility( // visible: visibility, // child: Container( // width: 230, // height: 60, // child: ElevatedButton.icon( // style: ElevatedButton.styleFrom( // primary: Theme.of(context).colorScheme.secondary, // onSurface: Theme.of(context).colorScheme.primary, // elevation: 15, // padding: EdgeInsets.fromLTRB(15, 15, 15, 15), // shape: RoundedRectangleBorder( // borderRadius: BorderRadius.zero), // shadowColor: Theme.of(context) // .colorScheme // .primary // .withOpacity(1), // ), // icon: Text( // "F", // style: TextStyle( // fontSize: 24, // fontFamily: 'Theme Black', // color: Theme.of(context).colorScheme.primary), // ), // label: Row( // children: [ // SizedBox( // width: 10, // ), // Text( // "SIGN IN WITH FELEXO", // style: TextStyle( // fontFamily: 'Theme Bold', // color: // Theme.of(context).colorScheme.primary), // ), // ], // ), // onPressed: () {}, // ), // ), // ), // ], // ), ], )), ]), )); } }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Services/categories-list.dart
import 'package:felexo/Widget/categories-tile.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; class CategoriesList extends StatefulWidget { @override _CategoriesListState createState() => _CategoriesListState(); } class _CategoriesListState extends State<CategoriesList> { final FirebaseAuth _auth = FirebaseAuth.instance; User user; @override void initState() { initUser(); super.initState(); } initUser() async { user = _auth.currentUser; assert(user.email != null); assert(user.uid != null); assert(user.photoURL != null); setState(() {}); } @override Widget build(BuildContext context) { final categories = Provider.of<List<Categories>>(context); return Scaffold( body: ListView.builder( itemCount: categories.length, itemBuilder: (context, index) { return CategoriesTile(categories: categories[index]); }, ), ); } } class Categories { final String imgUrl; final String categoryName; Categories({this.imgUrl, this.categoryName}) : assert(imgUrl != null), assert(categoryName != null); } class Suggestions { final String suggestionString; Suggestions({this.suggestionString}) : assert(suggestionString != null); }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Services/blur-service.dart
import 'dart:ui'; import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; /// Convenience widget to create blurred images. /// `BlurredImage.asset` behaves like `Image.asset`, and /// `BlurredImage.network` behaves like `Image.network`. class BlurredImage extends StatelessWidget { BlurredImage.asset( String imagePath, { Key key, this.blurValue = 5, }) : imageWidget = Image.asset( imagePath, width: double.infinity, fit: BoxFit.fitWidth, ), super(key: key); BlurredImage.network( BuildContext context, String url, { Key key, this.blurValue = 5, }) : imageWidget = CachedNetworkImage( imageUrl: url, width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height, fit: BoxFit.cover, fadeInCurve: Curves.easeIn, fadeOutCurve: Curves.easeOut, ), super(key: key); final double blurValue; final Widget imageWidget; @override Widget build(BuildContext context) { return Blurred( imageWidget, blurValue: blurValue, ); } } /// Wrapper widget that blurs the wudget passed to it. /// Any widget passed to the `child` argument will not be blurred. /// The higher the `blurValue`, the stronger the blur effect. class Blurred extends StatelessWidget { const Blurred( this.widget, { Key key, this.child, this.blurValue = 5, this.alignment = Alignment.center, }) : super(key: key); final Widget widget; final Widget child; final double blurValue; final AlignmentGeometry alignment; @override Widget build(BuildContext context) { return ClipRect( child: Stack( alignment: alignment, children: <Widget>[ widget, Positioned.fill( child: BackdropFilter( filter: ImageFilter.blur(sigmaX: blurValue, sigmaY: blurValue), child: Container(), ), ), if (child != null) child, ], ), ); } }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Services/ad-services.dart
import 'dart:io'; import 'package:felexo/Data/data.dart'; import 'package:google_mobile_ads/google_mobile_ads.dart'; class AdServices { static String get bannerAdUnitId => Platform.isAndroid ? bannerAdId : bannerAdId; static String get interstitialAdUnitId => Platform.isAndroid ? bannerAdId : bannerAdId; static intialize() { if (MobileAds.instance == null) { MobileAds.instance.initialize(); } } static BannerAd createBannerAd() { BannerAd bannerAd = new BannerAd( size: AdSize.banner, adUnitId: bannerAdUnitId, listener: BannerAdListener( onAdClosed: (Ad ad) => print('AD CLOSED!'), onAdFailedToLoad: (Ad ad, LoadAdError error) { ad.dispose(); }, onAdOpened: (Ad ad) => print('AD OPENED!'), onAdLoaded: (Ad ad) => print('BANNER AD LOADED!')), request: AdRequest()); return bannerAd; } }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Services/authentication-service.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:felexo/Color/colors.dart'; import 'package:felexo/Screens/landing-page.dart'; import 'package:felexo/Views/main-view.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:google_sign_in/google_sign_in.dart'; final GoogleSignIn _googleSignIn = GoogleSignIn(); final FirebaseAuth _auth = FirebaseAuth.instance; // ignore: missing_return Future<String> signInWithGoogle(BuildContext context) async { try { final GoogleSignInAccount googleSignInAccount = await _googleSignIn.signIn(); final GoogleSignInAuthentication googleSignInAuthentication = await googleSignInAccount.authentication; final AuthCredential authCredential = GoogleAuthProvider.credential( idToken: googleSignInAuthentication.idToken, accessToken: googleSignInAuthentication.accessToken); final User user = (await _auth.signInWithCredential(authCredential)).user; assert(!user.isAnonymous); assert(await user.getIdToken() != null); final User currentUser = _auth.currentUser; assert(user.uid == currentUser.uid); assert(user.email != null); assert(user.uid != null); assert(user.photoURL != null); print("UID: " + user.uid); DocumentReference documentReference = FirebaseFirestore.instance.collection("User").doc(user.uid.toString()); documentReference.get().then((value) { if (!value.exists) { FirebaseFirestore.instance.collection("User").doc(user.uid).set({ "uid": user.uid, "displayName": user.displayName, "email": user.email, "verified": "false", "storeHistory": true, "subscribedToNotifications": true, }); } }); FirebaseFirestore.instance .collection("User") .doc(_auth.currentUser.uid) .snapshots() .forEach((element) { if (element.data()["subscribedToNotifications"].toString() == "null") { FirebaseFirestore.instance .collection("User") .doc(_auth.currentUser.uid) .update({"subscribedToNotifications": true}); } if (element.data()["subscribedToNotifications"].toString() == null) { FirebaseFirestore.instance .collection("User") .doc(_auth.currentUser.uid) .update({"subscribedToNotifications": true}); } }); Navigator.pushAndRemoveUntil(context, CupertinoPageRoute(builder: (context) => MainView()), (route) => false); } catch (e) { String message = e.message; if (e is PlatformException) { showDialog( context: context, builder: (context) => AlertDialog( backgroundColor: cardColor, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8), side: BorderSide(color: Colors.black, width: 3)), title: Text( "Error", style: TextStyle(fontFamily: 'Theme Bold', color: textColor), ), content: Text( "$message", style: TextStyle(fontFamily: 'Theme Bold', color: textColor), ), actions: [ // ignore: deprecated_member_use FlatButton( child: Text( "OK", style: TextStyle(fontFamily: 'Theme Bold', color: textColor), ), onPressed: () { Navigator.pop(context); }, ) ], )); } else { showDialog( context: context, builder: (context) => AlertDialog( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8), side: BorderSide(color: Colors.black, width: 8)), title: Text( "ERROR", style: TextStyle(fontFamily: 'Theme Bold', color: textColor), ), content: Text( "SOMETHING IS WRONG PLEASE TRY AGAIN", style: TextStyle(fontFamily: 'Theme Bold', color: textColor), ), actions: [ // ignore: deprecated_member_use FlatButton( child: Text( "OK", style: TextStyle(fontFamily: 'Theme Bold', color: textColor), ), onPressed: () { Navigator.pop(context); }, ) ], )); } } } void signOutGoogle(BuildContext context) async { await _auth.signOut(); await _googleSignIn.signOut(); Navigator.pushAndRemoveUntil( context, CupertinoPageRoute(builder: (context) => LandingPage()), (route) => false); }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Services/push-notifications.dart
import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; const AndroidNotificationChannel channel = AndroidNotificationChannel( "curated_channel", "Curated Channel", "This Channel is used for Curated Notification"); final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); Future<void> fcmBackgroundHandler(RemoteMessage message) async { await Firebase.initializeApp(); print("FCM INITIALIZED: ${message.messageId}"); print("FCM MESSAGE DATA: ${message.data}"); } class PushNotificationService { initialize() async { await Firebase.initializeApp(); FirebaseMessaging.onBackgroundMessage(fcmBackgroundHandler); await flutterLocalNotificationsPlugin .resolvePlatformSpecificImplementation< AndroidFlutterLocalNotificationsPlugin>() ?.createNotificationChannel(channel); var initializationSettingsAndroid = AndroidInitializationSettings('@drawable/ic_stat_f'); var initializationSettings = InitializationSettings(android: initializationSettingsAndroid); flutterLocalNotificationsPlugin.initialize(initializationSettings); FirebaseMessaging.onMessage.listen((RemoteMessage remoteMessage) { RemoteNotification remoteNotification = remoteMessage.notification; AndroidNotification androidNotification = remoteMessage.notification?.android; if (remoteNotification != null && androidNotification != null) { flutterLocalNotificationsPlugin.show( remoteNotification.hashCode, remoteNotification.title, remoteNotification.body, NotificationDetails( android: AndroidNotificationDetails( channel.id, channel.name, channel.description, enableVibration: true, priority: Priority.high, channelShowBadge: true, icon: androidNotification?.smallIcon))); } }); } Future<String> getToken() async { String tokenFcm = await FirebaseMessaging.instance.getToken(); print("FCM TOKEN: " + tokenFcm); return tokenFcm; } subscribeToTopic(String topic) async { await FirebaseMessaging.instance.subscribeToTopic(topic); } unSubscribeToTopic(String topic) async { await FirebaseMessaging.instance.unsubscribeFromTopic(topic); } }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Services/animation-route.dart
import 'package:flutter/material.dart'; class ScaleRoute extends PageRouteBuilder { final Widget page; ScaleRoute(context, {this.page}) : super( pageBuilder: ( BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, ) => page, transitionsBuilder: ( BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child, ) => ScaleTransition( scale: Tween<double>( begin: 0.0, end: 1.0, ).animate( CurvedAnimation( parent: animation, curve: Curves.fastOutSlowIn, ), ), child: child, ), ); } class SizeRoute extends PageRouteBuilder { final Widget page; SizeRoute(BuildContext context, {this.page}) : super( pageBuilder: ( BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, ) => page, transitionsBuilder: ( BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child, ) => Align( child: SizeTransition( sizeFactor: animation, child: child, ), ), ); }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Services/favorites-list.dart
import 'package:felexo/Color/colors.dart'; import 'package:felexo/Views/wallpaper-view.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:lottie/lottie.dart'; import 'package:provider/provider.dart'; class FavoritesList extends StatefulWidget { @override _FavoritesListState createState() => _FavoritesListState(); } class _FavoritesListState extends State<FavoritesList> { final FirebaseAuth _auth = FirebaseAuth.instance; User user; var foregroundColor; @override void initState() { super.initState(); initUser(); } initUser() async { user = _auth.currentUser; assert(user.email != null); assert(user.uid != null); assert(user.photoURL != null); setState(() {}); } @override Widget build(BuildContext context) { final favorites = Provider.of<List<Favorites>>(context); if (favorites.length.toInt() == 0) { return Center( child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Lottie.asset("assets/lottie/404.json", width: 150, height: 150) ], ), Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Text("NO FAVORITES ADDED YET!", style: Theme.of(context).textTheme.headline6), ], ) ], ), ); } if (favorites.length != null) { return GridView.count( shrinkWrap: true, crossAxisCount: 2, physics: BouncingScrollPhysics(), childAspectRatio: 0.6, padding: EdgeInsets.symmetric(horizontal: 0, vertical: 0), mainAxisSpacing: 0.0, crossAxisSpacing: 0.0, children: favorites.map((favorite) { foregroundColor = Hexcolor(favorite.avgColor).computeLuminance() > 0.5 ? Colors.black : Colors.white; setState(() {}); return GridTile( child: Material( type: MaterialType.card, shadowColor: Theme.of(context).backgroundColor, elevation: 5, borderRadius: BorderRadius.circular(0), child: Container( decoration: BoxDecoration( color: Hexcolor(favorite.avgColor), borderRadius: BorderRadius.circular(0), shape: BoxShape.rectangle), child: Stack(children: [ Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Padding( padding: EdgeInsets.only(bottom: 0), ), Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Text( "LOADING IMAGES", style: TextStyle( color: foregroundColor, fontFamily: 'Theme Black'), ) ], ) ], ), GestureDetector( child: ClipRRect( borderRadius: BorderRadius.circular(0), child: Image.network( favorite.imgUrl, height: 800, fit: BoxFit.fill, )), onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => WallPaperView( avgColor: favorite.avgColor, uid: user.uid, imgUrl: favorite.imgUrl, originalUrl: favorite.originalUrl, photoID: favorite.photoID.toString(), photographer: favorite.photographer, photographerID: favorite.photographerID, photographerUrl: favorite.photographerUrl))); }, ), GestureDetector( onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => WallPaperView( avgColor: favorite.avgColor, uid: user.uid, imgUrl: favorite.imgUrl, originalUrl: favorite.originalUrl, photoID: favorite.photoID.toString(), photographer: favorite.photographer, photographerID: favorite.photographerID, photographerUrl: favorite.photographerUrl))); }, ) ]), ), ), ); }).toList(), ); } return Center( child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ CircularProgressIndicator( valueColor: AlwaysStoppedAnimation(Theme.of(context).colorScheme.primary), ), Text( "FINDING FAVORITES...", style: TextStyle(fontFamily: 'Theme Bold'), ) ], ), ); } } class Favorites { final String imgUrl; final String originalUrl; final String photographerUrl; final String photoID; final String photographerID; final String photographer; final String avgColor; Favorites( {this.imgUrl, this.originalUrl, this.photoID, this.photographer, this.photographerID, this.avgColor, this.photographerUrl}) : assert(imgUrl != null), assert(originalUrl != null), assert(photoID != null), assert(avgColor != null), assert(photographer != null), assert(photographerID != null), assert(photographerUrl != null); }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Widget/categories-tile.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:felexo/Services/categories-list.dart'; import 'package:felexo/Views/categoriesResult-view.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_parallax/flutter_parallax.dart'; class CategoriesTile extends StatelessWidget { final Categories categories; CategoriesTile({this.categories}); @override Widget build(BuildContext context) { return GestureDetector( child: Stack( children: [ Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(0), color: Theme.of(context).scaffoldBackgroundColor), child: ClipRRect( borderRadius: BorderRadius.circular(0), child: Parallax.inside( child: CachedNetworkImage( fit: BoxFit.fill, imageUrl: categories.imgUrl, ), mainAxisExtent: 200.0, direction: AxisDirection.up, flipDirection: true, ), ), ), Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Container( width: MediaQuery.of(context).size.width, height: 200, decoration: BoxDecoration( gradient: LinearGradient(colors: [ Colors.black.withOpacity(0.0), Colors.black.withOpacity(0.1), Colors.black.withOpacity(0.2), Colors.black.withOpacity(0.4), Colors.black.withOpacity(0.5), Colors.black.withOpacity(0.6), Colors.black.withOpacity(0.7), Colors.black.withOpacity(0.8), Colors.black.withOpacity(0.9), ], begin: Alignment.topCenter, end: Alignment.bottomCenter)), padding: EdgeInsets.symmetric(horizontal: 10, vertical: 75), alignment: Alignment.bottomRight, child: Text( categories.categoryName.toUpperCase(), style: TextStyle( shadows: [ BoxShadow( color: Colors.black, blurRadius: 20, spreadRadius: 10) ], letterSpacing: 5, fontSize: 25, fontFamily: 'Theme Bold', color: Colors.white), ), ), ], ) ], ), onTap: () { Navigator.push( context, CupertinoPageRoute( builder: (context) => CategoriesResult( categoryName: categories.categoryName, ))); }, ); } }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Widget/gridView.dart
import 'dart:convert'; import 'package:felexo/Color/colors.dart'; import 'package:felexo/Data/data.dart'; import 'package:felexo/Services/animation-route.dart'; import 'package:felexo/Views/views.dart'; import 'package:felexo/model/wallpapers-model.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'package:shimmer_animation/shimmer_animation.dart'; import '../Color/colors.dart'; class Curated extends StatefulWidget { @override _CuratedState createState() => _CuratedState(); } class _CuratedState extends State<Curated> { List<WallpaperModel> wallpapers = []; bool _buttonVisible = false; bool loading = true; String wallpaperLocation, uid, imgUrl, originalUrl, photoID, photographer, photographerID, avgColor, nextPage, prevPage, photographerUrl; int noOfImages = 20; int pageNumber = 1; bool imagesLoaded = false; bool moreVisible = false; bool _foundLast = false; User user; var foregroundColor; Uri uri = Uri.parse( "https://api.pexels.com/v1/collections/thnxj4c?page=1&per_page=10&type=photos"); @override void initState() { initUser(); getLastPage(); _buttonVisible = true; super.initState(); } getLastPage() async { while (_foundLast == false) { var response = await http.get(uri, headers: { "Authorization": apiKey }); // print(response.body.toString()); Map<String, dynamic> jsonData = jsonDecode(response.body); print("NEXTLOOP: " + jsonData["next_page"].toString()); nextPage = jsonData["next_page"]; if (nextPage == null) { print("URI: " + uri.toString()); print("NEXT PAGE: " + nextPage.toString()); getTrendingWallpapers(uri); _foundLast = true; } else { setState(() { uri = Uri.parse(nextPage); }); } } } Future<List> getTrendingWallpapers(Uri _uri) async { var response = await http.get(_uri, headers: {"Authorization": apiKey}); // print(response.body.toString()); Map<String, dynamic> jsonData = jsonDecode(response.body); print("NEXT: " + jsonData["prev_page"].toString()); prevPage = jsonData["prev_page"].toString(); print("TOTAL RESULTS: " + jsonData['total_results'].toString()); if (prevPage == "null") { setState(() { loading = false; }); } jsonData["media"].forEach((element) { WallpaperModel wallpaperModel = new WallpaperModel(); wallpaperModel = WallpaperModel.fromMap(element); wallpapers.add(wallpaperModel); }); wallpapers = wallpapers.reversed.toList(); imagesLoaded = true; setState(() {}); return wallpapers; } Future<List> getMoreWallpapers() async { var response = await http.get(Uri.parse(prevPage), headers: {"Authorization": apiKey}); Map<String, dynamic> jsonData = jsonDecode(response.body); jsonData["media"].forEach((element) { WallpaperModel wallpaperModel = new WallpaperModel(); wallpaperModel = WallpaperModel.fromMap(element); wallpapers.add(wallpaperModel); }); // print("Next" + jsonData["next_page"].toString()); prevPage = jsonData["prev_page"].toString(); if (prevPage == "null") { setState(() { loading = false; }); } moreVisible = false; _buttonVisible = !_buttonVisible; setState(() {}); return wallpapers; } Future initUser() async { user = FirebaseAuth.instance.currentUser; assert(user.email != null); assert(user.uid != null); assert(user.photoURL != null); // print("User: " + user.uid.toString()); uid = user.uid.toString(); } @override void dispose() { super.dispose(); } @override Widget build(BuildContext context) { return imagesLoaded ? Column( children: [ SingleChildScrollView( child: GridView.count( shrinkWrap: true, crossAxisCount: 2, physics: BouncingScrollPhysics(), childAspectRatio: 0.6, padding: EdgeInsets.symmetric(horizontal: 0, vertical: 0), mainAxisSpacing: 0.0, crossAxisSpacing: 0.0, children: wallpapers.map((wallpaper) { foregroundColor = Hexcolor(wallpaper.avgColor).computeLuminance() > 0.5 ? Colors.black : Colors.white; setState(() {}); return GridTile( child: Container( decoration: BoxDecoration( color: Hexcolor(wallpaper.avgColor), borderRadius: BorderRadius.circular(0), shape: BoxShape.rectangle), child: Stack(children: [ Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Padding( padding: EdgeInsets.only(bottom: 0), ), Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Text( loadingMessage, style: TextStyle( color: foregroundColor, fontFamily: 'Theme Bold'), ) ], ), ], ), ClipRRect( borderRadius: BorderRadius.circular(0), child: Image.network( wallpaper.src.portrait, height: 800, fit: BoxFit.fill, )), GestureDetector( onTap: () { Navigator.push( context, ScaleRoute(context, page: WallPaperView( avgColor: wallpaper.avgColor.toString(), uid: uid, photographerUrl: wallpaper.photographerUrl, imgUrl: wallpaper.src.portrait, originalUrl: wallpaper.src.original, photoID: wallpaper.photoID.toString(), photographer: wallpaper.photographer, photographerID: wallpaper.photographerId.toString(), ))); }, ) ]), ), ); }).toList(), )), SizedBox( height: 0, ), loading ? Align( alignment: Alignment.bottomCenter, child: Visibility( visible: !_buttonVisible, child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox( height: 10, ), Container( width: MediaQuery.of(context).size.width - 20, height: 60, child: Shimmer( child: ElevatedButton( onPressed: () { _buttonVisible = !_buttonVisible; setState(() {}); getMoreWallpapers(); }, style: ElevatedButton.styleFrom( elevation: 0, primary: Theme.of(context) .scaffoldBackgroundColor, onPrimary: Theme.of(context).colorScheme.primary, onSurface: Theme.of(context).colorScheme.primary, shape: RoundedRectangleBorder( side: BorderSide( color: Theme.of(context) .accentColor .withOpacity(0.5), width: 1), borderRadius: BorderRadius.circular(00)), ), child: Text( loadingMessage, style: TextStyle( fontFamily: 'Theme Bold', color: Theme.of(context) .colorScheme .primary), ), ), ), ), SizedBox( height: 10, ), ], ), ), ) : Container(), loading ? Align( alignment: Alignment.bottomCenter, child: Visibility( visible: _buttonVisible, child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox( height: 10, ), Container( width: MediaQuery.of(context).size.width - 20, height: 60, child: ElevatedButton( onPressed: () { _buttonVisible = !_buttonVisible; setState(() {}); getMoreWallpapers(); }, style: ElevatedButton.styleFrom( elevation: 0, primary: Theme.of(context).scaffoldBackgroundColor, onPrimary: Theme.of(context).colorScheme.primary, onSurface: Theme.of(context).colorScheme.primary, shape: RoundedRectangleBorder( side: BorderSide( color: Theme.of(context) .accentColor .withOpacity(0.5), width: 1), borderRadius: BorderRadius.circular(00)), ), child: Text( loadMoreMessage, style: TextStyle( fontFamily: 'Theme Bold', color: Theme.of(context) .colorScheme .primary), ), ), ), SizedBox( height: 10, ), ], ), ), ) : Container(), ], ) : Shimmer( child: Container( width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height, )); } }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Widget/widgets.dart
export 'gridView.dart'; export 'categories-tile.dart'; export 'favorite-tile.dart'; export 'gridSearchView.dart'; export 'collectionResultPreview.dart'; export 'collectionsResultsGrid.dart'; export 'collectionResultPreview.dart';
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Widget/gridSearchView.dart
import 'package:felexo/Color/colors.dart'; import 'package:felexo/Data/data.dart'; import 'package:felexo/Services/animation-route.dart'; import 'package:felexo/Views/wallpaper-view.dart'; import 'package:felexo/model/wallpapers-model.dart'; import 'package:flutter/material.dart'; import '../Color/colors.dart'; Widget wallpaperSearchGrid( {@required List<WallpaperModel> wallpapers, @required context, @required String uid}) { return Column( children: [ Container( child: GridView.count( shrinkWrap: true, crossAxisCount: 2, physics: ClampingScrollPhysics(), childAspectRatio: 0.6, padding: EdgeInsets.symmetric(horizontal: 0, vertical: 0), mainAxisSpacing: 0.0, crossAxisSpacing: 0.0, children: wallpapers.map((wallpaper) { var foreGroundColor = Hexcolor(wallpaper.avgColor).computeLuminance() > 0.5 ? Colors.black : Colors.white; return GridTile( child: Material( type: MaterialType.card, shadowColor: Theme.of(context).backgroundColor, elevation: 5, borderRadius: BorderRadius.circular(0), child: Container( decoration: BoxDecoration( color: Hexcolor(wallpaper.avgColor), borderRadius: BorderRadius.circular(0), shape: BoxShape.rectangle), child: Stack(children: [ Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Padding( padding: EdgeInsets.only(bottom: 10), ), Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Text( loadingMessage, style: TextStyle( color: foreGroundColor, fontFamily: 'Theme Bold'), ) ], ) ], ), Hero( tag: wallpaper, child: GestureDetector( child: ClipRRect( borderRadius: BorderRadius.circular(0), child: Image.network( wallpaper.src.portrait, height: 800, fit: BoxFit.fill, )), onTap: () { Navigator.push( context, ScaleRoute(context, page: WallPaperView( avgColor: wallpaper.avgColor, uid: uid, photographerUrl: wallpaper.photographerUrl, imgUrl: wallpaper.src.portrait, originalUrl: wallpaper.src.original, photoID: wallpaper.photoID.toString(), photographer: wallpaper.photographer, photographerID: wallpaper.photographerId.toString(), ))); }, ), ), GestureDetector( onTap: () { Navigator.push( context, ScaleRoute(context, page: WallPaperView( avgColor: wallpaper.avgColor.toString(), uid: uid, photographerUrl: wallpaper.photographerUrl, imgUrl: wallpaper.src.portrait, originalUrl: wallpaper.src.original, photoID: wallpaper.photoID.toString(), photographer: wallpaper.photographer, photographerID: wallpaper.photographerId.toString(), ))); }, // child: Padding( // padding: const EdgeInsets.only(top: 200.0), // child: Container( // height: 200, // decoration: BoxDecoration( // borderRadius: BorderRadius.circular(0), // gradient: LinearGradient( // colors: [ // Colors.transparent, // Colors.black12, // Colors.black38, // Colors.black45 // ], // begin: Alignment.center, // end: Alignment.bottomCenter)), // child: Padding( // padding: const EdgeInsets.all(8.0), // child: Column( // crossAxisAlignment: CrossAxisAlignment.end, // mainAxisAlignment: MainAxisAlignment.end, // children: [ // Row( // children: [ // Align( // alignment: Alignment.bottomLeft, // child: AutoSizeText( // wallpaper.photographer, // style: TextStyle( // color: textColor, // fontFamily: 'Theme Bold', // fontSize: 20), // maxLines: 1, // minFontSize: 5, // maxFontSize: 8, // ), // ), // ], // ), // Row( // children: [ // Align( // alignment: Alignment.bottomLeft, // child: AutoSizeText( // wallpaper.photographerId.toString(), // style: TextStyle( // color: textColor, // fontFamily: 'Theme Bold', // fontSize: 15), // maxLines: 1, // minFontSize: 5, // maxFontSize: 10, // ), // ), // ], // ) // ], // ), // ), // ), // ), ) // Padding( // padding: const EdgeInsets.only(bottom: 15.0), // child: Align( // alignment: Alignment.bottomRight, // child: Hero( // tag: wallpaper.src.portrait, // child: IconButton( // iconSize: 24, // onPressed: () { // Navigator.push( // context, // FadeRoute(context, // page: WallPaperView( // imgUrl: wallpaper.src.portrait, // photoID: wallpaper.photoID.toString(), // photographer: wallpaper.photographer, // photographerID: // wallpaper.photographerId.toString(), // ))); // }, // icon: Icon( // Icons.open_in_new, // color: Colors.black, // ), // splashColor: secondaryColor, // ), // ), // ), // ) ]), ), ), ); }).toList(), ), ), ], ); }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Widget/collectionsGridView.dart
import 'dart:convert'; import 'package:auto_size_text_pk/auto_size_text_pk.dart'; import 'package:felexo/Data/data.dart'; import 'package:felexo/Model/collections-model.dart'; import 'package:felexo/Model/wallpapers-model.dart'; import 'package:felexo/Views/collectionsResultView.dart'; import 'package:felexo/Widget/widgets.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:http/http.dart' as http; import 'package:shimmer_animation/shimmer_animation.dart'; class CollectionsGrid extends StatefulWidget { @override _CollectionsGridState createState() => _CollectionsGridState(); } class _CollectionsGridState extends State<CollectionsGrid> { List<CollectionsModel> collections = []; List<WallpaperModel> collectionsResult = []; String collectionID; int totalResults; SliverGridDelegate gridDelegate; bool hasDesc = false; bool isLoading = true; @override void initState() { getCollections(); super.initState(); } getCollections() async { var response = await http.get( Uri.parse("https://api.pexels.com/v1/collections?page=1&per_page=80"), headers: {"Authorization": apiKey}); Map<String, dynamic> jsonData = jsonDecode(response.body); totalResults = jsonData["total_results"]; // print("COLLECTIONTOTAL " + jsonData["total_results"].toString()); jsonData["collections"].forEach((element) { CollectionsModel collectionsModel = new CollectionsModel(); collectionsModel = CollectionsModel.fromMap(element); if (element['id'] != "thnxj4c") { collections.add(collectionsModel); } }); setState(() { isLoading = false; }); } @override Widget build(BuildContext context) { return isLoading ? Shimmer( duration: Duration(seconds: 3), interval: Duration(seconds: 0), color: Theme.of(context).colorScheme.primary.withOpacity(0.5), enabled: true, direction: ShimmerDirection.fromLTRB(), child: Container( width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height, color: Theme.of(context).scaffoldBackgroundColor, ), ) : SingleChildScrollView( child: GridView.count( shrinkWrap: true, crossAxisCount: 1, physics: BouncingScrollPhysics(), childAspectRatio: 1.2, padding: const EdgeInsets.symmetric(horizontal: 0, vertical: 0), mainAxisSpacing: 0, crossAxisSpacing: 0, children: collections.map((collection) { setState(() {}); return Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Column( children: [ InkWell( onTap: () { Navigator.push( context, CupertinoPageRoute( builder: (context) => CRView( collectionID: collection.collectionId, collectionName: collection.collectionTitle, ))); }, child: CRPreview( collectionsID: collection.collectionId.toString())), SizedBox( height: 5, ), Center( child: Padding( padding: const EdgeInsets.only(left: 20.0, right: 20), child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(0), border: Border.all( color: Theme.of(context) .accentColor .withOpacity(0.5), width: 1), color: Theme.of(context).cardColor, ), width: MediaQuery.of(context).size.width - 10, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Padding( padding: const EdgeInsets.only( left: 10.0, top: 10, bottom: 10), child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.start, children: [ AutoSizeText( collection.collectionTitle .toUpperCase(), maxFontSize: 24, minFontSize: 14, style: TextStyle( color: Theme.of(context) .colorScheme .primary, fontFamily: 'Theme Black'), ), ], ), Row( mainAxisAlignment: MainAxisAlignment.start, children: [ Text( collection.collectionDescription .toUpperCase(), style: TextStyle( fontSize: 10, color: Theme.of(context) .colorScheme .primary), ), ], ), ], ), ), Padding( padding: const EdgeInsets.only(right: 10.0), child: Row( children: [ Icon( Icons.photo_library_outlined, size: 14, color: Theme.of(context) .colorScheme .primary, ), SizedBox( width: 5, ), Text( collection.photosCount, style: TextStyle( color: Theme.of(context) .colorScheme .primary, ), ) ], ), ) ], )), ), ), ], ), ], ); }).toList(), ), ); } }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Widget/collectionResultPreview.dart
import 'dart:convert'; import 'package:felexo/Color/colors.dart'; import 'package:felexo/Data/data.dart'; import 'package:felexo/Model/wallpapers-model.dart'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; class CRPreview extends StatefulWidget { final String collectionsID; CRPreview({@required this.collectionsID}); @override _CRPreviewState createState() => _CRPreviewState(); } class _CRPreviewState extends State<CRPreview> { List<WallpaperModel> crPreview = []; String p1; String p2; String p3; bool _p3avail = false; int totalResults; var foregroundColor; getPreviews() async { var response = await http.get( Uri.parse("https://api.pexels.com/v1/collections/" + widget.collectionsID + "?&type=photos&page=1&per_page=80"), headers: {"Authorization": apiKey}); Map<String, dynamic> jsonData = jsonDecode(response.body); // print("TOTALRESULTS " + jsonData["total_results"].toString()); totalResults = (jsonData["total_results"] - 2); jsonData["media"].forEach((element) { WallpaperModel wallpaperModel = new WallpaperModel(); wallpaperModel = WallpaperModel.fromMap(element); crPreview.add(wallpaperModel); }); // print("LENGTH " + crPreview.length.toString()); p1 = crPreview.last.src.portrait; p2 = crPreview.first.src.portrait; if (totalResults != 0) { _p3avail = true; foregroundColor = Hexcolor(crPreview[2].avgColor).computeLuminance() > 0.5 ? Colors.black : Colors.white; p3 = crPreview[2].src.portrait; } // print(totalResults); setState(() {}); // print(response.body.toString()); } @override void initState() { getPreviews(); super.initState(); } @override Widget build(BuildContext context) { return Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ ClipRRect( borderRadius: BorderRadius.only( topLeft: Radius.circular(0), bottomLeft: Radius.circular(0)), child: Image.network( p1 ?? loadingAnimation, width: MediaQuery.of(context).size.width / 2, height: 250, fit: BoxFit.cover, errorBuilder: (BuildContext context, Object exception, StackTrace trace) { return Container( color: Theme.of(context).colorScheme.primary, ); }, ), ), Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ ClipRRect( borderRadius: BorderRadius.only(topRight: Radius.circular(0)), child: Image.network( p2 ?? loadingAnimation, width: MediaQuery.of(context).size.width / 2.47, height: 160, errorBuilder: (BuildContext context, Object exception, StackTrace trace) { return Container( color: Theme.of(context).colorScheme.primary, ); }, fit: BoxFit.cover, ), ), _p3avail ? Stack( children: [ Container( width: MediaQuery.of(context).size.width / 2.47, height: 90, child: ClipRRect( borderRadius: BorderRadius.only( bottomRight: Radius.circular(0)), child: Image.network( p3 ?? loadingAnimation, fit: BoxFit.cover, errorBuilder: (BuildContext context, Object exception, StackTrace trace) { return Container( color: Theme.of(context).colorScheme.primary, ); }, ), ), ), Container( width: MediaQuery.of(context).size.width / 2.47, height: 90, decoration: BoxDecoration( color: foregroundColor.withOpacity(0.3) ?? Theme.of(context).scaffoldBackgroundColor, borderRadius: BorderRadius.only( bottomRight: Radius.circular(0))), child: Center( child: Text( "VIEW MORE", style: TextStyle( color: foregroundColor, fontFamily: 'Theme Bold', fontSize: 16), ), )), ], ) : Container( width: 160, height: 90, // color: // Theme.of(context).colorScheme.primary.withOpacity(0.5), child: Center( child: Text("VIEW MORE"), )) ], ) ], ); } }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Widget/wallpaper-controls.dart
import 'dart:io'; import 'dart:typed_data'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:dio/dio.dart'; import 'package:felexo/Views/views.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:image_gallery_saver/image_gallery_saver.dart'; import 'package:path_provider/path_provider.dart'; import 'package:permission/permission.dart'; import 'package:wallpaper_manager/wallpaper_manager.dart'; // import 'package:toast/toast.dart'; const String testDevices = "10541B246DA05AC314ED0A170DA2B594"; String home = "Home Screen"; String lock = "Lock Screen"; String both = "Both Screen"; String system = "System"; String res; String pexelsText = "Wallpapers Provided by Pexels"; bool deletingFav = false; bool downloading = false; bool setWall = false; User user; String wallpaperLocation; // ignore: must_be_immutable class WallpaperControls extends StatefulWidget { final String imgUrl, photoID, photographer, photographerID, originalUrl, photographerUrl, uid, avgColor; var foregroundColor; bool favExists; WallpaperControls( {@required this.uid, @required this.imgUrl, @required this.originalUrl, @required this.photoID, @required this.photographer, @required this.photographerID, @required this.photographerUrl, @required this.avgColor, @required this.favExists, @required this.foregroundColor}); @override _WallpaperControlsState createState() => _WallpaperControlsState(); } class _WallpaperControlsState extends State<WallpaperControls> { bool _permissionStatus; double progressValue; String progressString = "0%"; @override void initState() { downloading = false; checkPermissionStatus(); setState(() {}); super.initState(); } @override void dispose() { super.dispose(); } initUser() async { user = FirebaseAuth.instance.currentUser; assert(user.email != null); assert(user.uid != null); assert(user.photoURL != null); print("User: " + user.uid.toString()); setState(() {}); } checkPermissionStatus() async { List<Permissions> permissions = await Permission.getPermissionsStatus([PermissionName.Storage]); print("PERMISSION STATUS"); print(permissions.map((e) { print(e.permissionStatus); if (e.permissionStatus == PermissionStatus.allow) { _permissionStatus = true; setState(() {}); } if (e.permissionStatus == PermissionStatus.deny) { _permissionStatus = false; setState(() {}); } if (e.permissionStatus == PermissionStatus.notAgain) { _permissionStatus = false; setState(() {}); } })); print(_permissionStatus); } askPermission() async { // ignore: unused_local_variable List<Permissions> permissionNames = await Permission.requestPermissions([PermissionName.Storage]); checkPermissionStatus(); } @override Widget build(BuildContext context) { return downloading ? Padding( padding: const EdgeInsets.only(top: 54.0, bottom: 20), child: Column( children: [ Row( children: [ SizedBox( width: 280, height: 5, child: LinearProgressIndicator( value: progressValue, backgroundColor: Theme.of(context).colorScheme.primary.withAlpha(80), valueColor: AlwaysStoppedAnimation( Theme.of(context).colorScheme.primary), ), ), SizedBox( width: 10, ), Text( progressString, style: TextStyle( color: Theme.of(context).colorScheme.primary, fontSize: 10), ), ], ), Row( children: [ Text( "DOWNLOADING...", style: TextStyle( color: Theme.of(context).colorScheme.primary, fontSize: 10), ), ], ), ], ), ) : Container( width: 250, height: 85, color: Colors.transparent, child: Scaffold( backgroundColor: Colors.transparent, body: Padding( padding: const EdgeInsets.only(bottom: 0.0), child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ InkWell( onTap: () { HapticFeedback.heavyImpact(); saveDialog(context); }, child: controlButton( context, Icons.save_outlined)), ], ), SizedBox( width: 30, ), Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.center, children: [ InkWell( onTap: () { HapticFeedback.heavyImpact(); setWallpaperDialog(context); }, child: controlButton( context, Icons.wallpaper_outlined)), ], ), SizedBox( width: 30, ), GestureDetector( child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.center, children: [ Container( width: 50, height: 50, decoration: BoxDecoration( border: Border.all( color: Theme.of(context) .accentColor .withOpacity(0.5)), shape: BoxShape.circle, color: Theme.of(context).cardColor), child: Padding( padding: const EdgeInsets.all(8.0), child: Icon( widget.favExists ? Icons.favorite : Icons.favorite_border, size: 25, color: widget.favExists ? Colors.redAccent : Theme.of(context).colorScheme.primary, ), ), ) ], ), onTap: () async { HapticFeedback.heavyImpact(); if (widget.favExists == true) { favExistsDialog(context); } if (widget.favExists != true) { addToFav(); } }, ), // ], ), ], ), ), ), ); } addToFav() { FirebaseFirestore.instance .collection("User") .doc(user.uid) .collection("Favorites") .doc(widget.photoID) .set({ "imgUrl": widget.imgUrl, "photographer": widget.photographer, "photographerUrl": widget.photographerUrl, "photoID": widget.photoID.toString(), "photographerID": widget.photographerID.toString(), "originalUrl": widget.originalUrl, "avgColor": widget.avgColor, }); setState(() { widget.favExists = !widget.favExists; }); } favExistsDialog(BuildContext context) { FirebaseFirestore.instance .collection("User") .doc(user.uid) .collection("Favorites") .doc(widget.photoID) .delete() .whenComplete(() { setState(() { widget.favExists = !widget.favExists; }); }); } Future<dynamic> setWallpaperDialog(BuildContext context) { return showDialog( context: context, builder: (context) => AlertDialog( elevation: 0, shape: RoundedRectangleBorder( side: BorderSide( width: 1, color: Theme.of(context).accentColor.withOpacity(0.5)), borderRadius: BorderRadius.circular(0)), title: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Text("SELECT A LOCATION", style: Theme.of(context).textTheme.bodyText1), ], ), content: Container( height: 100, child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Padding( padding: const EdgeInsets.only(left: 10, right: 10), child: TextButton( child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Icon( Icons.home_outlined, size: 24, color: Theme.of(context).colorScheme.primary, ), Text( "HOME\nSCREEN", textAlign: TextAlign.center, style: TextStyle( fontSize: 10, fontFamily: 'Theme Bold', color: Theme.of(context).colorScheme.primary), ) ], ), onPressed: () async { Navigator.of(context).pop(); Future.delayed(Duration(seconds: 1), () { saveWallpaper(WallpaperManager.HOME_SCREEN); }); }, ), ), Padding( padding: const EdgeInsets.only(left: 10, right: 10), child: TextButton( child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Icon(Icons.lock_outlined, size: 24, color: Theme.of(context).colorScheme.primary), Text( "LOCK\nSCREEN", textAlign: TextAlign.center, style: TextStyle( fontSize: 10, fontFamily: 'Theme Bold', color: Theme.of(context).colorScheme.primary), ) ], ), onPressed: () async { Navigator.of(context).pop(); Future.delayed(Duration(seconds: 1), () { saveWallpaper(WallpaperManager.LOCK_SCREEN); }); }, ), ), Padding( padding: const EdgeInsets.only(left: 10, right: 0), child: TextButton( child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Icon(Icons.smartphone_outlined, size: 24, color: Theme.of(context).colorScheme.primary), Text( "BOTH\nSCREEN", textAlign: TextAlign.center, style: TextStyle( fontSize: 10, fontFamily: 'Theme Bold', color: Theme.of(context).colorScheme.primary), ) ], ), onPressed: () async { Navigator.of(context).pop(); Future.delayed(Duration(seconds: 1), () { saveWallpaper(WallpaperManager.BOTH_SCREENS); }); }, ), ), ], ), ))); } Container controlButton( BuildContext context, var iconStyle, ) { return Container( child: Container( width: 50, height: 50, decoration: BoxDecoration( shape: BoxShape.circle, border: Border.all(color: Theme.of(context).accentColor.withOpacity(0.5)), color: Theme.of(context).cardColor, ), child: Icon( iconStyle, size: 25, color: Theme.of(context).colorScheme.primary, ), ), ); } Future<dynamic> saveDialog(BuildContext context) { return showDialog( context: context, useSafeArea: true, builder: (context) => AlertDialog( elevation: 0, backgroundColor: Theme.of(context).cardColor, shape: RoundedRectangleBorder( side: BorderSide( width: 1, color: Theme.of(context).accentColor.withOpacity(0.5)), borderRadius: BorderRadius.circular(0)), title: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Text( "SELECT SIZE OF WALLPAPER", style: Theme.of(context).textTheme.bodyText1, ), ], ), content: Padding( padding: const EdgeInsets.all(8.0), child: Container( height: 80, child: ClipRRect( child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ TextButton( child: Column( children: [ Icon( Icons.smartphone, size: 24, color: Theme.of(context).colorScheme.primary, ), SizedBox( height: 10, ), Text( "PORTRAIT", style: TextStyle( fontSize: 10, fontFamily: 'Theme Bold', color: Theme.of(context).colorScheme.primary), ) ], ), onPressed: () async { Navigator.of(context).pop(); _save(widget.imgUrl, _permissionStatus, "p"); }, ), TextButton( child: Column( children: [ Icon(Icons.photo_size_select_actual_outlined, size: 24, color: Theme.of(context).colorScheme.primary), SizedBox( height: 10, ), Text( "ORIGINAL", style: TextStyle( fontSize: 10, fontFamily: 'Theme Bold', color: Theme.of(context).colorScheme.primary), ) ], ), onPressed: () async { Navigator.of(context).pop(); _save(widget.originalUrl, _permissionStatus, "o"); }, ), ], ), ), ), ))); } _save(String url, bool _permissionReceived, String type) async { String _type; if (type == "o") { _type = "ORIGINAL"; } if (type == "p") { _type = "PORTRAIT"; } var appDirectory = Directory("storage/emulated/0/Pictures/FELEXO"); if (!(await appDirectory.exists())) { appDirectory.createSync(recursive: true); } downloading = true; setState(() {}); if (_permissionStatus) { var response = await Dio().download( url, "storage/emulated/0/Pictures/FELEXO/" + widget.photographer + widget.photoID + " " + _type + ".jpg", options: Options(responseType: ResponseType.bytes), onReceiveProgress: (received, total) { if (total != -1) { progressValue = received / total; progressString = (received / total * 100).toStringAsFixed(0) + "%"; setState(() {}); print((received / total * 100).toStringAsFixed(0) + "%"); } }).whenComplete(() { downloading = false; setState(() {}); }); if (progressString == "100") { downloading = false; setState(() {}); } // var response = await Dio() // .get(url, options: Options(responseType: ResponseType.bytes), // onReceiveProgress: (received, total) { // if (total != -1) { // progressValue = received / total; // progressString = (received / total * 100).toStringAsFixed(0) + "%"; // setState(() {}); // print((received / total * 100).toStringAsFixed(0) + "%"); // } // }); final result = await ImageGallerySaver.saveImage( Uint8List.fromList(response.data), quality: 100, name: widget.photographer + widget.photoID.toString()); print(result); downloading = false; setState(() { progressString = "0%"; progressValue = 0; }); } if (!_permissionStatus) { showDialog( context: context, builder: (context) => AlertDialog( shape: RoundedRectangleBorder( side: BorderSide( width: 1, color: Theme.of(context).accentColor.withOpacity(0.5)), borderRadius: BorderRadius.circular(0)), elevation: 0, backgroundColor: Theme.of(context).colorScheme.secondary, title: Text("OOPS!", style: Theme.of(context).textTheme.bodyText1), content: Text("FILE PERMISSIONS ARE DENIED", style: Theme.of(context).textTheme.bodyText1), actions: [ TextButton( onPressed: () { askPermission(); Navigator.pop(context); }, child: Text("ASK PERMISSION", style: Theme.of(context).textTheme.button)), TextButton( child: Text("OK", style: Theme.of(context).textTheme.button), onPressed: () async { Navigator.of(context).pop(); }, ) ], )); } } saveWallpaper(int location) async { try { String url = widget.imgUrl; String originalUrl = widget.originalUrl; var file; showDialog( barrierDismissible: true, context: context, builder: (context) => AlertDialog( shape: RoundedRectangleBorder( side: BorderSide( width: 1, color: Theme.of(context).accentColor.withOpacity(0.5)), borderRadius: BorderRadius.circular(0)), elevation: 0, backgroundColor: Theme.of(context).colorScheme.secondary, title: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Text("CHOOSE TYPE", style: Theme.of(context).textTheme.bodyText1), ], ), content: Container( height: 80, child: ClipRRect( child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ TextButton( child: Column( children: [ Icon( Icons.compress_outlined, size: 24, color: Theme.of(context).colorScheme.primary, ), SizedBox( height: 10, ), Text( "COMPRESSED", style: TextStyle( fontSize: 10, fontFamily: 'Theme Bold', color: Theme.of(context).colorScheme.primary), ) ], ), onPressed: () async { Navigator.of(context).pop(); setWallpaper(file, url, location); }, ), TextButton( child: Column( children: [ Icon(Icons.photo_size_select_actual_outlined, size: 24, color: Theme.of(context).colorScheme.primary), SizedBox( height: 10, ), Text( "ORIGINAL", style: TextStyle( fontSize: 10, fontFamily: 'Theme Bold', color: Theme.of(context).colorScheme.primary), ) ], ), onPressed: () async { Navigator.of(context).pop(); setWallpaper(file, originalUrl, location); }, ), TextButton( child: Column( children: [ Icon(Icons.blur_on_outlined, size: 24, color: Theme.of(context).colorScheme.primary), SizedBox( height: 10, ), Text( "BLURRED", style: TextStyle( fontSize: 10, fontFamily: 'Theme Bold', color: Theme.of(context).colorScheme.primary), ) ], ), onPressed: () async { Navigator.of(context).pop(); Navigator.push( context, CupertinoPageRoute( builder: (context) => BlurWallpaperView( location: location, avgColor: widget.avgColor, photoID: widget.photoID, url: widget.originalUrl, photographer: widget.photographer, foregroundColor: widget.foregroundColor, ))); }, ), ], ), ), ), )); } catch (e) { print("Exception: " + e.message); } } Future<Null> setWallpaper(var file, String url, int location) async { setState(() { downloading = true; }); try { // final file = await DefaultCacheManager().getSingleFile(url); // var response = await http.get(Uri.parse(url)); // var filePath = // await ImagePickerSaver.saveFile(fileData: response.bodyBytes); var filePath = await getTemporaryDirectory(); print(filePath); var response = await Dio().get(url, options: Options( responseType: ResponseType.bytes, ), onReceiveProgress: (received, total) { if (total != -1) { setState(() { progressValue = received / total; progressString = (received / total * 100).toStringAsFixed(0) + "%"; }); // print((received / total * 100).toStringAsFixed(0) + "%"); } }); print(response.data); final result = await ImageGallerySaver.saveImage( Uint8List.fromList(response.data), quality: 100, name: widget.photographer + widget.photoID.toString()); print(result); try { final String result = await WallpaperManager.setWallpaperFromFile( "storage/emulated/0/Pictures/" + widget.photographer + widget.photoID.toString() + ".jpg", location, ).whenComplete(() { downloading = false; final file = File("storage/emulated/0/Pictures/" + widget.photographer + widget.photoID.toString() + ".jpg"); file.delete(); setState(() {}); HapticFeedback.heavyImpact(); Fluttertoast.showToast( msg: "Your wallpaper is set", toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.CENTER, timeInSecForIosWeb: 1, backgroundColor: Theme.of(context).colorScheme.primary, textColor: Theme.of(context).colorScheme.secondary, fontSize: 16.0); }); print(result); } catch (e) { print(e); } } catch (e) { print(e); } } }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Widget/collectionsResultsGrid.dart
import 'dart:convert'; import 'package:felexo/Color/colors.dart'; import 'package:felexo/Data/data.dart'; import 'package:felexo/Model/wallpapers-model.dart'; import 'package:felexo/Services/animation-route.dart'; import 'package:felexo/Views/views.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'package:shimmer_animation/shimmer_animation.dart'; class CRGrid extends StatefulWidget { final String collectionsID; CRGrid({@required this.collectionsID}); @override _CRGridState createState() => _CRGridState(); } class _CRGridState extends State<CRGrid> { List<WallpaperModel> wallpapers = []; bool _buttonVisible = false; bool loading = true; String wallpaperLocation, uid, imgUrl, originalUrl, photoID, photographer, photographerID, avgColor, nextPage, photographerUrl; int noOfImages = 20; int pageNumber = 1; bool imagesLoaded = false; bool moreVisible = false; User user; var foregroundColor; @override void initState() { initUser(); getTrendingWallpapers(); _buttonVisible = true; super.initState(); } Future<List> getTrendingWallpapers() async { var response = await http.get( Uri.parse("https://api.pexels.com/v1/collections/" + widget.collectionsID + "?&type=photos&page=$pageNumber&per_page=$noOfImages"), headers: {"Authorization": apiKey}); // print(response.body.toString()); Map<String, dynamic> jsonData = jsonDecode(response.body); print("NEXT: " + jsonData["next_page"].toString()); nextPage = jsonData["next_page"].toString(); if (nextPage == "null") { setState(() { loading = false; }); } jsonData["media"].forEach((element) { // print(element); WallpaperModel wallpaperModel = new WallpaperModel(); wallpaperModel = WallpaperModel.fromMap(element); wallpapers.add(wallpaperModel); }); // print("TrendingState"); imagesLoaded = true; setState(() {}); return wallpapers; } Future<List> getMoreWallpapers() async { var response = await http.get(Uri.parse(nextPage), headers: {"Authorization": apiKey}); Map<String, dynamic> jsonData = jsonDecode(response.body); jsonData["media"].forEach((element) { WallpaperModel wallpaperModel = new WallpaperModel(); wallpaperModel = WallpaperModel.fromMap(element); wallpapers.add(wallpaperModel); }); // print("Next" + jsonData["next_page"].toString()); nextPage = jsonData["next_page"].toString(); if (nextPage == "null") { setState(() { loading = false; }); } moreVisible = false; _buttonVisible = !_buttonVisible; setState(() {}); return wallpapers; } Future initUser() async { user = FirebaseAuth.instance.currentUser; assert(user.email != null); assert(user.uid != null); assert(user.photoURL != null); // print("User: " + user.uid.toString()); uid = user.uid.toString(); } @override void dispose() { super.dispose(); } @override Widget build(BuildContext context) { return imagesLoaded ? SafeArea( child: Column( children: [ SingleChildScrollView( child: GridView.count( shrinkWrap: true, crossAxisCount: 2, physics: BouncingScrollPhysics(), childAspectRatio: 0.6, padding: EdgeInsets.symmetric(horizontal: 0, vertical: 0), mainAxisSpacing: 0.0, crossAxisSpacing: 0.0, children: wallpapers.map((wallpaper) { foregroundColor = Hexcolor(wallpaper.avgColor).computeLuminance() > 0.5 ? Colors.black : Colors.white; setState(() {}); return GridTile( child: Material( type: MaterialType.card, shadowColor: Theme.of(context).backgroundColor, elevation: 5, borderRadius: BorderRadius.circular(0), child: Container( decoration: BoxDecoration( color: Hexcolor(wallpaper.avgColor), borderRadius: BorderRadius.circular(0), shape: BoxShape.rectangle), child: Stack(children: [ Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Padding( padding: EdgeInsets.only(bottom: 0), ), Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Text( loadingMessage, style: TextStyle( color: foregroundColor, fontFamily: 'Theme Bold'), ) ], ) ], ), GestureDetector( child: ClipRRect( borderRadius: BorderRadius.circular(0), child: Image.network( wallpaper.src.portrait, height: 800, fit: BoxFit.fill, )), onTap: () { Navigator.push( context, ScaleRoute(context, page: WallPaperView( avgColor: wallpaper.avgColor, uid: user.uid, photographerUrl: wallpaper.photographerUrl, imgUrl: wallpaper.src.portrait, originalUrl: wallpaper.src.original, photoID: wallpaper.photoID.toString(), photographer: wallpaper.photographer, photographerID: wallpaper .photographerId .toString(), ))); }, ), GestureDetector( onTap: () { Navigator.push( context, ScaleRoute(context, page: WallPaperView( avgColor: wallpaper.avgColor.toString(), uid: uid, photographerUrl: wallpaper.photographerUrl, imgUrl: wallpaper.src.portrait, originalUrl: wallpaper.src.original, photoID: wallpaper.photoID.toString(), photographer: wallpaper.photographer, photographerID: wallpaper .photographerId .toString(), ))); }, ) ]), ), ), ); }).toList(), )), loading ? Align( alignment: Alignment.bottomCenter, child: Visibility( visible: !_buttonVisible, child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox( height: 10, ), Container( width: MediaQuery.of(context).size.width - 20, height: 60, child: Shimmer( child: ElevatedButton( onPressed: () { _buttonVisible = !_buttonVisible; setState(() {}); getMoreWallpapers(); }, style: ElevatedButton.styleFrom( elevation: 0, primary: Theme.of(context) .scaffoldBackgroundColor, onPrimary: Theme.of(context).colorScheme.primary, onSurface: Theme.of(context).colorScheme.primary, shape: RoundedRectangleBorder( side: BorderSide( color: Theme.of(context) .accentColor .withOpacity(0.5), width: 1), borderRadius: BorderRadius.circular(00)), ), child: Text( loadingMessage, style: TextStyle( fontFamily: 'Theme Bold', color: Theme.of(context) .colorScheme .primary), ), ), ), ), SizedBox( height: 10, ), ], ), ), ) : Container(), loading ? Align( alignment: Alignment.bottomCenter, child: Visibility( visible: _buttonVisible, child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox( height: 10, ), Container( width: MediaQuery.of(context).size.width - 20, height: 60, child: ElevatedButton( onPressed: () { _buttonVisible = !_buttonVisible; setState(() {}); getMoreWallpapers(); }, style: ElevatedButton.styleFrom( elevation: 0, primary: Theme.of(context) .scaffoldBackgroundColor, onPrimary: Theme.of(context).colorScheme.primary, onSurface: Theme.of(context).colorScheme.primary, shape: RoundedRectangleBorder( side: BorderSide( color: Theme.of(context) .accentColor .withOpacity(0.5), width: 1), borderRadius: BorderRadius.circular(00)), ), child: Text( loadMoreMessage, style: TextStyle( fontFamily: 'Theme Bold', color: Theme.of(context) .colorScheme .primary), ), ), ), SizedBox( height: 10, ), ], ), ), ) : Container(), ], ), ) : Shimmer( child: Container( width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height, )); } }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Widget/favorite-tile.dart
import 'package:felexo/Data/data.dart'; import 'package:felexo/Services/favorites-list.dart'; import 'package:felexo/Views/wallpaper-view.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:felexo/Color/colors.dart'; class FavoriteTile extends StatefulWidget { final Favorites favorites; FavoriteTile({this.favorites}); @override _FavoriteTileState createState() => _FavoriteTileState(); } class _FavoriteTileState extends State<FavoriteTile> { User user; @override initState() { super.initState(); initUser(); } initUser() async { user = FirebaseAuth.instance.currentUser; assert(user.email != null); assert(user.uid != null); assert(user.photoURL != null); print("User: " + user.uid.toString()); setState(() {}); } @override Widget build(BuildContext context) { return Scaffold( body: Material( type: MaterialType.card, child: Container( height: 800, decoration: BoxDecoration( color: Hexcolor(widget.favorites.avgColor), borderRadius: BorderRadius.circular(0), shape: BoxShape.rectangle), child: Stack(alignment: Alignment.center, children: [ Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Padding( padding: EdgeInsets.only(bottom: 0), ), Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Text( loadingMessage, style: TextStyle( color: Theme.of(context).colorScheme.primary, fontFamily: 'Thene Bold'), ) ], ) ], ), GestureDetector( onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => WallPaperView( avgColor: widget.favorites.avgColor, uid: user.uid, imgUrl: widget.favorites.imgUrl, originalUrl: widget.favorites.originalUrl, photoID: widget.favorites.photoID.toString(), photographer: widget.favorites.photographer, photographerID: widget.favorites.photographerID, photographerUrl: widget.favorites.photographerUrl))); }, child: ClipRRect( child: Image.network( widget.favorites.imgUrl, height: 800, fit: BoxFit.fill, ), ), ), ]), ), ), ); } }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/theme/app-theme.dart
import 'package:felexo/Color/colors.dart'; import 'package:flutter/material.dart'; final ThemeData darkTheme = ThemeData( canvasColor: Colors.black, cardColor: Colors.black, dialogBackgroundColor: Colors.black, scaffoldBackgroundColor: backgroundColor, backgroundColor: Colors.black, accentColor: iconColor, primaryColor: Colors.black, primaryColorDark: Colors.white, appBarTheme: AppBarTheme( elevation: 0, centerTitle: true, color: Colors.black, textTheme: TextTheme( headline1: TextStyle(color: textColor, fontFamily: 'Theme Black'), headline2: TextStyle(color: textColor, fontFamily: 'Theme Black'), headline3: TextStyle(color: textColor, fontFamily: 'Theme Black'), headline4: TextStyle(color: textColor, fontFamily: 'Theme Black'), headline5: TextStyle(color: textColor, fontFamily: 'Theme Black'), headline6: TextStyle(color: textColor, fontFamily: 'Theme Bold'), subtitle1: TextStyle(color: textColor, fontFamily: 'Theme Regular'), subtitle2: TextStyle(color: textColor, fontFamily: 'Theme Regular'), bodyText1: TextStyle(color: textColor, fontFamily: 'Theme Regular'), bodyText2: TextStyle(color: textColor, fontFamily: 'Theme Regular'), caption: TextStyle(color: textColor, fontFamily: 'Theme Regular'), button: TextStyle(color: textColor, fontFamily: 'Theme Bold'), ), iconTheme: IconThemeData(color: iconColor)), colorScheme: ColorScheme.dark( primary: textColor, secondary: cardColor, ), inputDecorationTheme: InputDecorationTheme( hintStyle: TextStyle(color: textColor, fontFamily: 'Theme Bold'), labelStyle: TextStyle(color: textColor, fontFamily: 'Theme Bold'), ), textTheme: TextTheme( headline1: TextStyle(color: textColor, fontFamily: 'Theme Black'), headline2: TextStyle(color: textColor, fontFamily: 'Theme Black'), headline3: TextStyle(color: textColor, fontFamily: 'Theme Black'), headline4: TextStyle(color: textColor, fontFamily: 'Theme Black'), headline5: TextStyle(color: textColor, fontFamily: 'Theme Black'), headline6: TextStyle(color: textColor, fontFamily: 'Theme Bold'), subtitle1: TextStyle(color: textColor, fontFamily: 'Theme Regular'), subtitle2: TextStyle(color: textColor, fontFamily: 'Theme Regular'), bodyText1: TextStyle(color: textColor, fontFamily: 'Theme Regular'), bodyText2: TextStyle(color: textColor, fontFamily: 'Theme Regular'), caption: TextStyle(color: textColor, fontFamily: 'Theme Regular'), button: TextStyle(color: textColor, fontFamily: 'Theme Bold'), ), visualDensity: VisualDensity.adaptivePlatformDensity, ); final ThemeData lightTheme = ThemeData( canvasColor: Colors.white, cardColor: Colors.white, dialogBackgroundColor: Colors.white, scaffoldBackgroundColor: backgroundColorLight, backgroundColor: Colors.white, accentColor: iconColorLight, primaryColor: Colors.white, primaryColorDark: Colors.black, appBarTheme: AppBarTheme( elevation: 0, centerTitle: true, color: Colors.white, textTheme: TextTheme( headline1: TextStyle(color: Colors.black, fontFamily: 'Theme Black'), headline2: TextStyle(color: Colors.black, fontFamily: 'Theme Black'), headline3: TextStyle(color: Colors.black, fontFamily: 'Theme Black'), headline4: TextStyle(color: Colors.black, fontFamily: 'Theme Black'), headline5: TextStyle(color: Colors.black, fontFamily: 'Theme Black'), headline6: TextStyle(color: Colors.black, fontFamily: 'Theme Bold'), subtitle1: TextStyle(color: Colors.black, fontFamily: 'Theme Bold'), subtitle2: TextStyle(color: Colors.black, fontFamily: 'Theme Regular'), bodyText1: TextStyle(color: Colors.black, fontFamily: 'Theme Regular'), bodyText2: TextStyle(color: Colors.black, fontFamily: 'Theme Regular'), caption: TextStyle(color: Colors.black, fontFamily: 'Theme Regular'), button: TextStyle(color: Colors.black, fontFamily: 'Theme Bold'), ), iconTheme: IconThemeData(color: iconColor)), colorScheme: ColorScheme.light( primary: cardColor, secondary: textColor, ), inputDecorationTheme: InputDecorationTheme( hintStyle: TextStyle(color: Colors.black, fontFamily: 'Theme Bold'), labelStyle: TextStyle(color: Colors.black, fontFamily: 'Theme Bold'), ), textTheme: TextTheme( headline1: TextStyle(color: Colors.black, fontFamily: 'Theme Black'), headline2: TextStyle(color: Colors.black, fontFamily: 'Theme Black'), headline3: TextStyle(color: Colors.black, fontFamily: 'Theme Black'), headline4: TextStyle(color: Colors.black, fontFamily: 'Theme Black'), headline5: TextStyle(color: Colors.black, fontFamily: 'Theme Black'), headline6: TextStyle(color: Colors.black, fontFamily: 'Theme Bold'), subtitle1: TextStyle(color: Colors.black, fontFamily: 'Theme Regular'), subtitle2: TextStyle(color: Colors.black, fontFamily: 'Theme Regular'), bodyText1: TextStyle(color: Colors.black, fontFamily: 'Theme Regular'), bodyText2: TextStyle(color: Colors.black, fontFamily: 'Theme Regular'), caption: TextStyle(color: Colors.black, fontFamily: 'Theme Regular'), button: TextStyle(color: Colors.black, fontFamily: 'Theme Bold'), ), visualDensity: VisualDensity.adaptivePlatformDensity, ); class ThemeNotifier with ChangeNotifier { ThemeData _themeData; ThemeNotifier(this._themeData); getTheme() => _themeData; setTheme(ThemeData themeData) async { _themeData = themeData; notifyListeners(); } } class ThemeModeNotifier with ChangeNotifier { ThemeMode _mode; ThemeModeNotifier(this._mode); getMode() => _mode; setMode(ThemeMode mode) async { _mode = mode; notifyListeners(); } }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Model/similar-model.dart
class SimilarSearchTerms { String searchTerm1; String searchTerm2; String searchTerm3; String searchTerm4; SimilarSearchTerms( {this.searchTerm1, this.searchTerm2, this.searchTerm3, this.searchTerm4}); factory SimilarSearchTerms.fromMap(Map<String, dynamic> jsonData) { return SimilarSearchTerms( searchTerm1: jsonData[0].toString(), searchTerm2: jsonData[1].toString(), searchTerm3: jsonData[2].toString(), searchTerm4: jsonData[3].toString()); } }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Model/wallpapers-model.dart
class WallpaperModel { String photographer; String photographerUrl; int photographerId; int photoID; String avgColor; String nextPage; SourceModel src; WallpaperModel( {this.src, this.photoID, this.photographerUrl, this.photographerId, this.photographer, this.avgColor, this.nextPage}); factory WallpaperModel.fromMap(Map<String, dynamic> jsonData) { return WallpaperModel( src: SourceModel.fromMap(jsonData["src"]), photographerUrl: jsonData["photographer_url"], photographer: jsonData["photographer"], photographerId: jsonData["photographer_id"], photoID: jsonData["id"], avgColor: jsonData["avg_color"], nextPage: jsonData["next_page"]); } } class SourceModel { String original; String small; String portrait; SourceModel({this.original, this.portrait, this.small}); factory SourceModel.fromMap(Map<String, dynamic> jsonData) { return SourceModel( original: jsonData["original"], portrait: jsonData["portrait"], small: jsonData["small"]); } }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Model/collections-model.dart
class CollectionsModel { String collectionId; String collectionTitle; String collectionDescription; String photosCount; String totalResults; CollectionsModel({ this.collectionId, this.collectionTitle, this.collectionDescription, this.photosCount, this.totalResults, }); factory CollectionsModel.fromMap(Map<String, dynamic> jsonData) { return CollectionsModel( collectionId: jsonData["id"].toString(), collectionTitle: jsonData["title"].toString(), collectionDescription: jsonData["description"].toString(), photosCount: jsonData["photos_count"].toString(), totalResults: jsonData["total_results"].toString(), ); } }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Views/categories-view.dart
import 'package:felexo/Data/categories-data.dart'; import 'package:felexo/Services/categories-list.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; class CategoriesView extends StatefulWidget { @override _CategoriesViewState createState() => _CategoriesViewState(); } class _CategoriesViewState extends State<CategoriesView> { final FirebaseAuth _auth = FirebaseAuth.instance; User user; @override void initState() { initUser(); super.initState(); } initUser() async { user = _auth.currentUser; assert(user.email != null); assert(user.uid != null); assert(user.photoURL != null); setState(() {}); } @override void dispose() { super.dispose(); } @override Widget build(BuildContext context) { return StreamProvider<List<Categories>>.value( value: CategoryService().categories, initialData: [], child: CategoriesList()); } }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Views/search-delegate.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:felexo/Views/search-view.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class WallpaperSearch extends SearchDelegate<String> { // final defaultSuggestions = ["Abstract", "Architexture"]; List defaultSuggestions; List searchHistory; String uid; bool storeHistory; bool isDark; WallpaperSearch(this.defaultSuggestions, this.searchHistory, this.uid, this.storeHistory, this.isDark) : super( searchFieldLabel: "Search by keywords or color", keyboardType: TextInputType.text, textInputAction: TextInputAction.search); @override ThemeData appBarTheme(BuildContext context) { assert(context != null); final ThemeData theme = Theme.of(context); assert(theme != null); return theme.copyWith( textTheme: TextTheme( headline1: TextStyle( fontSize: 20, fontFamily: 'Theme Regular', color: Theme.of(context).colorScheme.primary), headline2: TextStyle( fontSize: 20, fontFamily: 'Theme Regular', color: Theme.of(context).colorScheme.primary), headline3: TextStyle( fontSize: 20, fontFamily: 'Theme Regular', color: Theme.of(context).colorScheme.primary), headline4: TextStyle( fontSize: 20, fontFamily: 'Theme Regular', color: Theme.of(context).colorScheme.primary), headline5: TextStyle( fontSize: 20, fontFamily: 'Theme Regular', color: Theme.of(context).colorScheme.primary), headline6: TextStyle( fontSize: 16, fontFamily: 'Theme Regular', color: Theme.of(context).colorScheme.primary)), appBarTheme: AppBarTheme( shadowColor: Theme.of(context).colorScheme.primary, centerTitle: true, titleSpacing: 0, elevation: 0, toolbarTextStyle: TextStyle( color: Theme.of(context).colorScheme.primary, fontFamily: 'Theme Regular'), titleTextStyle: TextStyle( color: Theme.of(context).colorScheme.primary, fontFamily: 'Theme Regular'), ), inputDecorationTheme: InputDecorationTheme( contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 10, bottom: 15), isDense: true, floatingLabelBehavior: FloatingLabelBehavior.never, fillColor: Theme.of(context).scaffoldBackgroundColor, filled: true, focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(0), borderSide: BorderSide( color: Theme.of(context).accentColor.withOpacity(0.5))), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(0), borderSide: BorderSide( color: Theme.of(context).accentColor.withOpacity(0.5))), hintStyle: TextStyle( fontSize: 12, color: Theme.of(context).accentColor, fontFamily: 'Theme Regular'))); } @override List<Widget> buildActions(BuildContext context) { print(searchHistory); print(defaultSuggestions); return [ Padding( padding: const EdgeInsets.fromLTRB(10, 0, 20, 0), child: Row( children: [ Container( width: 35, height: 35, decoration: BoxDecoration( border: Border.all( color: Theme.of(context).accentColor.withOpacity(0.5), width: 1), color: Theme.of(context).scaffoldBackgroundColor, shape: BoxShape.circle), child: Center( child: InkWell( onTap: () { query = ''; }, child: Icon( Icons.clear, size: 20, color: Theme.of(context).colorScheme.primary, ), ), ), ), SizedBox( width: 5, ), ], ), ) ]; // ignore: dead_code throw UnimplementedError(); } @override Widget buildLeading(BuildContext context) { return IconButton( icon: Icon( Icons.arrow_back_ios, color: Theme.of(context).colorScheme.primary, ), onPressed: () { // Navigator.of(context).pushAndRemoveUntil( // MaterialPageRoute(builder: (context) => MainView()), // (route) => false); close(context, null); }); // ignore: dead_code throw UnimplementedError(); } @override Widget buildResults(BuildContext context) { return SafeArea( child: SearchView( searchQuery: query, appBarState: false, ), ); // ignore: dead_code throw UnimplementedError(); } @override void showResults(BuildContext context) { String suggestionString; suggestionString = query[0].toUpperCase() + query.substring(1); print(suggestionString); searchHistory.toList(); if (searchHistory.isEmpty) { FirebaseFirestore.instance .collection("User") .doc(uid) .collection("SearchHistory") .doc(query.toString()) .set({"searchHistory": suggestionString}); } if (!searchHistory.contains(suggestionString)) { if (storeHistory) { FirebaseFirestore.instance .collection("SearchSuggestions") .doc(suggestionString.toString()) .set({"term": suggestionString}); if (!defaultSuggestions.contains(suggestionString)) { defaultSuggestions.insert(0, suggestionString); } } FirebaseFirestore.instance .collection("User") .doc(uid) .collection("SearchHistory") .doc(query.toString()) .set({"searchHistory": suggestionString}); if (!searchHistory.contains(suggestionString)) { searchHistory.insert(0, suggestionString); } } super.showResults(context); } @override Widget buildSuggestions(BuildContext context) { final suggestionList = query.isEmpty ? searchHistory.isEmpty ? defaultSuggestions : searchHistory : defaultSuggestions .where((p) => p.startsWith('${query[0].toUpperCase()}${query.substring(1)}')) .toList(); var icon = query.isEmpty ? searchHistory.isEmpty ? Icons.insights_outlined : Icons.history : Icons.search; return ListView.builder( itemCount: suggestionList.length, itemBuilder: (context, index) => ListTile( leading: Icon( icon, color: Theme.of(context).accentColor, ), title: InkWell( onTap: () { query = suggestionList[index].toString(); showResults(context); }, child: RichText( text: TextSpan( text: suggestionList[index].substring(0, query.length), style: TextStyle( fontFamily: 'Theme Regular', color: Theme.of(context).colorScheme.primary), children: [ TextSpan( text: suggestionList[index].substring(query.length), style: TextStyle( fontFamily: 'Theme Regular', color: Theme.of(context).accentColor)), ]), ), ), trailing: InkWell( onTap: () { query = suggestionList[index].toString(); }, child: Icon( Icons.north_west_outlined, size: 16, color: Theme.of(context).accentColor, ), ), ), ); // ignore: dead_code throw UnimplementedError(); } }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Views/main-view.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:felexo/Data/data.dart'; import 'package:felexo/Services/push-notifications.dart'; import 'package:felexo/Views/collections-view.dart'; import 'package:felexo/Views/search-delegate.dart'; import 'package:felexo/Widget/wallpaper-controls.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:md2_tab_indicator/md2_tab_indicator.dart'; import 'views.dart'; class MainView extends StatefulWidget { @override _MainViewState createState() => _MainViewState(); } class _MainViewState extends State<MainView> with SingleTickerProviderStateMixin { TabController _tabController; final suggestions = FirebaseFirestore.instance; final history = FirebaseFirestore.instance; bool storeHistory = true; bool subscription = true; bool isDark = true; PushNotificationService fcmNotification; final myTabs = [ const Tab(text: "CURATED"), const Tab(text: "COLLECTIONS"), const Tab(text: "FAVORITES"), const Tab(text: "CATEGORIES"), ]; @override void initState() { initUser(); findIfStoreHistory(); fetchSuggestions(); fcmNotification = PushNotificationService(); fcmNotification.initialize(); fetchHistory(); _tabController = new TabController(length: 4, vsync: this); super.initState(); } initUser() { user = FirebaseAuth.instance.currentUser; assert(user.email != null); assert(user.uid != null); assert(user.photoURL != null); handleAsync(); // print("User: " + user.uid.toString()); } handleAsync() async { FirebaseFirestore.instance .collection("User") .doc(user.uid) .snapshots() .forEach((element) { if (element.data()["subscribedToNotifications"] == true) { fcmNotification.subscribeToTopic('notification'); } if (element.data()["subscribedToNotifications"] == false) { fcmNotification.unSubscribeToTopic('notification'); } }); } findIfStoreHistory() { FirebaseFirestore.instance .collection("User") .doc(user.uid.toString()) .snapshots() .forEach((element) { setState(() { storeHistory = element.data()["storeHistory"]; print("Mainsh" + storeHistory.toString()); }); }); setState(() {}); } Future<List> fetchSuggestions() async { suggestions .collection("SearchSuggestions") .get() .then((QuerySnapshot snapshot) { snapshot.docs.map((e) { defaultSuggestions.add(e.get("term")); }).toList(); }); return defaultSuggestions; } Future<List> fetchHistory() async { history .collection("User") .doc(user.uid.toString()) .collection("SearchHistory") .get() .then((QuerySnapshot snapshot) { snapshot.docs.map((e) { searchHistory.add(e.get("searchHistory").toString()); }).toList(); }); return searchHistory; } @override void dispose() { _tabController.dispose(); super.dispose(); } TabBar get _tabBar => TabBar( isScrollable: true, enableFeedback: true, controller: _tabController, dragStartBehavior: DragStartBehavior.down, labelColor: Theme.of(context).colorScheme.primary, unselectedLabelColor: Theme.of(context).accentColor, labelStyle: TextStyle(fontSize: 12, fontFamily: 'Theme Bold'), indicatorSize: TabBarIndicatorSize.label, indicatorWeight: 4, indicatorColor: Theme.of(context).colorScheme.primary, indicator: MD2Indicator( indicatorHeight: 5, indicatorColor: Theme.of(context).colorScheme.primary, indicatorSize: MD2IndicatorSize.full), tabs: myTabs); @override Widget build(BuildContext context) { return Scaffold( body: DefaultTabController( length: 4, child: SafeArea( child: NestedScrollView( headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) { return <Widget>[ SliverAppBar( backgroundColor: Theme.of(context).colorScheme.secondary, expandedHeight: 200.0, floating: true, pinned: true, centerTitle: true, title: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox( height: 20, ), Text( "FELEXO", style: Theme.of(context).textTheme.headline3, ), ], ), actions: [ InkWell( onTap: () { Navigator.of(context).push(MaterialPageRoute( builder: (context) => SettingsView())); }, child: Padding( padding: const EdgeInsets.only(right: 10.0), child: CircleAvatar( radius: 18, child: CircleAvatar( radius: 18, backgroundImage: NetworkImage(user.photoURL), ), ))) ], shadowColor: Theme.of(context).colorScheme.secondary, flexibleSpace: FlexibleSpaceBar( stretchModes: [ StretchMode.fadeTitle, StretchMode.blurBackground ], centerTitle: true, background: Padding( padding: const EdgeInsets.only( top: 20.0, left: 10, right: 10, bottom: 0), child: Stack( children: [ Align( alignment: Alignment.topCenter, child: Padding( padding: const EdgeInsets.only( top: 45.0, bottom: 30), child: Text( "A LIBRARY OF AMAZING WALLPAPERS!", style: TextStyle(fontSize: 12), ), )), Padding( padding: const EdgeInsets.only(top: 10.0), child: InkWell( onTap: () async { setState(() { findIfStoreHistory(); }); showSearch( context: context, delegate: WallpaperSearch( defaultSuggestions, searchHistory, user.uid.toString(), storeHistory, isDark)); }, child: Center( child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(0), border: Border.all( color: Theme.of(context) .accentColor .withOpacity(0.5)), ), alignment: Alignment.center, width: MediaQuery.of(context).size.width - 20, height: 54, child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.start, children: [ SizedBox( width: 20, ), Icon(Icons.search), SizedBox( width: 10, ), Text( "SEARCH ACROSS THE LIBRARY OF PEXELS", style: TextStyle(fontSize: 12), ) ], ), ), ), ), ), ], ), ), ), backwardsCompatibility: true, collapsedHeight: 80, bottom: _tabBar, ), ]; }, body: TabBarView( controller: _tabController, children: [ HomeView(), CollectionsView(), FavoritesView(), CategoriesView(), ], ), ), ), ), ); } }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Views/blur-wallpaper.dart
import 'dart:io'; import 'dart:ui'; import 'package:blurrycontainer/blurrycontainer.dart'; import 'package:cached_network_image/cached_network_image.dart'; import 'package:felexo/Color/colors.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:screenshot/screenshot.dart'; import 'package:syncfusion_flutter_sliders/sliders.dart'; import 'package:wallpaper_manager/wallpaper_manager.dart'; class BlurWallpaperView extends StatefulWidget { final String url, photoID, photographer, avgColor; final int location; final foregroundColor; BlurWallpaperView( {@required this.photoID, @required this.location, @required this.photographer, @required this.url, @required this.avgColor, @required this.foregroundColor}); @override _BlurWallpaperViewState createState() => _BlurWallpaperViewState(); } class _BlurWallpaperViewState extends State<BlurWallpaperView> { double sliderValue = 0; final sliderMaxValue = 20.0; bool downloading = false; String progressString; double progressValue; ScreenshotController _screenshotController = new ScreenshotController(); @override void didChangeDependencies() { // Navigator.pop(context); super.didChangeDependencies(); } @override Widget build(BuildContext context) { return Scaffold( extendBodyBehindAppBar: true, appBar: AppBar( backgroundColor: Colors.transparent, toolbarHeight: 80, elevation: 0, leading: Padding( padding: const EdgeInsets.only(left: 10.0, top: 5), child: InkWell( onTap: () { Navigator.pop(context); }, child: Container( width: 35, height: 35, decoration: BoxDecoration( border: Border.all( width: 1, color: Theme.of(context).accentColor.withOpacity(0.5)), color: widget.foregroundColor.withOpacity(0.5), shape: BoxShape.circle, ), child: Center( child: Icon( Icons.arrow_back_ios_new_outlined, size: 20, color: widget.foregroundColor, ), ), ), ), ), ), body: SingleChildScrollView( child: Stack( alignment: Alignment.center, children: [ Container( width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height, color: Hexcolor(widget.avgColor), ), // Screenshot( // controller: _screenshotController, // child: BlurredImage.network( // context, // widget.url, // blurValue: sliderValue, // ), // ), Screenshot( controller: _screenshotController, child: Stack( alignment: Alignment.center, children: <Widget>[ CachedNetworkImage( width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height, fit: BoxFit.cover, imageUrl: widget.url, fadeInCurve: Curves.easeIn, ), Positioned.fill( child: BackdropFilter( filter: ImageFilter.blur( sigmaX: sliderValue, sigmaY: sliderValue), child: Container( width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height, ), ), ), ], ), ), Positioned( top: MediaQuery.of(context).size.height / 1.3, child: BlurryContainer( blur: 5, borderRadius: BorderRadius.zero, width: MediaQuery.of(context).size.width, height: 200, child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Text("SELECT BLUR VALUE", style: TextStyle( color: widget.foregroundColor, fontFamily: 'Theme Bold', fontSize: 14)), SfSlider( min: 0.0, max: 20.0, value: sliderValue, // showLabels: true, activeColor: widget.foregroundColor, inactiveColor: widget.foregroundColor.withOpacity(0.5), enableTooltip: true, interval: 5, showDivisors: true, onChanged: (dynamic value) { setState(() { sliderValue = value; }); }, ), Container( width: 150, height: 30, child: ElevatedButton( onPressed: () { _screenshotController .captureAndSave("storage/emulated/0/Pictures", fileName: widget.photoID.toString() + widget.photographer.toString() + ".jpg", pixelRatio: 1, delay: const Duration(milliseconds: 10)) .then((value) { setWallpaper(widget.location); }); }, style: ElevatedButton.styleFrom( elevation: 0, primary: Colors.transparent, onPrimary: widget.foregroundColor, onSurface: widget.foregroundColor, shape: RoundedRectangleBorder( side: BorderSide( color: widget.foregroundColor, width: 1), borderRadius: BorderRadius.circular(00)), ), child: Text( "SET WALLPAPER", style: TextStyle( fontFamily: 'Theme Bold', color: widget.foregroundColor), ), ), ), ], ), ), ) ], ), ), ); } Future<Null> setWallpaper(int location) async { setState(() { downloading = true; }); try { // final file = await DefaultCacheManager().getSingleFile(url); // var response = await http.get(Uri.parse(url)); // var filePath = // await ImagePickerSaver.saveFile(fileData: response.bodyBytes); try { final String result = await WallpaperManager.setWallpaperFromFile( "storage/emulated/0/Pictures/" + widget.photoID.toString() + widget.photographer.toString() + ".jpg", location, ).whenComplete(() { downloading = false; final file = File("storage/emulated/0/Pictures/" + widget.photoID.toString() + widget.photographer.toString() + ".jpg"); file.delete(); setState(() {}); HapticFeedback.heavyImpact(); Fluttertoast.showToast( msg: "Your wallpaper is set", toastLength: Toast.LENGTH_SHORT, gravity: ToastGravity.CENTER, timeInSecForIosWeb: 1, backgroundColor: Theme.of(context).colorScheme.primary, textColor: Theme.of(context).colorScheme.secondary, fontSize: 16.0); Navigator.pop(context); }); print(result); } catch (e) { print(e); } } catch (e) { print(e); } } }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Views/collectionsResultView.dart
import 'package:felexo/Widget/widgets.dart'; import 'package:flutter/material.dart'; class CRView extends StatefulWidget { final String collectionID, collectionName; CRView({@required this.collectionID, @required this.collectionName}); @override _CRViewState createState() => _CRViewState(); } class _CRViewState extends State<CRView> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( toolbarHeight: 80, leading: InkWell( onTap: () { Navigator.pop(context); }, child: Icon( Icons.arrow_back_ios, color: Theme.of(context).colorScheme.primary, ), ), title: Text( widget.collectionName.toUpperCase(), style: Theme.of(context).textTheme.headline6, ), ), body: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ CRGrid( collectionsID: widget.collectionID, ), ], ), ), ); } }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Views/views.dart
export 'categories-view.dart'; export 'categoriesResult-view.dart'; export 'favorites-view.dart'; export 'home-view.dart'; export 'search-view.dart'; export 'settings-view.dart'; export 'wallpaper-view.dart'; export 'search-delegate.dart'; export 'collections-view.dart'; export 'color-search-view.dart'; export 'blur-wallpaper.dart';
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Views/color-search-view.dart
import 'dart:convert'; import 'package:felexo/Color/colors.dart'; import 'package:felexo/Data/data.dart'; import 'package:felexo/model/wallpapers-model.dart'; import 'package:felexo/Widget/widgets.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:http/http.dart' as http; // ignore: must_be_immutable class ColorSearchView extends StatefulWidget { String color; ColorSearchView({this.color}); @override _ColorSearchViewState createState() => _ColorSearchViewState(); } class _ColorSearchViewState extends State<ColorSearchView> { TextEditingController searchController = new TextEditingController(); bool searchComplete = false; int noOfImages = 30; int pageNumber = 1; String searchQery; String nextPage; String searchMessage = "Search for some amazing wallpapers!"; final FirebaseAuth _auth = FirebaseAuth.instance; User user; Color chip = iconColor.withAlpha(60); List<WallpaperModel> wallpapers = []; bool _buttonVisible = true; @override void initState() { searchQery = widget.color; getSearchResults(widget.color); super.initState(); initUser(); } initUser() async { user = _auth.currentUser; assert(user.email != null); assert(user.uid != null); assert(user.photoURL != null); setState(() {}); } Future<List> getSearchResults(color) async { var response = await http.get( Uri.parse( "https://api.pexels.com/v1/search?query=photos&per_page=$noOfImages&color=$color"), headers: {"Authorization": apiKey}); Map<String, dynamic> jsonData = jsonDecode(response.body); // print(jsonData["next_page"].toString()); nextPage = jsonData["next_page"].toString(); jsonData["photos"].forEach((element) { // print(element); WallpaperModel wallpaperModel = new WallpaperModel(); wallpaperModel = WallpaperModel.fromMap(element); wallpapers.add(wallpaperModel); }); searchComplete = true; setState(() {}); return wallpapers; } Future<List> getMoreSearchResults(searchQuery) async { var response = await http.get(Uri.parse(nextPage), headers: {"Authorization": apiKey}); Map<String, dynamic> jsonData = jsonDecode(response.body); // print(jsonData["next_page"].toString()); nextPage = jsonData["next_page"].toString(); jsonData["photos"].forEach((element) { // print(element); WallpaperModel wallpaperModel = new WallpaperModel(); wallpaperModel = WallpaperModel.fromMap(element); wallpapers.add(wallpaperModel); }); searchComplete = true; _buttonVisible = !_buttonVisible; setState(() {}); return wallpapers; } @override void dispose() { super.dispose(); } @override Widget build(BuildContext context) { SystemChrome.setPreferredOrientations([ DeviceOrientation.portraitUp, ]); return Scaffold( appBar: AppBar( title: Text( "#" + widget.color, style: Theme.of(context).textTheme.headline6, ), leading: GestureDetector( onTap: () { Navigator.pop(context); }, child: Icon(Icons.arrow_back_ios)), ), body: SingleChildScrollView( child: wallpaperSearchGrid( wallpapers: wallpapers, context: context, uid: user.uid), ), ); } }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Views/categoriesResult-view.dart
import 'dart:convert'; import 'package:felexo/Color/colors.dart'; import 'package:felexo/Data/data.dart'; import 'package:felexo/Widget/widgets.dart'; import 'package:felexo/model/wallpapers-model.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:http/http.dart' as http; import 'package:shimmer_animation/shimmer_animation.dart'; class CategoriesResult extends StatefulWidget { final String categoryName; CategoriesResult({this.categoryName}); @override _CategoriesResultState createState() => _CategoriesResultState(); } class _CategoriesResultState extends State<CategoriesResult> { final FirebaseAuth _auth = FirebaseAuth.instance; User user; int noOfImages = 30; bool imagesLoaded = false; bool _buttonVisible = true; int pageNumber = 1; List<WallpaperModel> wallpapers = []; getCateogryWallpapers(String categoryName) async { var response = await http.get( Uri.parse( "https://api.pexels.com/v1/search/?page=2&per_page=$noOfImages&query=$categoryName"), headers: {"Authorization": apiKey}); // print(response.body.toString()); Map<String, dynamic> jsonData = jsonDecode(response.body); jsonData["photos"].forEach((element) { WallpaperModel wallpaperModel = new WallpaperModel(); wallpaperModel = WallpaperModel.fromMap(element); wallpapers.add(wallpaperModel); }); imagesLoaded = true; setState(() {}); } getMoreWallpapers(String categoryName) async { var response = await http.get( Uri.parse( "https://api.pexels.com/v1/search/?page=$pageNumber&per_page=10&query=$categoryName"), headers: {"Authorization": apiKey}); // print(response.body.toString()); Map<String, dynamic> jsonData = jsonDecode(response.body); jsonData["photos"].forEach((element) { // print(element); WallpaperModel wallpaperModel = new WallpaperModel(); wallpaperModel = WallpaperModel.fromMap(element); wallpapers.add(wallpaperModel); }); imagesLoaded = true; _buttonVisible = !_buttonVisible; setState(() {}); } @override void initState() { getCateogryWallpapers(widget.categoryName); initUser(); super.initState(); } initUser() async { user = _auth.currentUser; assert(user.email != null); assert(user.uid != null); assert(user.photoURL != null); setState(() {}); } @override Widget build(BuildContext context) { SystemChrome.setPreferredOrientations([ DeviceOrientation.portraitUp, ]); if (imagesLoaded == true) { return Scaffold( appBar: AppBar( toolbarHeight: 80, leading: InkWell( child: Icon(Icons.arrow_back_ios), onTap: () { Navigator.pop(context); }, ), title: Text( widget.categoryName.toUpperCase(), style: Theme.of(context).textTheme.headline6, ), ), body: SafeArea( child: SingleChildScrollView( child: Padding( padding: const EdgeInsets.only(top: 0.0), child: Container( child: Padding( padding: EdgeInsets.symmetric(horizontal: 00, vertical: 00), child: Column( children: [ Padding( padding: EdgeInsets.only(top: 0), ), Padding( padding: const EdgeInsets.only(top: 0.0), child: wallpaperSearchGrid( wallpapers: wallpapers, context: context, uid: user.uid), ), Align( alignment: Alignment.bottomCenter, child: Visibility( visible: !_buttonVisible, child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox( height: 10, ), Container( width: MediaQuery.of(context).size.width - 20, height: 60, child: Shimmer( child: ElevatedButton( onPressed: () { _buttonVisible = !_buttonVisible; setState(() {}); getMoreWallpapers(widget.categoryName); }, style: ElevatedButton.styleFrom( elevation: 0, primary: Theme.of(context) .scaffoldBackgroundColor, onPrimary: Theme.of(context).colorScheme.primary, onSurface: Theme.of(context).colorScheme.primary, shape: RoundedRectangleBorder( side: BorderSide( color: Theme.of(context) .accentColor .withOpacity(0.5), width: 1), borderRadius: BorderRadius.circular(00)), ), child: Text( loadingMessage, style: TextStyle( fontFamily: 'Theme Bold', color: Theme.of(context) .colorScheme .primary), ), ), ), ), SizedBox( height: 10, ), ], ), ), ), Align( alignment: Alignment.bottomCenter, child: Visibility( visible: _buttonVisible, child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox( height: 10, ), Container( width: MediaQuery.of(context).size.width - 20, height: 60, child: ElevatedButton( onPressed: () { _buttonVisible = !_buttonVisible; setState(() {}); getMoreWallpapers(widget.categoryName); }, style: ElevatedButton.styleFrom( elevation: 0, primary: Theme.of(context).scaffoldBackgroundColor, onPrimary: Theme.of(context).colorScheme.primary, onSurface: Theme.of(context).colorScheme.primary, shape: RoundedRectangleBorder( side: BorderSide( color: Theme.of(context) .accentColor .withOpacity(0.5), width: 1), borderRadius: BorderRadius.circular(00)), ), child: Text( loadMoreMessage, style: TextStyle( fontFamily: 'Theme Bold', color: Theme.of(context) .colorScheme .primary), ), ), ), SizedBox( height: 10, ), ], ), ), ) ], ), ), ), )), ), ); } if (imagesLoaded == false) { return Scaffold( appBar: AppBar( centerTitle: true, iconTheme: IconThemeData(color: Colors.black), title: Text("CATEGORIES", style: Theme.of(context).textTheme.headline6), elevation: 5, ), body: Center( child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ LinearProgressIndicator( valueColor: AlwaysStoppedAnimation(iconColor), ), SizedBox( height: 20, ), Text( "Loading...", style: TextStyle( fontFamily: 'Theme Bold', fontSize: 20, ), ), SizedBox( height: 20, ), LinearProgressIndicator( valueColor: AlwaysStoppedAnimation(iconColor), ), ], ), ), ); } return Scaffold(); } }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Views/wallpaper-view.dart
import 'dart:io'; import 'dart:typed_data'; import 'package:cached_network_image/cached_network_image.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:dio/dio.dart'; import 'package:felexo/Color/colors.dart'; import 'package:felexo/Services/ad-services.dart'; import 'package:felexo/Widget/wallpaper-controls.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:google_ml_vision/google_ml_vision.dart'; import 'package:google_mobile_ads/google_mobile_ads.dart'; import 'package:image_gallery_saver/image_gallery_saver.dart'; import 'package:permission/permission.dart'; import 'package:share/share.dart'; import 'package:shimmer_animation/shimmer_animation.dart'; import 'package:sliding_up_panel/sliding_up_panel.dart'; import 'package:intent/intent.dart' as android_intent; import 'package:intent/action.dart' as android_action; import 'views.dart'; class WallPaperView extends StatefulWidget { final String avgColor, searchString, imgUrl, photoID, photographer, photographerID, originalUrl, photographerUrl, uid; WallPaperView( {this.avgColor, this.searchString, @required this.uid, @required this.imgUrl, @required this.originalUrl, @required this.photoID, @required this.photographer, @required this.photographerID, @required this.photographerUrl}); @override _WallPaperViewState createState() => _WallPaperViewState(); } class _WallPaperViewState extends State<WallPaperView> { String home = "Home Screen"; String lock = "Lock Screen"; String both = "Both Screen"; String system = "System"; String res; bool favExists = false; bool deletingFav = false; bool fullScreen = false; bool setWall = false; bool transparent = false; User user; String wallpaperLocation; final globalKey = GlobalKey<ScaffoldState>(); var result = "Waiting to set wallpapers"; var foregroundColor; var linkTarget; double elevationValue = 0; bool _isVerified = false; bool _permissionStatus; double progressValue; String progressString = "0%"; String creatorCheck = ""; bool foundTerms = false; List<String> searchTerms = []; @override initState() { print(widget.uid); checkPermissionStatus(); transparent = false; findIfFav(); checkVerified(); super.initState(); } Future<void> _getImageAndDetectLabels() async { // print("GET IMAGE LABELS"); var response = await Dio().get(widget.imgUrl, options: Options( responseType: ResponseType.bytes, )); await ImageGallerySaver.saveImage(Uint8List.fromList(response.data), quality: 100, name: widget.photoID.toString()); File imageFile = File.fromUri( Uri.parse("storage/emulated/0/Pictures/" + widget.photoID + ".jpg")); final GoogleVisionImage visionImage = GoogleVisionImage.fromFile(imageFile); final ImageLabeler labeler = GoogleVision.instance.imageLabeler( ImageLabelerOptions(confidenceThreshold: 0.75), ); final List<ImageLabel> labels = await labeler.processImage(visionImage).whenComplete(() { labeler.close(); }); for (ImageLabel label in labels) { searchTerms.add((label.text).toUpperCase()); } if (searchTerms.isNotEmpty) { setState(() { foundTerms = true; }); final file = File( "storage/emulated/0/Pictures/" + widget.photoID.toString() + ".jpg"); file.delete(); } } checkVerified() async { print("CHECK VERIFIED"); FirebaseFirestore.instance .collection('User') .snapshots() .forEach((element) { print(element.docs.map((e) async { if (e.get('displayName') == widget.photographer) { DocumentSnapshot snapshot = await FirebaseFirestore.instance .collection('VerifiedCreators') .doc(e.get('uid')) .get(); if (snapshot.exists) { setState(() { _isVerified = true; }); } } })); }); } checkPermissionStatus() async { List<Permissions> permissions = await Permission.getPermissionsStatus([PermissionName.Storage]); print("PERMISSION STATUS"); print(permissions.map((e) { print(e.permissionStatus); if (e.permissionStatus == PermissionStatus.allow) { _permissionStatus = true; setState(() {}); } if (e.permissionStatus == PermissionStatus.deny) { _permissionStatus = false; setState(() {}); } if (e.permissionStatus == PermissionStatus.notAgain) { _permissionStatus = false; setState(() {}); } })); print(_permissionStatus); } askPermission() async { // ignore: unused_local_variable List<Permissions> permissionNames = await Permission.requestPermissions([PermissionName.Storage]); checkPermissionStatus(); } @mustCallSuper didChangeDependencies() async { if (widget.avgColor.length < 6) { foregroundColor = Theme.of(context).colorScheme.secondary; elevationValue = 1; } else { foregroundColor = Hexcolor(widget.avgColor).computeLuminance() > 0.5 ? Colors.black : Colors.white; elevationValue = 0; } super.didChangeDependencies(); } initUser() async { user = FirebaseAuth.instance.currentUser; assert(user.email != null); assert(user.uid != null); assert(user.photoURL != null); // print("User: " + user.uid.toString()); setState(() {}); } findIfFav() async { _getImageAndDetectLabels(); // print("finding fav"); final snapShot = await FirebaseFirestore.instance .collection("User") .doc(widget.uid) .collection("Favorites") .doc(widget.photoID.toString()) .get(); if (snapShot.exists) { favExists = true; // print("Fav Exists"); setState(() {}); } else { // print("Fav Not Exists"); favExists = false; } setState(() {}); } @override Widget build(BuildContext context) { return Scaffold( extendBodyBehindAppBar: true, appBar: AppBar( backgroundColor: Colors.transparent, toolbarHeight: 80, elevation: 0, leading: Padding( padding: const EdgeInsets.only(left: 10.0, top: 5), child: InkWell( onTap: () { Navigator.pop(context); }, child: Container( width: 35, height: 35, decoration: BoxDecoration( border: Border.all( width: 1, color: Theme.of(context).accentColor.withOpacity(0.5)), color: Theme.of(context).scaffoldBackgroundColor, shape: BoxShape.circle, ), child: Center( child: Icon( Icons.arrow_back_ios_new_outlined, size: 20, color: Theme.of(context).colorScheme.primary, ), ), ), ), ), ), body: SlidingUpPanel( border: Border.all( color: Theme.of(context).accentColor.withOpacity(0.5), width: 1), borderRadius: BorderRadius.circular(0), backdropEnabled: true, backdropColor: Hexcolor(widget.avgColor), backdropOpacity: 0.5, backdropTapClosesPanel: true, color: Theme.of(context).scaffoldBackgroundColor, maxHeight: MediaQuery.of(context).size.height - 100, minHeight: MediaQuery.of(context).size.height / 8, body: Stack(children: [ Center( child: Container( width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height, color: Hexcolor(widget.avgColor), ), ), Shimmer( child: Container( width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height, )), Center( child: Container( width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height, child: CachedNetworkImage( imageUrl: widget.imgUrl, fit: BoxFit.cover, fadeInCurve: Curves.easeIn), ), ), ]), panel: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Icon( Icons.minimize_outlined, size: 40, color: Theme.of(context).colorScheme.primary, ) ], ), SizedBox( height: 5, ), Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Text( "SWIPE FOR MORE", style: Theme.of(context).textTheme.button, ) ], ), SizedBox( height: 20, ), Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ WallpaperControls( uid: widget.uid, imgUrl: widget.imgUrl, originalUrl: widget.originalUrl, photoID: widget.photoID, photographer: widget.photographer, photographerID: widget.photographerID, photographerUrl: widget.photographerUrl, avgColor: widget.avgColor, favExists: favExists, foregroundColor: foregroundColor) ], ), SizedBox( height: 20, ), Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ infoCard(context), ], ), SizedBox( height: 20, ), Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Text( "RELATED SEARCH TERMS", style: Theme.of(context).textTheme.headline6, ) ], ), foundTerms ? Container( width: MediaQuery.of(context).size.width - 20, height: 100, child: Padding( padding: const EdgeInsets.only(left: 10.0), child: SingleChildScrollView( scrollDirection: Axis.horizontal, child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.start, children: [ ListView.builder( shrinkWrap: true, scrollDirection: Axis.horizontal, itemCount: searchTerms.length, itemBuilder: (context, index) { return Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ InkWell( onTap: () { Navigator.push( context, CupertinoPageRoute( builder: (context) => SearchView( searchQuery: searchTerms[ index], appBarState: true, ))); }, child: Container( height: 50, decoration: BoxDecoration( color: Theme.of(context) .cardColor, border: Border.all( color: Theme.of(context) .accentColor, width: 1)), child: Padding( padding: const EdgeInsets.all(8.0), child: Center( child: Text( searchTerms[index], style: TextStyle( fontFamily: 'Theme Bold', fontSize: 16, color: Theme.of(context) .colorScheme .primary)), ), )), ), SizedBox( width: 10, ) ], ); }) ], ), ), ), ) : Shimmer( color: Theme.of(context).colorScheme.primary, direction: ShimmerDirection.fromLTRB(), child: Container( width: MediaQuery.of(context).size.width - 20, height: 80, child: Center(child: Text("LOADING SUGGESTIONS")), ), ), SizedBox( height: 20, ), Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ adBox(context), ], ), ], )), ); } Row adBox(BuildContext context) { return Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Container( width: MediaQuery.of(context).size.width, height: 80, child: AdWidget( ad: AdServices.createBannerAd()..load(), key: UniqueKey(), ), ) ], ); } Row infoCard(BuildContext context) { return Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Container( width: MediaQuery.of(context).size.width - 30, decoration: BoxDecoration( borderRadius: BorderRadius.circular(0), border: Border.all( color: Theme.of(context).accentColor.withOpacity(0.5), width: 1), color: Theme.of(context).cardColor, // color: Colors.transparent, ), child: Padding( padding: const EdgeInsets.all(8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ SizedBox( height: 20, ), Row( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Column( children: [ GestureDetector( onTap: () { var color = widget.avgColor .substring(1, widget.avgColor.length); print(color); Navigator.of(context).push(CupertinoPageRoute( builder: (context) => ColorSearchView( color: color, ))); }, child: Row( children: [ Material( type: MaterialType.circle, color: Hexcolor(widget.avgColor), elevation: elevationValue, shadowColor: Theme.of(context).colorScheme.secondary, child: Container( width: 35, height: 35, decoration: BoxDecoration( shape: BoxShape.circle, color: Hexcolor(widget.avgColor), ), child: Icon( Icons.palette_outlined, size: 20, color: foregroundColor, ), ), ), SizedBox( width: 10, ), Text( widget.avgColor, style: TextStyle( fontSize: 16, fontFamily: 'Theme Bold', color: Theme.of(context).colorScheme.primary), ), ], ), ), ], ), Column( children: [ Row( children: [ Container( width: 35, height: 35, decoration: BoxDecoration( shape: BoxShape.circle, color: Theme.of(context).colorScheme.primary), child: Icon( Icons.tag, size: 20, color: Theme.of(context).colorScheme.secondary, ), ), SizedBox( width: 10, ), Text( widget.photoID, style: TextStyle( fontSize: 16, fontFamily: 'Theme Bold', color: Theme.of(context).colorScheme.primary), ), ], ), ], ), ], ), SizedBox( height: 20, ), Row( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ GestureDetector( onLongPress: () { HapticFeedback.heavyImpact(); ScaffoldMessenger.of(context).showSnackBar(SnackBar( backgroundColor: Theme.of(context).colorScheme.primary, content: Row( children: [ Text( widget.photographer.toUpperCase(), style: TextStyle( color: Theme.of(context).cardColor, fontFamily: 'Theme Bold'), ), _isVerified ? Icon(Icons.verified, size: 16, color: Theme.of(context).cardColor) : SizedBox(), ], ))); }, child: Column( children: [ Row( children: [ Container( width: 35, height: 35, decoration: BoxDecoration( shape: BoxShape.circle, color: Theme.of(context) .colorScheme .primary), child: Icon( Icons.badge_outlined, size: 20, color: Theme.of(context).colorScheme.secondary, ), ), SizedBox( width: 10, ), Container( width: 150, child: Row( children: [ Flexible( child: Text( widget.photographer.toUpperCase(), overflow: TextOverflow.ellipsis, style: TextStyle( fontSize: 16, fontFamily: 'Theme Bold', color: Theme.of(context) .colorScheme .primary), ), ), SizedBox(width: 5), _isVerified ? Icon(Icons.verified, size: 16, color: Theme.of(context) .colorScheme .primary) : SizedBox(), ], ), ), ], ), ], ), ), InkWell( onTap: () { showDialog( context: context, builder: (context) => AlertDialog( shape: RoundedRectangleBorder( side: BorderSide( width: 1, color: Theme.of(context) .accentColor .withOpacity(0.5)), borderRadius: BorderRadius.circular(0)), elevation: 0, title: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Text( "SHARE AS", style: Theme.of(context).textTheme.bodyText1, ) ], ), content: SizedBox( height: 100, width: 80, child: Center( child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ InkWell( onTap: () { _imageShare(widget.imgUrl, _permissionStatus); }, child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Icon( Icons.image_outlined, size: 24, color: Theme.of(context) .colorScheme .primary, ), SizedBox( height: 10, ), Text( "IMAGE", textAlign: TextAlign.center, style: Theme.of(context) .textTheme .button, ) ], ), ), InkWell( onTap: () { Share.share("Checkout this Photo By: " + widget.photographer + "\n\nPhotographer: " + widget.photographerUrl + "\n\nFind Image at: " + widget.originalUrl + "\n\nDownload FELEXO for more amazing wallpapers\nbit.ly/33XLfoX"); }, child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Icon( Icons.link_outlined, size: 24, color: Theme.of(context) .colorScheme .primary, ), SizedBox( height: 10, ), Text( "LINK", textAlign: TextAlign.center, style: Theme.of(context) .textTheme .button, ) ], ), ), ]), ), ), ), ); }, child: Column( children: [ Row( children: [ Container( width: 35, height: 35, decoration: BoxDecoration( shape: BoxShape.circle, color: Theme.of(context) .colorScheme .primary), child: Icon( Icons.share_outlined, size: 20, color: Theme.of(context).colorScheme.secondary, ), ), SizedBox( width: 10, ), Text( "SHARE", style: TextStyle( fontSize: 16, fontFamily: 'Theme Bold', color: Theme.of(context) .colorScheme .primary), ), ], ), ], ), ), ]), SizedBox( height: 40, ), GestureDetector( onTap: () { android_intent.Intent() ..setAction(android_action.Action.ACTION_VIEW) ..setData(Uri(scheme: "https", host: "pexels.com")) ..startActivity().catchError((e) => print(e)); }, child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Container( width: 35, height: 35, decoration: BoxDecoration( shape: BoxShape.circle, color: Theme.of(context).colorScheme.primary, ), child: Icon( Icons.public_outlined, size: 20, color: Theme.of(context).colorScheme.secondary, ), ), SizedBox( width: 10, ), Text( "VISIT PEXELS", style: TextStyle( fontSize: 16, fontFamily: 'Theme Bold', color: Theme.of(context).colorScheme.primary), ) ], ), ), SizedBox( height: 5, ), ], ), ), ), SizedBox( height: 20, ), ], ); } _imageShare(String url, bool _permissionReceived) async { setState(() {}); if (_permissionStatus) { var response = await Dio() .get(url, options: Options(responseType: ResponseType.bytes), onReceiveProgress: (received, total) { if (total != -1) { progressValue = received / total; progressString = (received / total * 100).toStringAsFixed(0) + "%"; setState(() {}); print((received / total * 100).toStringAsFixed(0) + "%"); } }); final result = await ImageGallerySaver.saveImage( Uint8List.fromList(response.data), quality: 100, name: widget.photographer + widget.photoID.toString()); print(result); Share.shareFiles([ "storage/emulated/0/Pictures/FELEXO/" + widget.photographer + widget.photoID.toString() + ".jpg" ], text: "Checkout this Photo By: " + widget.photographer + "\n\nPhotographer: " + widget.photographerUrl + "\n\nFind Image at: " + widget.originalUrl + "\n\nDownload FELEXO for more amazing wallpapers\nbit.ly/33XLfoX"); setState(() {}); } if (!_permissionStatus) { showDialog( context: context, builder: (context) => AlertDialog( backgroundColor: Theme.of(context).colorScheme.secondary, title: Text("OOPS!", style: Theme.of(context).textTheme.subtitle1), content: Text("FILE PERMISSIONS ARE DENIED", style: Theme.of(context).textTheme.button), actions: [ TextButton( onPressed: () { askPermission(); Navigator.pop(context); }, child: Text("ASK PERMISSION", style: Theme.of(context).textTheme.button)), TextButton( child: Text("OK", style: Theme.of(context).textTheme.button), onPressed: () async { Navigator.of(context).pop(); }, ) ], )); } } }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Views/search-view.dart
import 'dart:convert'; import 'package:felexo/Color/colors.dart'; import 'package:felexo/Data/data.dart'; import 'package:felexo/Widget/widgets.dart'; import 'package:felexo/model/wallpapers-model.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:http/http.dart' as http; import 'package:shimmer_animation/shimmer_animation.dart'; class SearchView extends StatefulWidget { final String searchQuery; final bool appBarState; SearchView({@required this.searchQuery, @required this.appBarState}); @override _SearchViewState createState() => _SearchViewState(); } class _SearchViewState extends State<SearchView> { TextEditingController searchController = new TextEditingController(); bool searchComplete = false; int noOfImages = 30; int pageNumber = 1; String searchQery; String nextPage; String searchMessage = "Search for some amazing wallpapers!"; final FirebaseAuth _auth = FirebaseAuth.instance; User user; Color chip = iconColor.withAlpha(60); List<WallpaperModel> wallpapers = []; bool _buttonVisible = true; bool _isLoading = true; bool _hasResults = true; bool loading = false; bool _appBar; @override void initState() { searchQery = widget.searchQuery; getSearchResults(widget.searchQuery); super.initState(); _appBar = widget.appBarState; initUser(); } initUser() async { user = _auth.currentUser; assert(user.email != null); assert(user.uid != null); assert(user.photoURL != null); setState(() {}); } Future<List> getSearchResults(searchQuery) async { var response = await http.get( Uri.parse( "https://api.pexels.com/v1/search?query=$searchQuery&per_page=$noOfImages"), headers: {"Authorization": apiKey}); print("STATUS CODE: " + response.statusCode.toString()); print("CONTENT LENGHT: " + response.contentLength.toString()); Map<String, dynamic> jsonData = jsonDecode(response.body); // print(jsonData["next_page"].toString()); print("CONTENT LENGHT: " + jsonData['photos'].toString()); if (jsonData['photos'].toList().isEmpty) { setState(() { _hasResults = false; }); print("NO RESULTS"); } else { setState(() { _hasResults = true; }); print("RESULTS FOUND!"); } nextPage = jsonData["next_page"].toString(); if (nextPage == null) { setState(() { loading = false; }); } if (nextPage != null) { setState(() { loading = true; }); } jsonData["photos"].forEach((element) { // print(element); WallpaperModel wallpaperModel = new WallpaperModel(); wallpaperModel = WallpaperModel.fromMap(element); wallpapers.add(wallpaperModel); }); searchComplete = true; _isLoading = false; setState(() {}); return wallpapers; } Future<List> getMoreSearchResults(searchQuery) async { var response = await http.get(Uri.parse(nextPage), headers: {"Authorization": apiKey}); Map<String, dynamic> jsonData = jsonDecode(response.body); // print(jsonData["next_page"].toString()); nextPage = jsonData["next_page"].toString(); jsonData["photos"].forEach((element) { // print(element); WallpaperModel wallpaperModel = new WallpaperModel(); wallpaperModel = WallpaperModel.fromMap(element); wallpapers.add(wallpaperModel); }); searchComplete = true; _buttonVisible = !_buttonVisible; setState(() {}); return wallpapers; } @override void dispose() { super.dispose(); } @override Widget build(BuildContext context) { SystemChrome.setPreferredOrientations([ DeviceOrientation.portraitUp, ]); return _appBar ? scaffoldWithAppBar(context) : scaffoldWithoutAppBar(context); } Scaffold scaffoldWithoutAppBar(BuildContext context) { return Scaffold( body: _isLoading ? Shimmer( child: Container( width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height, ), ) : _hasResults ? SafeArea( child: SingleChildScrollView( child: Column( children: [ Align( alignment: Alignment.topCenter, child: wallpaperSearchGrid( wallpapers: wallpapers, context: context, uid: user.uid), ), loading ? Align( alignment: Alignment.bottomCenter, child: Visibility( visible: !_buttonVisible, child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox( height: 10, ), Container( width: MediaQuery.of(context).size.width - 20, height: 60, child: Shimmer( child: ElevatedButton( onPressed: () { _buttonVisible = !_buttonVisible; setState(() {}); getMoreSearchResults( widget.searchQuery); }, style: ElevatedButton.styleFrom( elevation: 0, primary: Theme.of(context) .scaffoldBackgroundColor, onPrimary: Theme.of(context) .colorScheme .primary, onSurface: Theme.of(context) .colorScheme .primary, shape: RoundedRectangleBorder( side: BorderSide( color: Theme.of(context) .accentColor .withOpacity(0.5), width: 1), borderRadius: BorderRadius.circular( 00)), ), child: Text( loadingMessage, style: TextStyle( fontFamily: 'Theme Bold', color: Theme.of(context) .colorScheme .primary), ), ), ), ), SizedBox( height: 10, ), ], ), ), ) : Container(), loading ? Align( alignment: Alignment.bottomCenter, child: Visibility( visible: _buttonVisible, child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox( height: 10, ), Container( width: MediaQuery.of(context).size.width - 20, height: 60, child: ElevatedButton( onPressed: () { _buttonVisible = !_buttonVisible; setState(() {}); getMoreSearchResults( widget.searchQuery); }, style: ElevatedButton.styleFrom( elevation: 0, primary: Theme.of(context) .scaffoldBackgroundColor, onPrimary: Theme.of(context) .colorScheme .primary, onSurface: Theme.of(context) .colorScheme .primary, shape: RoundedRectangleBorder( side: BorderSide( color: Theme.of(context) .accentColor .withOpacity(0.5), width: 1), borderRadius: BorderRadius.circular(00)), ), child: Text( loadMoreMessage, style: TextStyle( fontFamily: 'Theme Bold', color: Theme.of(context) .colorScheme .primary), ), ), ), SizedBox( height: 10, ), ], ), ), ) : Container(), ], ), ), ) : Center( child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Icon( Icons.warning_amber_rounded, size: 30, ), SizedBox( height: 20, ), Text( "WE COULDN'T FIND ANY RESULTS FOR YOUR SEARCH!", style: TextStyle( color: Theme.of(context).colorScheme.primary, fontSize: 12, fontFamily: 'Theme Black'), textAlign: TextAlign.center, ) ], ), ), ); } Scaffold scaffoldWithAppBar(BuildContext context) { return Scaffold( appBar: AppBar( toolbarHeight: 80, leading: InkWell( child: Icon(Icons.arrow_back_ios), onTap: () { Navigator.pop(context); }, ), title: Text( widget.searchQuery.toUpperCase(), style: Theme.of(context).textTheme.headline6, ), ), body: _isLoading ? Shimmer( child: Container( width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height, ), ) : _hasResults ? SafeArea( child: SingleChildScrollView( child: Column( children: [ Align( alignment: Alignment.topCenter, child: wallpaperSearchGrid( wallpapers: wallpapers, context: context, uid: user.uid), ), loading ? Align( alignment: Alignment.bottomCenter, child: Visibility( visible: !_buttonVisible, child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox( height: 10, ), Container( width: MediaQuery.of(context).size.width - 20, height: 60, child: Shimmer( child: ElevatedButton( onPressed: () { _buttonVisible = !_buttonVisible; setState(() {}); getMoreSearchResults( widget.searchQuery); }, style: ElevatedButton.styleFrom( elevation: 0, primary: Theme.of(context) .scaffoldBackgroundColor, onPrimary: Theme.of(context) .colorScheme .primary, onSurface: Theme.of(context) .colorScheme .primary, shape: RoundedRectangleBorder( side: BorderSide( color: Theme.of(context) .accentColor .withOpacity(0.5), width: 1), borderRadius: BorderRadius.circular( 00)), ), child: Text( loadingMessage, style: TextStyle( fontFamily: 'Theme Bold', color: Theme.of(context) .colorScheme .primary), ), ), ), ), SizedBox( height: 10, ), ], ), ), ) : Container(), loading ? Align( alignment: Alignment.bottomCenter, child: Visibility( visible: _buttonVisible, child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox( height: 10, ), Container( width: MediaQuery.of(context).size.width - 20, height: 60, child: ElevatedButton( onPressed: () { _buttonVisible = !_buttonVisible; setState(() {}); getMoreSearchResults( widget.searchQuery); }, style: ElevatedButton.styleFrom( elevation: 0, primary: Theme.of(context) .scaffoldBackgroundColor, onPrimary: Theme.of(context) .colorScheme .primary, onSurface: Theme.of(context) .colorScheme .primary, shape: RoundedRectangleBorder( side: BorderSide( color: Theme.of(context) .accentColor .withOpacity(0.5), width: 1), borderRadius: BorderRadius.circular(00)), ), child: Text( loadMoreMessage, style: TextStyle( fontFamily: 'Theme Bold', color: Theme.of(context) .colorScheme .primary), ), ), ), SizedBox( height: 10, ), ], ), ), ) : Container(), ], ), ), ) : Center( child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Icon( Icons.warning_amber_rounded, size: 30, ), SizedBox( height: 20, ), Text( "WE COULDN'T FIND ANY RESULTS FOR YOUR SEARCH!", style: TextStyle( color: Theme.of(context).colorScheme.primary, fontSize: 12, fontFamily: 'Theme Black'), textAlign: TextAlign.center, ) ], ), ), ); } }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Views/settings-view.dart
import 'dart:io'; import 'package:cached_network_image/cached_network_image.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:expandable_bottom_sheet/expandable_bottom_sheet.dart'; import 'package:felexo/Data/data.dart'; import 'package:felexo/Services/authentication-service.dart'; import 'package:felexo/Services/push-notifications.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_storage/firebase_storage.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:package_info/package_info.dart'; import 'package:path_provider/path_provider.dart'; import 'package:random_string/random_string.dart'; import 'package:filesize/filesize.dart'; class SettingsView extends StatefulWidget { @override _SettingsViewState createState() => _SettingsViewState(); } class _SettingsViewState extends State<SettingsView> { final FirebaseAuth _auth = FirebaseAuth.instance; final fsref = FirebaseStorage.instance.ref(); User user; String feedbackToken; final globalKey = GlobalKey<ScaffoldState>(); bool isDark = true; String appName; String packageName; String version; String buildNumber; bool _storeHistory = true; bool historyAvail = false; TextEditingController subject = new TextEditingController(); TextEditingController feedback = new TextEditingController(); var logoPlayStore; bool _isVerified = false; String cacheMemorySize = "0"; String appMemorySize = "0"; bool appMemoryFound = false; bool cacheFound = false; Directory tempDir; Directory appDir; bool _subscribedNotification = true; PushNotificationService fcmNotification; PackageInfo _packageInfo = PackageInfo( appName: 'Unknown', packageName: 'Unknown', version: 'Unknown', buildNumber: 'Unknown', ); @override void initState() { _initPackageInfo(); setState(() {}); fcmNotification = PushNotificationService(); fcmNotification.initialize(); // print(searchHistory.length); if (searchHistory.length == null) { setState(() { historyAvail = false; }); } if (searchHistory.length == 0) { setState(() { historyAvail = false; }); } if (searchHistory.length > 0) { setState(() { historyAvail = true; }); } else { setState(() { historyAvail = false; }); } getCacheMemory(); getAppMemory(); getLogo(); initUser(); findIfStoreHistory(); findSubscrptionStatus(); super.initState(); } getCacheMemory() async { Directory _tempDir = await getTemporaryDirectory(); cacheDirStatSync(_tempDir.path); } getAppMemory() async { Directory _appDir = Directory("storage/emulated/0/Pictures/FELEXO"); print("APP DIRECTORY" + _appDir.path); appDirStatSync(_appDir.path); } getLogo() async { await fsref .child('ic_launcher-playstore.png') .getDownloadURL() .then((value) { setState(() { logoPlayStore = value; }); }); } initUser() async { user = _auth.currentUser; assert(user.email != null); assert(user.uid != null); assert(user.photoURL != null); setState(() { checkVerified(); }); } checkVerified() async { print("CHECK VERIFIED"); FirebaseFirestore.instance .collection('User') .snapshots() .forEach((element) { print(element.docs.map((e) async { if (e.get('displayName') == user.displayName) { DocumentSnapshot snapshot = await FirebaseFirestore.instance .collection('VerifiedCreators') .doc(e.get('uid')) .get(); if (snapshot.exists) { setState(() { _isVerified = true; }); } } })); }); } Future<void> _initPackageInfo() async { final PackageInfo info = await PackageInfo.fromPlatform(); setState(() { _packageInfo = info; }); } findIfStoreHistory() { FirebaseFirestore.instance .collection("User") .doc(user.uid.toString()) .snapshots() .forEach((element) { setState(() { _storeHistory = element.data()["storeHistory"]; print("Settingsh" + _storeHistory.toString()); }); }); setState(() {}); } findSubscrptionStatus() { FirebaseFirestore.instance .collection("User") .doc(user.uid) .snapshots() .forEach((element) { setState(() { _subscribedNotification = element.data()["subscribedToNotifications"]; }); print("SUBSCRIPTION STATUS: " + _subscribedNotification.toString()); }); if (_subscribedNotification == null) { setState(() { _subscribedNotification = true; }); } } void historyPref(bool value) { setState(() { _storeHistory = !_storeHistory; }); FirebaseFirestore.instance .collection("User") .doc(user.uid.toString()) .update({'storeHistory': _storeHistory}); } Future<void> _deleteCacheDir() async { Directory _tempDir = await getTemporaryDirectory(); setState(() { tempDir = _tempDir; }); cacheDirStatSync(_tempDir.path); if (_tempDir.existsSync()) { _tempDir.deleteSync(recursive: true); } } Future<void> _deleteAppDir() async { final _appDir = Directory("storage/emulated/0/Pictures/FELEXO"); setState(() { appDir = _appDir; }); print("APP DIRECTORY" + appDir.path); appDirStatSync(_appDir.path); if (_appDir.existsSync()) { _appDir.deleteSync(recursive: true); } } Map<String, int> cacheDirStatSync(String dirPath) { int fileNum = 0; int totalSize = 0; var dir = Directory(dirPath); try { if (dir.existsSync()) { dir .listSync(recursive: true, followLinks: false) .forEach((FileSystemEntity entity) { if (entity is File) { fileNum++; totalSize += entity.lengthSync(); } }); } } catch (e) { print(e.toString()); } // print("SIZE " + filesize(totalSize).toString()); setState(() { cacheMemorySize = filesize(totalSize); if (totalSize > 0) { cacheFound = true; } if (totalSize <= 0) { cacheFound = false; } }); return {'fileNum': fileNum, 'size': totalSize}; } Map<String, int> appDirStatSync(String dirPath) { int fileNum = 0; int totalSize = 0; var dir = Directory(dirPath); try { if (dir.existsSync()) { dir .listSync(recursive: true, followLinks: false) .forEach((FileSystemEntity entity) { if (entity is File) { fileNum++; totalSize += entity.lengthSync(); } }); } } catch (e) { print(e.toString()); } // print("SIZE " + filesize(totalSize).toString()); setState(() { appMemorySize = filesize(totalSize); if (totalSize > 0) { appMemoryFound = true; } if (totalSize <= 0) { appMemoryFound = false; } }); return {'fileNum': fileNum, 'size': totalSize}; } @override void didChangeDependencies() { if (MediaQuery.of(context).platformBrightness == Brightness.dark) { isDark = true; setState(() {}); } if (MediaQuery.of(context).platformBrightness == Brightness.light) { isDark = false; setState(() {}); } super.didChangeDependencies(); } @override void dispose() { super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( key: globalKey, resizeToAvoidBottomInset: false, appBar: AppBar( elevation: 0, centerTitle: true, toolbarHeight: 80, leading: IconButton( onPressed: () { Navigator.pop(context); }, icon: Icon( Icons.arrow_back_ios, color: Theme.of(context).colorScheme.primary, )), title: Text("PROFILE", style: Theme.of(context).textTheme.headline6), ), body: SafeArea( child: SingleChildScrollView( child: Align( alignment: Alignment.bottomCenter, child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [ Padding( padding: const EdgeInsets.fromLTRB(20, 20, 10, 4), child: Container( decoration: BoxDecoration( shape: BoxShape.circle, border: Border.all( color: Theme.of(context).accentColor, width: 2)), child: Padding( padding: const EdgeInsets.all(8.0), child: CircleAvatar( radius: 45, backgroundImage: NetworkImage(user.photoURL), ), ), ), ), SizedBox( height: 10, ), Padding( padding: const EdgeInsets.fromLTRB(20, 5, 10, 0), child: Row( crossAxisAlignment: CrossAxisAlignment.center, children: [ InkWell( onLongPress: () { ScaffoldMessenger.of(context).showSnackBar( SnackBar( backgroundColor: Theme.of(context).colorScheme.primary, duration: const Duration(seconds: 1), content: Row( children: [ Icon( Icons.account_circle_outlined, color: Theme.of(context).colorScheme.secondary, ), SizedBox( width: 10, ), Text( user.displayName.toUpperCase(), style: TextStyle( color: Theme.of(context) .scaffoldBackgroundColor, fontFamily: 'Theme Bold'), ), SizedBox( width: 5, ), _isVerified ? Icon( Icons.verified, size: 16, color: Theme.of(context) .colorScheme .primary, ) : SizedBox(), ], ), ), ); }, child: SizedBox( width: 300, child: Row( children: [ Flexible( child: Text( user.displayName.toUpperCase(), overflow: TextOverflow.ellipsis, style: Theme.of(context).textTheme.headline5, ), ), SizedBox( width: 5, ), _isVerified ? Icon( Icons.verified, color: Theme.of(context).colorScheme.primary, ) : SizedBox(), ], ), ), ), ], ), ), SizedBox( height: 10, ), Padding( padding: const EdgeInsets.fromLTRB(20, 5, 10, 0), child: Text( user.email, style: Theme.of(context).textTheme.subtitle1, ), ), SizedBox( height: 30, ), Padding( padding: const EdgeInsets.only(left: 20), child: Text("SEARCH"), ), ListTile( minVerticalPadding: 10, horizontalTitleGap: 20, title: Text( "CLEAR SEARCH HISTORY", style: Theme.of(context).textTheme.button, ), subtitle: historyAvail ? Text("CLEAR ALL YOUR SEARCH HISTORY", style: TextStyle(fontSize: 10)) : Text("YOU HAVE NO SEARCH HISTORY", style: TextStyle(fontSize: 10)), leading: Icon( historyAvail ? Icons.search : Icons.search_off_outlined, color: historyAvail ? isDark ? Colors.greenAccent : Colors.green : Colors.redAccent, ), onTap: () async { if (searchHistory.length > 0) { searchHistory.clear(); historyAvail = false; setState(() {}); FirebaseFirestore.instance .collection("User") .doc(user.uid) .collection("SearchHistory") .get() .then((value) { for (DocumentSnapshot ds in value.docs) { ds.reference.delete(); } }).whenComplete( () => ScaffoldMessenger.of(context).showSnackBar( SnackBar( backgroundColor: Theme.of(context).colorScheme.primary, duration: const Duration(seconds: 1), content: Row( children: [ Icon( Icons.check, color: Theme.of(context) .colorScheme .secondary, ), SizedBox( width: 10, ), Text( "SEARCH HISTORY DELETED!", style: TextStyle( color: Theme.of(context) .scaffoldBackgroundColor, fontFamily: 'Theme Bold'), ), ], ), ), )); } HapticFeedback.mediumImpact(); // print("Clicked"); }, ), ListTile( minVerticalPadding: 10, horizontalTitleGap: 20, leading: Icon( _storeHistory ? Icons.history : Icons.history_toggle_off, color: _storeHistory ? isDark ? Colors.greenAccent : Colors.green : Colors.redAccent, ), title: Text("SHARE MY SEARCH HISTORY", style: Theme.of(context).textTheme.button), subtitle: Text( "THIS WILL HELP US IMPROVE YOUR SEARCH RECOMMENDATIONS", style: TextStyle(fontSize: 10), ), trailing: Switch.adaptive( activeColor: isDark ? Colors.greenAccent : Colors.green, inactiveThumbColor: Colors.redAccent, activeTrackColor: isDark ? Colors.greenAccent.withOpacity(0.5) : Colors.green.withOpacity(0.5), inactiveTrackColor: Colors.redAccent.withOpacity(0.5), value: _storeHistory, onChanged: historyPref), onTap: () { HapticFeedback.mediumImpact(); }, ), SizedBox( height: 20, ), Padding( padding: const EdgeInsets.only(left: 20), child: Text("DEVICE"), ), ListTile( minVerticalPadding: 10, horizontalTitleGap: 20, title: Text( "CLEAR CACHE", style: Theme.of(context).textTheme.button, ), subtitle: Text( "CLEAR APP CACHE", style: TextStyle(fontSize: 10), ), leading: Icon( cacheFound ? Icons.delete : Icons.delete_outlined, color: cacheFound ? Colors.redAccent : Theme.of(context).colorScheme.primary, ), trailing: Text( cacheMemorySize, style: TextStyle( fontFamily: 'Theme Regular', fontSize: 10, color: cacheFound ? Colors.redAccent : Theme.of(context).colorScheme.primary), ), onTap: () async { HapticFeedback.mediumImpact(); if (cacheFound) { _deleteCacheDir().whenComplete(() { cacheDirStatSync(tempDir.path); ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Row( children: [ Icon( Icons.check, color: Theme.of(context).colorScheme.secondary, ), SizedBox( width: 10, ), Text( "CACHE DELETED!", ), ], ), backgroundColor: Theme.of(context).colorScheme.primary, )); }); } if (!cacheFound) { ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Row( children: [ Icon( Icons.error_outline_outlined, color: Theme.of(context).colorScheme.secondary, ), SizedBox( width: 10, ), Text( "NO CACHE TO DELETE!", ), ], ), backgroundColor: Theme.of(context).colorScheme.primary, )); } }, ), ListTile( minVerticalPadding: 10, horizontalTitleGap: 20, title: Text( "DELETE SAVED WALLPAPERS", style: Theme.of(context).textTheme.button, ), subtitle: Text( "ALL SAVED WALLPAPERS WILL BE DELETED", style: TextStyle(fontSize: 10), ), leading: Icon( appMemoryFound ? Icons.delete_forever : Icons.delete_forever_outlined, color: appMemoryFound ? Colors.redAccent : Theme.of(context).colorScheme.primary, ), trailing: Text( appMemorySize, style: TextStyle( fontFamily: 'Theme Regular', fontSize: 10, color: appMemoryFound ? Colors.redAccent : Theme.of(context).colorScheme.primary), ), onTap: () async { HapticFeedback.mediumImpact(); if (appMemoryFound) { showDialog( context: context, builder: (context) => AlertDialog( shape: RoundedRectangleBorder( side: BorderSide( width: 1, color: Theme.of(context) .accentColor .withOpacity(0.5)), borderRadius: BorderRadius.circular(0)), title: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.start, children: [ Text( "DELETE WALLPAPERS", style: Theme.of(context).textTheme.bodyText1, ) ], ), content: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Text( "THIS WILL PERMENANTLY DELETE \nTHE DOWNLOADED FILES!", style: Theme.of(context).textTheme.bodyText1, ) ], ), actions: [ TextButton( onPressed: () { Navigator.pop(context); }, child: Text("DON'T DELETE")), TextButton( onPressed: () { Navigator.pop(context); _deleteAppDir().whenComplete(() { appDirStatSync(appDir.path); ScaffoldMessenger.of(context) .showSnackBar(SnackBar( content: Row( children: [ Icon( Icons.check, color: Theme.of(context) .colorScheme .secondary, ), SizedBox( width: 10, ), Text( "SAVED WALLPAPERS ARE DELETED!", ), ], ), backgroundColor: Theme.of(context) .colorScheme .primary, )); }); }, child: Text("DELETE")), ], )); } if (!appMemoryFound) { ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Row( children: [ Icon( Icons.error_outline_outlined, color: Theme.of(context).colorScheme.secondary, ), SizedBox( width: 10, ), Text( "NO WALLPAPERS TO DELETE!", ), ], ), backgroundColor: Theme.of(context).colorScheme.primary, )); } }, ), SizedBox( height: 20, ), Padding( padding: const EdgeInsets.only(left: 20), child: Text("FEEDBACK & NOTIFICATIONS"), ), ListTile( minVerticalPadding: 10, horizontalTitleGap: 20, leading: Icon( Icons.rate_review_outlined, color: Theme.of(context).colorScheme.primary, ), title: Text("FEEDBACK", style: Theme.of(context).textTheme.button), subtitle: Text("YOUR FEEDBACKS AND SUGGESTIONS GOES HERE", style: TextStyle(fontSize: 10)), onTap: () { HapticFeedback.mediumImpact(); feedbackForm(); }, ), ListTile( minVerticalPadding: 10, horizontalTitleGap: 20, leading: Icon( _subscribedNotification ? Icons.notifications_active_outlined : Icons.notifications_none_outlined, color: _subscribedNotification ? isDark ? Colors.greenAccent : Colors.green : Colors.redAccent, ), title: _subscribedNotification ? Text("SUBSCRIBED TO NOTIFICATION", style: Theme.of(context).textTheme.button) : Text("SUBSCRIBE TO NOTIFICATION", style: Theme.of(context).textTheme.button), subtitle: Text( "SUBSCRIBE TO NOTIFICATIONS TO GET LATEST UPDATES", style: TextStyle(fontSize: 10), ), trailing: TextButton( style: TextButton.styleFrom( backgroundColor: Theme.of(context).cardColor, shape: RoundedRectangleBorder( borderRadius: BorderRadius.zero, side: BorderSide( color: Theme.of(context).accentColor))), onPressed: () { setState(() { _subscribedNotification = !_subscribedNotification; }); if (_subscribedNotification) { fcmNotification.unSubscribeToTopic('notification'); FirebaseFirestore.instance .collection("User") .doc(user.uid) .update({ "subscribedToNotifications": _subscribedNotification }); } if (!_subscribedNotification) { fcmNotification.subscribeToTopic('notification'); FirebaseFirestore.instance .collection("User") .doc(user.uid) .update({ "subscribedToNotifications": _subscribedNotification }); } }, child: _subscribedNotification ? Text( "UNSUBSCRIBE", style: TextStyle( color: Theme.of(context).colorScheme.primary, fontSize: 10, fontFamily: 'Theme Bold'), ) : Text( "SUBSCRIBE", style: TextStyle( color: Theme.of(context).colorScheme.primary, fontSize: 10, fontFamily: 'Theme Bold'), ), )), SizedBox( height: 20, ), Padding( padding: const EdgeInsets.only(left: 20), child: Text("ABOUT"), ), ListTile( minVerticalPadding: 10, horizontalTitleGap: 20, leading: Icon( Icons.build_circle_outlined, color: Theme.of(context).colorScheme.primary, ), title: Text("VERSION AND BUILD NUMBER", style: Theme.of(context).textTheme.button), subtitle: Text( "v" + _packageInfo.version + " (build v" + _packageInfo.buildNumber + ")", style: TextStyle(fontSize: 10), ), ), ListTile( minVerticalPadding: 10, horizontalTitleGap: 20, leading: Icon( Icons.tag, color: Theme.of(context).colorScheme.primary, ), title: Text("APPLICATION ID", style: Theme.of(context).textTheme.button), subtitle: Text( _packageInfo.packageName, style: TextStyle(fontSize: 10), ), ), ListTile( minVerticalPadding: 10, horizontalTitleGap: 20, leading: Icon( Icons.info_outlined, color: Theme.of(context).colorScheme.primary, ), title: Text( "ABOUT FELEXO", style: Theme.of(context).textTheme.button, ), subtitle: Text( "LICENSES & CERTIFICATES", style: TextStyle(fontSize: 10), ), onTap: () { HapticFeedback.mediumImpact(); Navigator.push( context, CupertinoPageRoute( builder: (context) => LicensePage( applicationIcon: Padding( padding: const EdgeInsets.all(10.0), child: ClipRRect( borderRadius: BorderRadius.circular(50), child: CachedNetworkImage( imageUrl: logoPlayStore, fadeInCurve: Curves.easeIn, fadeInDuration: const Duration(milliseconds: 500), width: 80, height: 80, ), ), ), applicationLegalese: "Apache License\nVersion 2.0, January 2004", applicationName: _packageInfo.appName, applicationVersion: "v" + _packageInfo.version + " (build v" + _packageInfo.buildNumber + ")", ))); }, ), SizedBox( height: 20, ), Align( alignment: Alignment.bottomCenter, child: Center( child: Container( width: MediaQuery.of(context).size.width - 30, height: 60, child: ElevatedButton( onPressed: () { signOutGoogle(context); }, style: ElevatedButton.styleFrom( elevation: 0, primary: Theme.of(context).scaffoldBackgroundColor, onPrimary: Theme.of(context).colorScheme.primary, shape: RoundedRectangleBorder( side: BorderSide( color: Theme.of(context) .accentColor .withOpacity(0.5), width: 1), borderRadius: BorderRadius.circular(0))), child: Text( "LOGOUT", ), ), ), ), ), SizedBox( height: 30, ), ], ), ), ), ), ); } void feedbackForm() { showDialog( useSafeArea: true, context: context, builder: (context) => ExpandableBottomSheet( persistentContentHeight: MediaQuery.of(context).size.height / 2, expandableContent: Container( width: MediaQuery.of(context).size.width, height: 640, decoration: BoxDecoration( color: Theme.of(context).scaffoldBackgroundColor, borderRadius: BorderRadius.only( topLeft: Radius.circular(0), topRight: Radius.circular(0))), child: Column( children: [ SizedBox( height: 10, ), Icon( Icons.maximize_outlined, color: Theme.of(context).colorScheme.primary, ), Form( child: Theme( data: ThemeData( indicatorColor: Theme.of(context).colorScheme.primary, textTheme: TextTheme( bodyText1: Theme.of(context).textTheme.bodyText1, headline1: Theme.of(context).textTheme.headline1, subtitle1: Theme.of(context).textTheme.subtitle1, subtitle2: Theme.of(context).textTheme.subtitle2, bodyText2: Theme.of(context).textTheme.bodyText2, caption: Theme.of(context).textTheme.caption, ), inputDecorationTheme: InputDecorationTheme( fillColor: Theme.of(context).scaffoldBackgroundColor, focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(0), borderSide: BorderSide( color: Theme.of(context).colorScheme.primary, width: 1)), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(0), borderSide: BorderSide( color: Theme.of(context).colorScheme.primary, width: 2)), counterStyle: TextStyle( color: Theme.of(context).colorScheme.primary), labelStyle: TextStyle( color: Theme.of(context).colorScheme.primary, fontFamily: 'Theme Bold')), ), child: Column( children: [ Padding( padding: const EdgeInsets.only(right: 15.0, left: 15), child: Material( color: Theme.of(context).scaffoldBackgroundColor, child: TextFormField( controller: subject, textCapitalization: TextCapitalization.words, keyboardType: TextInputType.text, maxLength: 20, decoration: InputDecoration( labelText: "Subject", ), ), ), ), Padding( padding: const EdgeInsets.only(right: 15.0, left: 15), child: Material( color: Theme.of(context).scaffoldBackgroundColor, child: TextFormField( controller: feedback, textCapitalization: TextCapitalization.sentences, keyboardType: TextInputType.multiline, maxLines: null, minLines: null, maxLength: 100, decoration: InputDecoration( labelText: "Feedback", ), ), ), ), SizedBox( height: 20, ), Material( child: InkWell( onTap: () async { feedbackToken = "#" + randomAlphaNumeric(5).toString(); await FirebaseFirestore.instance .collection("Feedbacks") .doc(feedbackToken) .set({ "uid": user.uid, "email": user.email, "name": user.displayName, "subject": subject.text, "feedback": feedback.text }); Navigator.pop(context); showDialog( context: context, builder: (context) => AlertDialog( backgroundColor: Theme.of(context) .colorScheme .secondary, actions: [ TextButton( onPressed: () { Navigator.pop(context); }, child: Text( "OK", style: Theme.of(context) .textTheme .button, ), ) ], content: Text( "Your feedback is received and you can refer back to it by using the token: " + feedbackToken, style: Theme.of(context) .textTheme .bodyText2, ), )); }, child: Center( child: Container( width: MediaQuery.of(context).size.width - 20, height: 60, color: Theme.of(context).colorScheme.primary, child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Text("SEND", style: TextStyle( color: Theme.of(context) .colorScheme .secondary, fontFamily: 'Theme Bold')), ], ), ), ), ), ), ], ), ), ) ], ), ), background: Container( color: Colors.transparent, ), )); } // void onThemeChanged(String val, ThemeModeNotifier themeModeNotifier) async { // var themeModePrefs = await SharedPreferences.getInstance(); // if (val == "ThemeMode.system") { // themeModeNotifier.setMode(ThemeMode.system); // } // if (val == "ThemeMode.dark") { // themeModeNotifier.setMode(ThemeMode.dark); // } // if (val == "ThemeMode.light") { // themeModeNotifier.setMode(ThemeMode.light); // } // themeModePrefs.setString("appTheme", val); // } }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Views/favorites-view.dart
import 'package:felexo/Data/favorites-data.dart'; import 'package:felexo/Services/favorites-list.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; class FavoritesView extends StatefulWidget { @override _FavoritesViewState createState() => _FavoritesViewState(); } class _FavoritesViewState extends State<FavoritesView> { final FirebaseAuth _auth = FirebaseAuth.instance; User user; @override void initState() { initUser(); super.initState(); } initUser() async { user = _auth.currentUser; assert(user.email != null); assert(user.uid != null); assert(user.photoURL != null); setState(() {}); } @override Widget build(BuildContext context) { return Container( height: 800, child: StreamProvider<List<Favorites>>.value( value: DatabaseService(uid: user.uid).favorites, initialData: [], child: FavoritesList()), ); } }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Views/collections-view.dart
import 'package:felexo/Widget/collectionsGridView.dart'; import 'package:flutter/material.dart'; import 'package:flutter/cupertino.dart'; class CollectionsView extends StatefulWidget { @override _CollectionsViewState createState() => _CollectionsViewState(); } class _CollectionsViewState extends State<CollectionsView> { @override Widget build(BuildContext context) { return Scaffold( body: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [ CollectionsGrid(), ], ), ), ); } }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Views/home-view.dart
import 'dart:async'; import 'package:felexo/Widget/widgets.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; const String testDevices = "mobileID"; class HomeView extends StatefulWidget { @override _HomeViewState createState() => _HomeViewState(); } class _HomeViewState extends State<HomeView> with SingleTickerProviderStateMixin { User user; String wallpaperLocation, imgUrl, originalUrl, photoID, photographer, photographerID, avgColor, nextPage, photographerUrl; var foregroundColor; int pageNumber = 1; Timer timer; bool isLoading = true; Map data; @override void initState() { super.initState(); setState(() {}); initUser(); } Future initUser() async { user = FirebaseAuth.instance.currentUser; assert(user.email != null); assert(user.uid != null); assert(user.photoURL != null); // print("User: " + user.uid.toString()); // assert(imgUrl != null); // assert(originalUrl != null); // assert(photoID != null); // assert(photographer != null); // assert(photographerID != null); // assert(photographerUrl != null); // assert(avgColor != null); setState(() {}); } @override Widget build(BuildContext context) { return Scaffold( body: SingleChildScrollView( child: Column( children: [ Curated(), ], ))); } @override void dispose() { super.dispose(); } }
0
mirrored_repositories/felexo-app/lib
mirrored_repositories/felexo-app/lib/Color/colors.dart
import 'dart:ui'; import 'package:flutter/material.dart'; Map<int, Color> color = { 50: Color.fromRGBO(136, 14, 79, .1), 100: Color.fromRGBO(136, 14, 79, .2), 200: Color.fromRGBO(136, 14, 79, .3), 300: Color.fromRGBO(136, 14, 79, .4), 400: Color.fromRGBO(136, 14, 79, .5), 500: Color.fromRGBO(136, 14, 79, .6), 600: Color.fromRGBO(136, 14, 79, .7), 700: Color.fromRGBO(136, 14, 79, .8), 800: Color.fromRGBO(136, 14, 79, .9), 900: Color.fromRGBO(136, 14, 79, 1), }; MaterialColor backgroundColor = MaterialColor(0xFF0C0C0C, color); MaterialColor backgroundColorLight = MaterialColor(0xFFF7F7F7, color); MaterialColor primaryColor = MaterialColor(0xFFFFFFFF, color); MaterialColor cardColor = MaterialColor(0xFF000000, color); MaterialColor cardColorLight = MaterialColor(0xFFFFFFFF, color); MaterialColor textColor = MaterialColor(0xFFFFFFFF, color); MaterialColor iconColor = MaterialColor(0xff5f6368, color); MaterialColor iconColorLight = MaterialColor(0xFF9298A0, color); class Hexcolor extends Color { static int _getColorFromHex(String hexColor) { hexColor = hexColor.toUpperCase().replaceAll("#", ""); if (hexColor.length == 6) { hexColor = "FF" + hexColor; } return int.parse(hexColor, radix: 16); } Hexcolor(final String hexColor) : super(_getColorFromHex(hexColor)); }
0
mirrored_repositories/felexo-app
mirrored_repositories/felexo-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:felexo/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/DhiBasket
mirrored_repositories/DhiBasket/lib/generated_plugin_registrant.dart
// // Generated file. Do not edit. // // ignore_for_file: directives_ordering // ignore_for_file: lines_longer_than_80_chars // ignore_for_file: depend_on_referenced_packages import 'package:cloud_firestore_web/cloud_firestore_web.dart'; import 'package:connectivity_plus_web/connectivity_plus_web.dart'; import 'package:file_picker/_internal/file_picker_web.dart'; import 'package:firebase_auth_web/firebase_auth_web.dart'; import 'package:firebase_core_web/firebase_core_web.dart'; import 'package:flutter_facebook_auth_web/flutter_facebook_auth_web.dart'; import 'package:google_sign_in_web/google_sign_in_web.dart'; import 'package:shared_preferences_web/shared_preferences_web.dart'; import 'package:flutter_web_plugins/flutter_web_plugins.dart'; // ignore: public_member_api_docs void registerPlugins(Registrar registrar) { FirebaseFirestoreWeb.registerWith(registrar); ConnectivityPlusPlugin.registerWith(registrar); FilePickerWeb.registerWith(registrar); FirebaseAuthWeb.registerWith(registrar); FirebaseCoreWeb.registerWith(registrar); FlutterFacebookAuthPlugin.registerWith(registrar); GoogleSignInPlugin.registerWith(registrar); SharedPreferencesPlugin.registerWith(registrar); registrar.registerMessageHandler(); }
0
mirrored_repositories/DhiBasket
mirrored_repositories/DhiBasket/lib/main.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'core/app_export.dart'; void main() { WidgetsFlutterBinding.ensureInitialized(); SystemChrome.setPreferredOrientations([ DeviceOrientation.portraitUp, ]); runApp(MyApp()); } class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return GetMaterialApp( debugShowCheckedModeBanner: false, translations: AppLocalization(), locale: Get.deviceLocale, //for setting localization strings fallbackLocale: Locale('en', 'US'), title: 'grocery_app', initialBinding: InitialBindings(), initialRoute: AppRoutes.initialRoute, getPages: AppRoutes.pages, ); } }
0
mirrored_repositories/DhiBasket/lib
mirrored_repositories/DhiBasket/lib/widgets/custom_button.dart
import 'package:flutter/material.dart'; import 'package:grocery_app/core/app_export.dart'; class CustomButton extends StatelessWidget { CustomButton( {this.shape, this.padding, this.variant, this.fontStyle, this.alignment, this.onTap, this.width, this.margin, this.text}); ButtonShape? shape; ButtonPadding? padding; ButtonVariant? variant; ButtonFontStyle? fontStyle; Alignment? alignment; VoidCallback? onTap; double? width; EdgeInsetsGeometry? margin; String? text; @override Widget build(BuildContext context) { return alignment != null ? Align( alignment: alignment ?? Alignment.center, child: _buildButtonWidget(), ) : _buildButtonWidget(); } _buildButtonWidget() { return InkWell( onTap: onTap, child: Container( width: getHorizontalSize(width ?? 0), margin: margin, padding: _setPadding(), decoration: _buildDecoration(), child: Text( text ?? "", textAlign: TextAlign.center, style: _setFontStyle(), ), ), ); } _buildDecoration() { return BoxDecoration( color: _setColor(), border: _setBorder(), borderRadius: _setBorderRadius(), boxShadow: _setBoxShadow(), ); } _setPadding() { switch (padding) { case ButtonPadding.PaddingAll10: return getPadding( all: 10, ); default: return getPadding( all: 14, ); } } _setColor() { switch (variant) { case ButtonVariant.OutlineIndigoA20033: return ColorConstant.green500; case ButtonVariant.FillGray300d8: return ColorConstant.gray300D8; case ButtonVariant.OutlineGreen500: return null; default: return ColorConstant.green500; } } _setBorder() { switch (variant) { case ButtonVariant.OutlineGreen500: return Border.all( color: ColorConstant.green500, width: getHorizontalSize( 1.00, ), ); case ButtonVariant.FillGreen500: case ButtonVariant.OutlineIndigoA20033: case ButtonVariant.FillGray300d8: return null; default: return null; } } _setBorderRadius() { switch (shape) { case ButtonShape.RoundedBorder10: return BorderRadius.circular( getHorizontalSize( 10.00, ), ); case ButtonShape.RoundedBorder2: return BorderRadius.circular( getHorizontalSize( 2.66, ), ); case ButtonShape.Square: return BorderRadius.circular(0); default: return BorderRadius.circular( getHorizontalSize( 5.00, ), ); } } _setBoxShadow() { switch (variant) { case ButtonVariant.OutlineIndigoA20033: return [ BoxShadow( color: ColorConstant.indigoA20033, spreadRadius: getHorizontalSize( 2.00, ), blurRadius: getHorizontalSize( 2.00, ), offset: Offset( 0, 4, ), ) ]; case ButtonVariant.FillGreen500: case ButtonVariant.OutlineGreen500: case ButtonVariant.FillGray300d8: return null; default: return null; } } _setFontStyle() { switch (fontStyle) { case ButtonFontStyle.MontserratSemiBold16Green500: return TextStyle( color: ColorConstant.green500, fontSize: getFontSize( 16, ), fontFamily: 'Montserrat', fontWeight: FontWeight.w600, ); case ButtonFontStyle.MontserratSemiBold18: return TextStyle( color: ColorConstant.whiteA700, fontSize: getFontSize( 18, ), fontFamily: 'Montserrat', fontWeight: FontWeight.w600, ); case ButtonFontStyle.MontserratSemiBold2661: return TextStyle( color: ColorConstant.whiteA700, fontSize: getFontSize( 26.61, ), fontFamily: 'Montserrat', fontWeight: FontWeight.w600, ); default: return TextStyle( color: ColorConstant.whiteA700, fontSize: getFontSize( 16, ), fontFamily: 'Montserrat', fontWeight: FontWeight.w600, ); } } } enum ButtonShape { Square, RoundedBorder5, RoundedBorder10, RoundedBorder2, } enum ButtonPadding { PaddingAll10, PaddingAll14, } enum ButtonVariant { FillGreen500, OutlineGreen500, OutlineIndigoA20033, FillGray300d8, } enum ButtonFontStyle { MontserratSemiBold16, MontserratSemiBold16Green500, MontserratSemiBold18, MontserratSemiBold2661, }
0
mirrored_repositories/DhiBasket/lib
mirrored_repositories/DhiBasket/lib/widgets/custom_checkbox.dart
import 'package:flutter/material.dart'; import 'package:grocery_app/core/app_export.dart'; class CustomCheckbox extends StatelessWidget { CustomCheckbox( {this.shape, this.variant, this.fontStyle, this.alignment, this.padding, this.iconSize, this.value, this.onChange, this.text}); CheckboxShape? shape; CheckboxVariant? variant; CheckboxFontStyle? fontStyle; Alignment? alignment; EdgeInsetsGeometry? padding; double? iconSize; bool? value; Function(bool)? onChange; String? text; @override Widget build(BuildContext context) { return alignment != null ? Align( alignment: alignment ?? Alignment.center, child: _buildCheckboxWidget(), ) : _buildCheckboxWidget(); } _buildCheckboxWidget() { return Padding( padding: padding ?? EdgeInsets.zero, child: InkWell( onTap: () { value = !(value!); onChange!(value!); }, child: Row( children: [ SizedBox( height: getHorizontalSize(iconSize ?? 0), width: getHorizontalSize(iconSize ?? 0), child: Checkbox( shape: _setShape(), value: value ?? false, onChanged: (value) { onChange!(value!); }, ), ), Padding( padding: getPadding( left: 10, ), child: Text( text ?? "", textAlign: TextAlign.center, style: _setFontStyle(), ), ), ], ), ), ); } _setOutlineBorderRadius() { switch (shape) { default: return BorderRadius.circular( getHorizontalSize( 2.00, ), ); } } _setShape() { switch (variant) { default: return RoundedRectangleBorder( side: BorderSide( color: ColorConstant.gray503, width: 1, ), borderRadius: _setOutlineBorderRadius(), ); } } _setFontStyle() { switch (fontStyle) { default: return TextStyle( color: ColorConstant.gray500, fontSize: getFontSize( 14, ), fontFamily: 'Montserrat', fontWeight: FontWeight.w400, ); } } } enum CheckboxShape { RoundedBorder2 } enum CheckboxVariant { OutlineGray503 } enum CheckboxFontStyle { MontserratRegular14 }
0
mirrored_repositories/DhiBasket/lib
mirrored_repositories/DhiBasket/lib/widgets/custom_drop_down.dart
import 'package:flutter/material.dart'; import 'package:grocery_app/core/app_export.dart'; class CustomDropDown extends StatelessWidget { CustomDropDown( {this.shape, this.padding, this.variant, this.fontStyle, this.alignment, this.width, this.margin, this.focusNode, this.icon, this.hintText, this.prefix, this.prefixConstraints, this.items, this.onChanged, this.validator}); DropDownShape? shape; DropDownPadding? padding; DropDownVariant? variant; DropDownFontStyle? fontStyle; Alignment? alignment; double? width; EdgeInsetsGeometry? margin; FocusNode? focusNode; Widget? icon; String? hintText; Widget? prefix; BoxConstraints? prefixConstraints; List<SelectionPopupModel>? items; Function(SelectionPopupModel)? onChanged; FormFieldValidator<SelectionPopupModel>? validator; @override Widget build(BuildContext context) { return alignment != null ? Align( alignment: alignment ?? Alignment.center, child: _buildDropDownWidget(), ) : _buildDropDownWidget(); } _buildDropDownWidget() { return Container( width: getHorizontalSize(width ?? 0), margin: margin, child: DropdownButtonFormField<SelectionPopupModel>( focusNode: focusNode, icon: icon, style: _setFontStyle(), decoration: _buildDecoration(), items: items?.map((SelectionPopupModel item) { return DropdownMenuItem<SelectionPopupModel>( value: item, child: Text( item.title, overflow: TextOverflow.ellipsis, ), ); }).toList(), onChanged: (value) { onChanged!(value!); }, validator: validator, ), ); } _buildDecoration() { return InputDecoration( hintText: hintText ?? "", hintStyle: _setFontStyle(), border: _setBorderStyle(), focusedBorder: _setBorderStyle(), prefixIcon: prefix, prefixIconConstraints: prefixConstraints, fillColor: _setFillColor(), filled: _setFilled(), isDense: true, contentPadding: _setPadding(), ); } _setFontStyle() { switch (fontStyle) { case DropDownFontStyle.MontserratRegular18: return TextStyle( color: ColorConstant.gray500, fontSize: getFontSize( 18, ), fontFamily: 'Montserrat', fontWeight: FontWeight.w400, ); default: return TextStyle( color: ColorConstant.gray604, fontSize: getFontSize( 16, ), fontFamily: 'Montserrat', fontWeight: FontWeight.w400, ); } } _setOutlineBorderRadius() { switch (shape) { default: return BorderRadius.circular( getHorizontalSize( 10.00, ), ); } } _setBorderStyle() { switch (variant) { case DropDownVariant.FillGray102: return OutlineInputBorder( borderRadius: _setOutlineBorderRadius(), borderSide: BorderSide.none, ); case DropDownVariant.FillGray101: return OutlineInputBorder( borderRadius: _setOutlineBorderRadius(), borderSide: BorderSide.none, ); default: return OutlineInputBorder( borderRadius: _setOutlineBorderRadius(), borderSide: BorderSide.none, ); } } _setFillColor() { switch (variant) { case DropDownVariant.FillGray101: return ColorConstant.gray101; default: return ColorConstant.gray102; } } _setFilled() { switch (variant) { case DropDownVariant.FillGray101: return true; default: return true; } } _setPadding() { switch (padding) { case DropDownPadding.PaddingT18: return getPadding( left: 11, top: 18, right: 11, bottom: 11, ); case DropDownPadding.PaddingTB21: return getPadding( left: 19, top: 19, right: 19, bottom: 21, ); default: return getPadding( left: 16, top: 24, right: 16, bottom: 16, ); } } } enum DropDownShape { RoundedBorder10, } enum DropDownPadding { PaddingT24, PaddingT18, PaddingTB21, } enum DropDownVariant { FillGray102, FillGray101, } enum DropDownFontStyle { MontserratRegular16, MontserratRegular18, }
0
mirrored_repositories/DhiBasket/lib
mirrored_repositories/DhiBasket/lib/widgets/common_image_view.dart
// ignore_for_file: must_be_immutable import 'dart:io'; import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; class CommonImageView extends StatelessWidget { ///[url] is required parameter for fetching network image String? url; String? imagePath; String? svgPath; File? file; double? height; double? width; final BoxFit fit; final String placeHolder; ///a [CommonNetworkImageView] it can be used for showing any network images /// it will shows the placeholder image if image is not found on network CommonImageView({ this.url, this.imagePath, this.svgPath, this.file, this.height, this.width, this.fit = BoxFit.fill, this.placeHolder = 'assets/images/image_not_found.png', }); @override Widget build(BuildContext context) { return _buildImageView(); } Widget _buildImageView() { if (svgPath != null && svgPath!.isNotEmpty) { return Container( height: height, width: width, child: SvgPicture.asset( svgPath!, height: height, width: width, fit: fit, ), ); } else if (file != null && file!.path.isNotEmpty) { return Image.file( file!, height: height, width: width, fit: fit, ); } else if (url != null && url!.isNotEmpty) { return CachedNetworkImage( height: height, width: width, fit: fit, imageUrl: url!, placeholder: (context, url) => Container( height: 30, width: 30, child: LinearProgressIndicator( color: Colors.grey.shade200, backgroundColor: Colors.grey.shade100, ), ), errorWidget: (context, url, error) => Image.asset( placeHolder, height: height, width: width, fit: fit, ), ); } else if (imagePath != null && imagePath!.isNotEmpty) { return Image.asset( imagePath!, height: height, width: width, fit: fit, ); } return SizedBox(); } }
0
mirrored_repositories/DhiBasket/lib
mirrored_repositories/DhiBasket/lib/widgets/custom_text_form_field.dart
import 'package:flutter/material.dart'; import 'package:grocery_app/core/app_export.dart'; class CustomTextFormField extends StatelessWidget { CustomTextFormField( {this.shape, this.padding, this.variant, this.fontStyle, this.alignment, this.width, this.margin, this.controller, this.focusNode, this.isObscureText = false, this.textInputAction = TextInputAction.next, this.hintText, this.prefix, this.prefixConstraints, this.suffix, this.suffixConstraints, this.validator}); TextFormFieldShape? shape; TextFormFieldPadding? padding; TextFormFieldVariant? variant; TextFormFieldFontStyle? fontStyle; Alignment? alignment; double? width; EdgeInsetsGeometry? margin; TextEditingController? controller; FocusNode? focusNode; bool? isObscureText; TextInputAction? textInputAction; String? hintText; Widget? prefix; BoxConstraints? prefixConstraints; Widget? suffix; BoxConstraints? suffixConstraints; FormFieldValidator<String>? validator; @override Widget build(BuildContext context) { return alignment != null ? Align( alignment: alignment ?? Alignment.center, child: _buildTextFormFieldWidget(), ) : _buildTextFormFieldWidget(); } _buildTextFormFieldWidget() { return Container( width: getHorizontalSize(width ?? 0), margin: margin, child: TextFormField( controller: controller, focusNode: focusNode, style: _setFontStyle(), obscureText: isObscureText!, textInputAction: textInputAction, decoration: _buildDecoration(), validator: validator, ), ); } _buildDecoration() { return InputDecoration( hintText: hintText ?? "", hintStyle: _setFontStyle(), border: _setBorderStyle(), enabledBorder: _setBorderStyle(), focusedBorder: _setBorderStyle(), disabledBorder: _setBorderStyle(), prefixIcon: prefix, prefixIconConstraints: prefixConstraints, suffixIcon: suffix, suffixIconConstraints: suffixConstraints, fillColor: _setFillColor(), filled: _setFilled(), isDense: true, contentPadding: _setPadding(), ); } _setFontStyle() { switch (fontStyle) { case TextFormFieldFontStyle.MontserratRegular16: return TextStyle( color: ColorConstant.bluegray400, fontSize: getFontSize( 16, ), fontFamily: 'Montserrat', fontWeight: FontWeight.w400, ); case TextFormFieldFontStyle.MontserratSemiBold12: return TextStyle( color: ColorConstant.whiteA700, fontSize: getFontSize( 12, ), fontFamily: 'Montserrat', fontWeight: FontWeight.w600, ); case TextFormFieldFontStyle.MontserratSemiBold14: return TextStyle( color: ColorConstant.green500, fontSize: getFontSize( 14, ), fontFamily: 'Montserrat', fontWeight: FontWeight.w600, ); default: return TextStyle( color: ColorConstant.gray500, fontSize: getFontSize( 18, ), fontFamily: 'Montserrat', fontWeight: FontWeight.w400, ); } } _setOutlineBorderRadius() { switch (shape) { case TextFormFieldShape.RoundedBorder3: return BorderRadius.circular( getHorizontalSize( 3.00, ), ); default: return BorderRadius.circular( getHorizontalSize( 10.00, ), ); } } _setBorderStyle() { switch (variant) { case TextFormFieldVariant.OutlineGray501: return OutlineInputBorder( borderRadius: _setOutlineBorderRadius(), borderSide: BorderSide( color: ColorConstant.gray501, width: 1, ), ); case TextFormFieldVariant.FillGreen500: return OutlineInputBorder( borderRadius: _setOutlineBorderRadius(), borderSide: BorderSide.none, ); case TextFormFieldVariant.FillGray102: return OutlineInputBorder( borderRadius: _setOutlineBorderRadius(), borderSide: BorderSide.none, ); default: return OutlineInputBorder( borderRadius: _setOutlineBorderRadius(), borderSide: BorderSide.none, ); } } _setFillColor() { switch (variant) { case TextFormFieldVariant.OutlineGray501: return ColorConstant.whiteA700; case TextFormFieldVariant.FillGreen500: return ColorConstant.green500; case TextFormFieldVariant.FillGray102: return ColorConstant.gray102; default: return ColorConstant.gray101; } } _setFilled() { switch (variant) { case TextFormFieldVariant.OutlineGray501: return true; case TextFormFieldVariant.FillGreen500: return true; case TextFormFieldVariant.FillGray102: return true; default: return true; } } _setPadding() { switch (padding) { case TextFormFieldPadding.PaddingTB20: return getPadding( left: 16, top: 16, right: 16, bottom: 20, ); case TextFormFieldPadding.PaddingTB7: return getPadding( left: 6, top: 6, right: 6, bottom: 7, ); case TextFormFieldPadding.PaddingT24: return getPadding( left: 21, top: 24, right: 21, bottom: 21, ); default: return getPadding( all: 21, ); } } } enum TextFormFieldShape { RoundedBorder10, RoundedBorder3, } enum TextFormFieldPadding { PaddingAll21, PaddingTB20, PaddingTB7, PaddingT24, } enum TextFormFieldVariant { FillGray101, OutlineGray501, FillGreen500, FillGray102, } enum TextFormFieldFontStyle { MontserratRegular18, MontserratRegular16, MontserratSemiBold12, MontserratSemiBold14, }
0
mirrored_repositories/DhiBasket/lib
mirrored_repositories/DhiBasket/lib/widgets/custom_icon_button.dart
import 'package:flutter/material.dart'; import 'package:grocery_app/core/app_export.dart'; class CustomIconButton extends StatelessWidget { CustomIconButton( {this.shape, this.padding, this.variant, this.alignment, this.margin, this.height, this.width, this.child, this.onTap}); IconButtonShape? shape; IconButtonPadding? padding; IconButtonVariant? variant; Alignment? alignment; EdgeInsetsGeometry? margin; double? height; double? width; Widget? child; VoidCallback? onTap; @override Widget build(BuildContext context) { return alignment != null ? Align( alignment: alignment ?? Alignment.center, child: _buildIconButtonWidget(), ) : _buildIconButtonWidget(); } _buildIconButtonWidget() { return Padding( padding: margin ?? EdgeInsets.zero, child: IconButton( constraints: BoxConstraints( minHeight: getSize(height ?? 0), minWidth: getSize(width ?? 0), ), padding: EdgeInsets.all(0), icon: Container( alignment: Alignment.center, width: getSize(width ?? 0), height: getSize(height ?? 0), padding: _setPadding(), decoration: _buildDecoration(), child: child, ), onPressed: onTap, ), ); } _buildDecoration() { return BoxDecoration( color: _setColor(), borderRadius: _setBorderRadius(), ); } _setPadding() { switch (padding) { case IconButtonPadding.PaddingAll4: return getPadding( all: 4, ); default: return getPadding( all: 7, ); } } _setColor() { switch (variant) { default: return ColorConstant.green500; } } _setBorderRadius() { switch (shape) { default: return BorderRadius.circular( getHorizontalSize( 10.00, ), ); } } } enum IconButtonShape { RoundedBorder10, } enum IconButtonPadding { PaddingAll7, PaddingAll4, } enum IconButtonVariant { FillGreen500, }
0
mirrored_repositories/DhiBasket/lib
mirrored_repositories/DhiBasket/lib/routes/app_routes.dart
import 'package:grocery_app/presentation/add_new_address_screen/add_new_address_screen.dart'; import 'package:grocery_app/presentation/add_new_address_screen/binding/add_new_address_binding.dart'; import 'package:grocery_app/presentation/details_screen/details_screen.dart'; import 'package:grocery_app/presentation/details_screen/binding/details_binding.dart'; import 'package:grocery_app/presentation/explore_screen/explore_screen.dart'; import 'package:grocery_app/presentation/explore_screen/binding/explore_binding.dart'; import 'package:grocery_app/presentation/home_screen/home_screen.dart'; import 'package:grocery_app/presentation/home_screen/binding/home_binding.dart'; import 'package:grocery_app/presentation/login_with_email_id_screen/login_with_email_id_screen.dart'; import 'package:grocery_app/presentation/login_with_email_id_screen/binding/login_with_email_id_binding.dart'; import 'package:grocery_app/presentation/register_screen/register_screen.dart'; import 'package:grocery_app/presentation/register_screen/binding/register_binding.dart'; import 'package:grocery_app/presentation/fruits_screen/fruits_screen.dart'; import 'package:grocery_app/presentation/fruits_screen/binding/fruits_binding.dart'; import 'package:grocery_app/presentation/wishlist_screen/wishlist_screen.dart'; import 'package:grocery_app/presentation/wishlist_screen/binding/wishlist_bindings.dart'; import 'package:grocery_app/presentation/my_addresses_screen/my_addresses_screen.dart'; import 'package:grocery_app/presentation/my_addresses_screen/binding/my_addresses_binding.dart'; import 'package:grocery_app/presentation/my_orders_screen/my_orders_screen.dart'; import 'package:grocery_app/presentation/my_orders_screen/binding/my_orders_binding.dart'; import 'package:grocery_app/presentation/contact_us_screen/contact_us_screen.dart'; import 'package:grocery_app/presentation/contact_us_screen/binding/contact_us_binding.dart'; import 'package:grocery_app/presentation/privacy_policy_screen/privacy_policy_screen.dart'; import 'package:grocery_app/presentation/privacy_policy_screen/binding/privacy_policy_binding.dart'; import 'package:grocery_app/presentation/my_cart_screen/my_cart_screen.dart'; import 'package:grocery_app/presentation/my_cart_screen/binding/my_cart_binding.dart'; import 'package:grocery_app/presentation/user_screen/user_screen.dart'; import 'package:grocery_app/presentation/user_screen/binding/user_binding.dart'; import 'package:grocery_app/presentation/splash_screen/splash_screen.dart'; import 'package:grocery_app/presentation/splash_screen/binding/splash_binding.dart'; import 'package:grocery_app/presentation/terms_of_services_screen/terms_of_services_screen.dart'; import 'package:grocery_app/presentation/terms_of_services_screen/binding/terms_of_services_binding.dart'; import 'package:grocery_app/presentation/about_us_screen/about_us_screen.dart'; import 'package:grocery_app/presentation/about_us_screen/binding/about_us_binding.dart'; import 'package:grocery_app/presentation/app_navigation_screen/app_navigation_screen.dart'; import 'package:grocery_app/presentation/app_navigation_screen/binding/app_navigation_binding.dart'; import 'package:get/get.dart'; class AppRoutes { static String detailsScreen = '/details_screen'; static String exploreScreen = '/explore_screen'; static String homeScreen = '/home_screen'; static String loginWithEmailIdScreen = '/login_with_email_id_screen'; static String registerScreen = '/register_screen'; static String fruitsScreen = '/fruits_screen'; static String wishlistScreen = '/wishlist_screen'; static String myAddressesScreen = '/my_addresses_screen'; static String myOrdersScreen = '/my_orders_screen'; static String contactUsScreen = '/contact_us_screen'; static String privacyPolicyScreen = '/privacy_policy_screen'; static String myCartScreen = '/my_cart_screen'; static String userScreen = '/user_screen'; static String splashScreen = '/splash_screen'; static String termsOfServicesScreen = '/terms_of_services_screen'; static String explorePopupScreen = '/explore_popup_screen'; static String aboutUsScreen = '/about_us_screen'; static String appNavigationScreen = '/app_navigation_screen'; static String addNewAddress = '/add_new_address'; static String initialRoute = '/initialRoute'; static List<GetPage> pages = [ GetPage( name: detailsScreen, page: () => DetailsScreen(), bindings: [ DetailsBinding(), ], ), GetPage( name: exploreScreen, page: () => ExploreScreen(), bindings: [ ExploreBinding(), ], ), GetPage( name: homeScreen, page: () => HomeScreen(), bindings: [ HomeBinding(), ], ), GetPage( name: loginWithEmailIdScreen, page: () => LoginWithEmailIdScreen(), bindings: [ LoginWithEmailIdBinding(), ], ), GetPage( name: registerScreen, page: () => RegisterScreen(), bindings: [ RegisterBinding(), ], ), GetPage( name: fruitsScreen, page: () => FruitsScreen(), bindings: [ FruitsBinding(), ], ), GetPage( name: wishlistScreen, page: () => WishlistScreen(), bindings: [ WishlistBinding(), ], ), GetPage( name: myAddressesScreen, page: () => MyAddressesScreen(), bindings: [ MyAddressesBinding(), ], ), GetPage( name: myOrdersScreen, page: () => MyOrdersScreen(), bindings: [ MyOrdersBinding(), ], ), GetPage( name: contactUsScreen, page: () => ContactUsScreen(), bindings: [ ContactUsBinding(), ], ), GetPage( name: privacyPolicyScreen, page: () => PrivacyPolicyScreen(), bindings: [ PrivacyPolicyBinding(), ], ), GetPage( name: myCartScreen, page: () => MyCartScreen(), bindings: [ MyCartBinding(), ], ), GetPage( name: userScreen, page: () => UserScreen(), bindings: [ UserBinding(), ], ), GetPage( name: splashScreen, page: () => SplashScreen(), bindings: [ SplashBinding(), ], ), GetPage( name: termsOfServicesScreen, page: () => TermsOfServicesScreen(), bindings: [ TermsOfServicesBinding(), ], ), GetPage( name: aboutUsScreen, page: () => AboutUsScreen(), bindings: [ AboutUsBinding(), ], ), GetPage( name: appNavigationScreen, page: () => AppNavigationScreen(), bindings: [ AppNavigationBinding(), ], ), GetPage( name: initialRoute, page: () => SplashScreen(), bindings: [ SplashBinding(), ], ), GetPage( name: addNewAddress, page: () => AddNewAddressScreen(), bindings: [ AddNewAddressBinding(), ], ), ]; }
0
mirrored_repositories/DhiBasket/lib
mirrored_repositories/DhiBasket/lib/routes/navigation_args.dart
class NavigationArgs { static String productId = "product_id"; static String categoryId = "category_id"; static String categoryName = 'Fruits'; }
0
mirrored_repositories/DhiBasket/lib/data/models
mirrored_repositories/DhiBasket/lib/data/models/product/get_product_resp.dart
class ProductResp { List<Items>? items; int? count; int? limit; int? offset; int? total; ProductResp({this.items, this.count, this.limit, this.offset, this.total}); ProductResp.fromJson(Map<String, dynamic> json) { if (json['items'] != null) { items = <Items>[]; json['items'].forEach((v) { items?.add(Items.fromJson(v)); }); } count = json['count']; limit = json['limit']; offset = json['offset']; total = json['total']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = {}; if (this.items != null) { data['items'] = this.items?.map((v) => v.toJson()).toList(); } if (this.count != null) { data['count'] = this.count; } if (this.limit != null) { data['limit'] = this.limit; } if (this.offset != null) { data['offset'] = this.offset; } if (this.total != null) { data['total'] = this.total; } return data; } } class Items { bool? bArchived; bool? bDraft; String? price; String? weight; String? name; Image? image; String? slug; String? categoryid; String? updatedOn; String? updatedBy; String? createdOn; String? createdBy; Null publishedOn; Null publishedBy; String? sCid; String? sId; String? description; Items( {this.bArchived, this.bDraft, this.price, this.weight, this.name, this.image, this.slug, this.categoryid, this.updatedOn, this.updatedBy, this.createdOn, this.createdBy, this.publishedOn, this.publishedBy, this.sCid, this.sId, this.description}); Items.fromJson(Map<String, dynamic> json) { bArchived = json['_archived']; bDraft = json['_draft']; price = json['price']; weight = json['weight']; name = json['name']; image = json['image'] != null ? Image.fromJson(json['image']) : null; slug = json['slug']; categoryid = json['categoryid']; updatedOn = json['updated-on']; updatedBy = json['updated-by']; createdOn = json['created-on']; createdBy = json['created-by']; publishedOn = json['published-on']; publishedBy = json['published-by']; sCid = json['_cid']; sId = json['_id']; description = json['description']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = {}; if (this.bArchived != null) { data['_archived'] = this.bArchived; } if (this.bDraft != null) { data['_draft'] = this.bDraft; } if (this.price != null) { data['price'] = this.price; } if (this.weight != null) { data['weight'] = this.weight; } if (this.name != null) { data['name'] = this.name; } if (this.image != null) { data['image'] = this.image?.toJson(); } if (this.slug != null) { data['slug'] = this.slug; } if (this.categoryid != null) { data['categoryid'] = this.categoryid; } if (this.updatedOn != null) { data['updated-on'] = this.updatedOn; } if (this.updatedBy != null) { data['updated-by'] = this.updatedBy; } if (this.createdOn != null) { data['created-on'] = this.createdOn; } if (this.createdBy != null) { data['created-by'] = this.createdBy; } if (this.publishedOn != null) { data['published-on'] = this.publishedOn; } if (this.publishedBy != null) { data['published-by'] = this.publishedBy; } if (this.sCid != null) { data['_cid'] = this.sCid; } if (this.sId != null) { data['_id'] = this.sId; } if (this.description != null) { data['description'] = this.description; } return data; } } class Image { String? fileId; String? url; Null alt; Image({this.fileId, this.url, this.alt}); Image.fromJson(Map<String, dynamic> json) { fileId = json['fileId']; url = json['url']; alt = json['alt']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = {}; if (this.fileId != null) { data['fileId'] = this.fileId; } if (this.url != null) { data['url'] = this.url; } if (this.alt != null) { data['alt'] = this.alt; } return data; } }
0
mirrored_repositories/DhiBasket/lib/data/models
mirrored_repositories/DhiBasket/lib/data/models/ItemId/get_item_id_resp.dart
class GetItemIdResp { List<Items>? items; int? count; int? limit; int? offset; int? total; GetItemIdResp({this.items, this.count, this.limit, this.offset, this.total}); GetItemIdResp.fromJson(Map<String, dynamic> json) { if (json['items'] != null) { items = <Items>[]; json['items'].forEach((v) { items?.add(Items.fromJson(v)); }); } count = json['count']; limit = json['limit']; offset = json['offset']; total = json['total']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = {}; if (this.items != null) { data['items'] = this.items?.map((v) => v.toJson()).toList(); } if (this.count != null) { data['count'] = this.count; } if (this.limit != null) { data['limit'] = this.limit; } if (this.offset != null) { data['offset'] = this.offset; } if (this.total != null) { data['total'] = this.total; } return data; } } class Items { bool? bArchived; bool? bDraft; String? email; String? name; String? userid; String? contact; String? slug; String? updatedOn; String? updatedBy; String? createdOn; String? createdBy; String? publishedOn; String? publishedBy; String? sCid; String? sId; Items( {this.bArchived, this.bDraft, this.email, this.name, this.userid, this.contact, this.slug, this.updatedOn, this.updatedBy, this.createdOn, this.createdBy, this.publishedOn, this.publishedBy, this.sCid, this.sId}); Items.fromJson(Map<String, dynamic> json) { bArchived = json['_archived']; bDraft = json['_draft']; email = json['email']; name = json['name']; userid = json['userid']; contact = json['contact']; slug = json['slug']; updatedOn = json['updated-on']; updatedBy = json['updated-by']; createdOn = json['created-on']; createdBy = json['created-by']; publishedOn = json['published-on']; publishedBy = json['published-by']; sCid = json['_cid']; sId = json['_id']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = {}; if (this.bArchived != null) { data['_archived'] = this.bArchived; } if (this.bDraft != null) { data['_draft'] = this.bDraft; } if (this.email != null) { data['email'] = this.email; } if (this.name != null) { data['name'] = this.name; } if (this.userid != null) { data['userid'] = this.userid; } if (this.contact != null) { data['contact'] = this.contact; } if (this.slug != null) { data['slug'] = this.slug; } if (this.updatedOn != null) { data['updated-on'] = this.updatedOn; } if (this.updatedBy != null) { data['updated-by'] = this.updatedBy; } if (this.createdOn != null) { data['created-on'] = this.createdOn; } if (this.createdBy != null) { data['created-by'] = this.createdBy; } if (this.publishedOn != null) { data['published-on'] = this.publishedOn; } if (this.publishedBy != null) { data['published-by'] = this.publishedBy; } if (this.sCid != null) { data['_cid'] = this.sCid; } if (this.sId != null) { data['_id'] = this.sId; } return data; } }
0
mirrored_repositories/DhiBasket/lib/data/models
mirrored_repositories/DhiBasket/lib/data/models/items/post_items_resp.dart
class PostItemsResp { String? email; bool? bArchived; bool? bDraft; String? name; String? userid; String? contact; String? slug; String? updatedOn; String? updatedBy; String? createdOn; String? createdBy; String? publishedOn; String? publishedBy; String? sCid; String? sId; PostItemsResp( {this.email, this.bArchived, this.bDraft, this.name, this.userid, this.contact, this.slug, this.updatedOn, this.updatedBy, this.createdOn, this.createdBy, this.publishedOn, this.publishedBy, this.sCid, this.sId}); PostItemsResp.fromJson(Map<String, dynamic> json) { email = json['email']; bArchived = json['_archived']; bDraft = json['_draft']; name = json['name']; userid = json['userid']; contact = json['contact']; slug = json['slug']; updatedOn = json['updated-on']; updatedBy = json['updated-by']; createdOn = json['created-on']; createdBy = json['created-by']; publishedOn = json['published-on']; publishedBy = json['published-by']; sCid = json['_cid']; sId = json['_id']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = {}; if (this.email != null) { data['email'] = this.email; } if (this.bArchived != null) { data['_archived'] = this.bArchived; } if (this.bDraft != null) { data['_draft'] = this.bDraft; } if (this.name != null) { data['name'] = this.name; } if (this.userid != null) { data['userid'] = this.userid; } if (this.contact != null) { data['contact'] = this.contact; } if (this.slug != null) { data['slug'] = this.slug; } if (this.updatedOn != null) { data['updated-on'] = this.updatedOn; } if (this.updatedBy != null) { data['updated-by'] = this.updatedBy; } if (this.createdOn != null) { data['created-on'] = this.createdOn; } if (this.createdBy != null) { data['created-by'] = this.createdBy; } if (this.publishedOn != null) { data['published-on'] = this.publishedOn; } if (this.publishedBy != null) { data['published-by'] = this.publishedBy; } if (this.sCid != null) { data['_cid'] = this.sCid; } if (this.sId != null) { data['_id'] = this.sId; } return data; } }
0
mirrored_repositories/DhiBasket/lib/data/models
mirrored_repositories/DhiBasket/lib/data/models/items/post_items_req.dart
class PostItemsReq { Fields? fields; PostItemsReq({this.fields}); PostItemsReq.fromJson(Map<String, dynamic> json) { fields = json['fields'] != null ? Fields.fromJson(json['fields']) : null; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = {}; if (this.fields != null) { data['fields'] = this.fields?.toJson(); } return data; } } class Fields { String? name; String? slug; bool? bArchived; bool? bDraft; String? productid; String? email; String? userid; String? contact; String? city; String? state; String? country; String? area; int? pincode; String? landmark; String? type; Fields( {this.name, this.slug, this.bArchived, this.bDraft, this.productid, this.email, this.contact, this.userid, this.city, this.state, this.country, this.area, this.pincode, this.landmark, this.type}); Fields.fromJson(Map<String, dynamic> json) { name = json['name']; slug = json['slug']; bArchived = json['_archived']; bDraft = json['_draft']; productid = json['productid']; email = json['email']; contact = json['contact']; userid = json['userid']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = {}; if (this.name != null) { data['name'] = this.name; } if (this.slug != null) { data['slug'] = this.slug; } if (this.bArchived != null) { data['_archived'] = this.bArchived; } if (this.bDraft != null) { data['_draft'] = this.bDraft; } if (this.productid != null) { data['productid'] = this.productid; } if (this.email != null) { data['email'] = this.email; } if (this.userid != null) { data['userid'] = this.userid; } if (this.contact != null) { data['contact'] = this.contact; } return data; } }
0
mirrored_repositories/DhiBasket/lib/data/models
mirrored_repositories/DhiBasket/lib/data/models/items/get_fruits_resp.dart
class GetFruitsResp { List<Items>? items; int? count; int? limit; int? offset; int? total; GetFruitsResp({this.items, this.count, this.limit, this.offset, this.total}); GetFruitsResp.fromJson(Map<String, dynamic> json) { if (json['items'] != null) { items = <Items>[]; json['items'].forEach((v) { items?.add(Items.fromJson(v)); }); } count = json['count']; limit = json['limit']; offset = json['offset']; total = json['total']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = {}; if (this.items != null) { data['items'] = this.items?.map((v) => v.toJson()).toList(); } if (this.count != null) { data['count'] = this.count; } if (this.limit != null) { data['limit'] = this.limit; } if (this.offset != null) { data['offset'] = this.offset; } if (this.total != null) { data['total'] = this.total; } return data; } } class Items { bool? bArchived; bool? bDraft; String? price; String? name; Image? image; String? slug; String? updatedOn; String? updatedBy; String? createdOn; String? createdBy; Null publishedOn; Null publishedBy; String? weight; String? sCid; String? sId; String? categoryid; Items( {this.bArchived, this.bDraft, this.price, this.name, this.image, this.slug, this.updatedOn, this.updatedBy, this.createdOn, this.createdBy, this.publishedOn, this.publishedBy, this.weight, this.sCid, this.sId, this.categoryid}); Items.fromJson(Map<String, dynamic> json) { bArchived = json['_archived']; bDraft = json['_draft']; price = json['price']; name = json['name']; image = json['image'] != null ? Image.fromJson(json['image']) : null; slug = json['slug']; updatedOn = json['updated-on']; updatedBy = json['updated-by']; createdOn = json['created-on']; createdBy = json['created-by']; publishedOn = json['published-on']; publishedBy = json['published-by']; weight = json['weight']; sCid = json['_cid']; sId = json['_id']; categoryid = json['categoryid']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = {}; if (this.bArchived != null) { data['_archived'] = this.bArchived; } if (this.bDraft != null) { data['_draft'] = this.bDraft; } if (this.price != null) { data['price'] = this.price; } if (this.name != null) { data['name'] = this.name; } if (this.image != null) { data['image'] = this.image?.toJson(); } if (this.slug != null) { data['slug'] = this.slug; } if (this.updatedOn != null) { data['updated-on'] = this.updatedOn; } if (this.updatedBy != null) { data['updated-by'] = this.updatedBy; } if (this.createdOn != null) { data['created-on'] = this.createdOn; } if (this.createdBy != null) { data['created-by'] = this.createdBy; } if (this.publishedBy != null) { data['published-by'] = this.publishedBy; } if (this.weight != null) { data['weight'] = this.weight; } if (this.sCid != null) { data['_cid'] = this.sCid; } if (this.sId != null) { data['_id'] = this.sId; } if (this.categoryid != null) { data['categoryid'] = this.categoryid; } return data; } } class Image { String? fileId; String? url; Null alt; Image({this.fileId, this.url, this.alt}); Image.fromJson(Map<String, dynamic> json) { fileId = json['fileId']; url = json['url']; alt = json['alt']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = {}; if (this.fileId != null) { data['fileId'] = this.fileId; } if (this.url != null) { data['url'] = this.url; } if (this.alt != null) { data['alt'] = this.alt; } return data; } }
0
mirrored_repositories/DhiBasket/lib/data/models
mirrored_repositories/DhiBasket/lib/data/models/items/get_category_resp.dart
class GetCategoryResp { List<Items>? items; int? count; int? limit; int? offset; int? total; GetCategoryResp( {this.items, this.count, this.limit, this.offset, this.total}); GetCategoryResp.fromJson(Map<String, dynamic> json) { if (json['items'] != null) { items = <Items>[]; json['items'].forEach((v) { items?.add(Items.fromJson(v)); }); } count = json['count']; limit = json['limit']; offset = json['offset']; total = json['total']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = {}; if (this.items != null) { data['items'] = this.items?.map((v) => v.toJson()).toList(); } if (this.count != null) { data['count'] = this.count; } if (this.limit != null) { data['limit'] = this.limit; } if (this.offset != null) { data['offset'] = this.offset; } if (this.total != null) { data['total'] = this.total; } return data; } } class Items { String? color; bool? bArchived; bool? bDraft; String? description; String? name; Icon? icon; String? slug; String? updatedOn; String? updatedBy; String? createdOn; String? createdBy; Null publishedOn; Null publishedBy; String? sCid; String? sId; Items( {this.color, this.bArchived, this.bDraft, this.description, this.name, this.icon, this.slug, this.updatedOn, this.updatedBy, this.createdOn, this.createdBy, this.publishedOn, this.publishedBy, this.sCid, this.sId}); Items.fromJson(Map<String, dynamic> json) { color = json['color']; bArchived = json['_archived']; bDraft = json['_draft']; description = json['description']; name = json['name']; icon = json['icon'] != null ? Icon.fromJson(json['icon']) : null; slug = json['slug']; updatedOn = json['updated-on']; updatedBy = json['updated-by']; createdOn = json['created-on']; createdBy = json['created-by']; publishedOn = json['published-on']; publishedBy = json['published-by']; sCid = json['_cid']; sId = json['_id']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = {}; if (this.color != null) { data['color'] = this.color; } if (this.bArchived != null) { data['_archived'] = this.bArchived; } if (this.bDraft != null) { data['_draft'] = this.bDraft; } if (this.description != null) { data['description'] = this.description; } if (this.name != null) { data['name'] = this.name; } if (this.icon != null) { data['icon'] = this.icon?.toJson(); } if (this.slug != null) { data['slug'] = this.slug; } if (this.updatedOn != null) { data['updated-on'] = this.updatedOn; } if (this.updatedBy != null) { data['updated-by'] = this.updatedBy; } if (this.createdOn != null) { data['created-on'] = this.createdOn; } if (this.createdBy != null) { data['created-by'] = this.createdBy; } if (this.publishedOn != null) { data['published-on'] = this.publishedOn; } if (this.publishedBy != null) { data['published-by'] = this.publishedBy; } if (this.sCid != null) { data['_cid'] = this.sCid; } if (this.sId != null) { data['_id'] = this.sId; } return data; } } class Icon { String? fileId; String? url; Null alt; Icon({this.fileId, this.url, this.alt}); Icon.fromJson(Map<String, dynamic> json) { fileId = json['fileId']; url = json['url']; alt = json['alt']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = {}; if (this.fileId != null) { data['fileId'] = this.fileId; } if (this.url != null) { data['url'] = this.url; } if (this.alt != null) { data['alt'] = this.alt; } return data; } }
0
mirrored_repositories/DhiBasket/lib/data/models
mirrored_repositories/DhiBasket/lib/data/models/items/get_items_resp.dart
class GetItemsResp { List<Items>? items; int? count; int? limit; int? offset; int? total; GetItemsResp({this.items, this.count, this.limit, this.offset, this.total}); GetItemsResp.fromJson(Map<String, dynamic> json) { if (json['items'] != null) { items = <Items>[]; json['items'].forEach((v) { items?.add(Items.fromJson(v)); }); } count = json['count']; limit = json['limit']; offset = json['offset']; total = json['total']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = {}; if (this.items != null) { data['items'] = this.items?.map((v) => v.toJson()).toList(); } if (this.count != null) { data['count'] = this.count; } if (this.limit != null) { data['limit'] = this.limit; } if (this.offset != null) { data['offset'] = this.offset; } if (this.total != null) { data['total'] = this.total; } return data; } } class Items { bool? bArchived; bool? bDraft; String? price; String? name; Image? image; String? slug; String? updatedOn; String? updatedBy; String? createdOn; String? createdBy; Null publishedOn; Null publishedBy; String? weight; String? sCid; String? sId; String? userid; String? city; String? state; String? country; String? area; int? pincode; String? landmark; String? type; Items( {this.bArchived, this.bDraft, this.price, this.name, this.image, this.slug, this.updatedOn, this.updatedBy, this.createdOn, this.createdBy, this.publishedOn, this.publishedBy, this.weight, this.sCid, this.sId, this.userid, this.city, this.state, this.country, this.area, this.pincode, this.landmark, this.type}); Items.fromJson(Map<String, dynamic> json) { bArchived = json['_archived']; bDraft = json['_draft']; price = json['price']; name = json['name']; image = json['image'] != null ? Image.fromJson(json['image']) : null; slug = json['slug']; updatedOn = json['updated-on']; updatedBy = json['updated-by']; createdOn = json['created-on']; createdBy = json['created-by']; publishedOn = json['published-on']; publishedBy = json['published-by']; weight = json['weight']; sCid = json['_cid']; sId = json['_id']; city = json['city']; state = json['state']; userid = json['userid']; pincode = json['pincode']; landmark = json['landmark']; country = json['country']; area = json['area']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = {}; if (this.bArchived != null) { data['_archived'] = this.bArchived; } if (this.bDraft != null) { data['_draft'] = this.bDraft; } if (this.price != null) { data['price'] = this.price; } if (this.name != null) { data['name'] = this.name; } if (this.image != null) { data['image'] = this.image?.toJson(); } if (this.slug != null) { data['slug'] = this.slug; } if (this.updatedOn != null) { data['updated-on'] = this.updatedOn; } if (this.updatedBy != null) { data['updated-by'] = this.updatedBy; } if (this.createdOn != null) { data['created-on'] = this.createdOn; } if (this.createdBy != null) { data['created-by'] = this.createdBy; } if (this.publishedOn != null) { data['published-on'] = this.publishedOn; } if (this.publishedBy != null) { data['published-by'] = this.publishedBy; } if (this.weight != null) { data['weight'] = this.weight; } if (this.sCid != null) { data['_cid'] = this.sCid; } if (this.sId != null) { data['_id'] = this.sId; } return data; } } class Image { String? fileId; String? url; Null alt; Image({this.fileId, this.url, this.alt}); Image.fromJson(Map<String, dynamic> json) { fileId = json['fileId']; url = json['url']; alt = json['alt']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = {}; if (this.fileId != null) { data['fileId'] = this.fileId; } if (this.url != null) { data['url'] = this.url; } if (this.alt != null) { data['alt'] = this.alt; } return data; } }
0
mirrored_repositories/DhiBasket/lib/data/models
mirrored_repositories/DhiBasket/lib/data/models/itemId/get_item_id_resp.dart
class GetItemIdResp { List<Items>? items; int? count; int? limit; int? offset; int? total; GetItemIdResp({this.items, this.count, this.limit, this.offset, this.total}); GetItemIdResp.fromJson(Map<String, dynamic> json) { if (json['items'] != null) { items = <Items>[]; json['items'].forEach((v) { items?.add(Items.fromJson(v)); }); } count = json['count']; limit = json['limit']; offset = json['offset']; total = json['total']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = {}; if (this.items != null) { data['items'] = this.items?.map((v) => v.toJson()).toList(); } if (this.count != null) { data['count'] = this.count; } if (this.limit != null) { data['limit'] = this.limit; } if (this.offset != null) { data['offset'] = this.offset; } if (this.total != null) { data['total'] = this.total; } return data; } } class Items { bool? bArchived; bool? bDraft; String? email; String? name; String? userid; String? contact; String? slug; String? updatedOn; String? updatedBy; String? createdOn; String? createdBy; Null publishedOn; Null publishedBy; String? sCid; String? sId; Items( {this.bArchived, this.bDraft, this.email, this.name, this.userid, this.contact, this.slug, this.updatedOn, this.updatedBy, this.createdOn, this.createdBy, this.publishedOn, this.publishedBy, this.sCid, this.sId}); Items.fromJson(Map<String, dynamic> json) { bArchived = json['_archived']; bDraft = json['_draft']; email = json['email']; name = json['name']; userid = json['userid']; contact = json['contact']; slug = json['slug']; updatedOn = json['updated-on']; updatedBy = json['updated-by']; createdOn = json['created-on']; createdBy = json['created-by']; publishedOn = json['published-on']; publishedBy = json['published-by']; sCid = json['_cid']; sId = json['_id']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = {}; if (this.bArchived != null) { data['_archived'] = this.bArchived; } if (this.bDraft != null) { data['_draft'] = this.bDraft; } if (this.email != null) { data['email'] = this.email; } if (this.name != null) { data['name'] = this.name; } if (this.userid != null) { data['userid'] = this.userid; } if (this.contact != null) { data['contact'] = this.contact; } if (this.slug != null) { data['slug'] = this.slug; } if (this.updatedOn != null) { data['updated-on'] = this.updatedOn; } if (this.updatedBy != null) { data['updated-by'] = this.updatedBy; } if (this.createdOn != null) { data['created-on'] = this.createdOn; } if (this.createdBy != null) { data['created-by'] = this.createdBy; } if (this.publishedOn != null) { data['published-on'] = this.publishedOn; } if (this.publishedBy != null) { data['published-by'] = this.publishedBy; } if (this.sCid != null) { data['_cid'] = this.sCid; } if (this.sId != null) { data['_id'] = this.sId; } return data; } }
0
mirrored_repositories/DhiBasket/lib/data/models
mirrored_repositories/DhiBasket/lib/data/models/selectionPopupModel/selection_popup_model.dart
///SelectionPopupModel is common model ///used for setting data into dropdowns class SelectionPopupModel { int? id; String title; dynamic value; bool isSelected; SelectionPopupModel({ this.id, required this.title, this.value, this.isSelected = false, }); }
0
mirrored_repositories/DhiBasket/lib/data
mirrored_repositories/DhiBasket/lib/data/apiClient/api_client.dart
import 'package:grocery_app/core/app_export.dart'; import 'package:grocery_app/core/utils/progress_dialog_utils.dart'; class ApiClient extends GetConnect { var baseUrl = "https://api.webflow.com"; @override void onInit() { super.onInit(); httpClient.timeout = Duration(seconds: 60); httpClient.addRequestModifier<dynamic>((request) { Map<String, String> headers = { "accept-version": "1.0.0", "Authorization": "Bearer ${ApiData().token}" }; request.headers.addAll(headers); return request; }); } /// is `true` when the response status code is between 200 and 299 bool _isSuccessCall(Response response) { return response.isOk; } ///method can be used for checking internet connection ///returns [bool] based on availability of internet Future isNetworkConnected() async { if (!await Get.find<NetworkInfo>().isConnected()) { throw NoInternetException('No Internet Found!'); } } Future fetchCategories( {Function(dynamic data)? onSuccess, Function(dynamic error)? onError}) async { ProgressDialogUtils.showProgressDialog(); try { await isNetworkConnected(); Response response = await httpClient .get('/collections/${ApiData().CategoryCollectionId}/items'); ProgressDialogUtils.hideProgressDialog(); if (_isSuccessCall(response)) { onSuccess!(response.body); } else { onError!( response.hasError ? response.statusText : 'Something Went Wrong!', ); } } catch (error) { ProgressDialogUtils.hideProgressDialog(); onError!(error); } } Future fetchProducts( {Function(dynamic data)? onSuccess, Function(dynamic error)? onError, id}) async { ProgressDialogUtils.showProgressDialog(); try { await isNetworkConnected(); Response response = await httpClient .get('/collections/${ApiData().ProductCollectionId}/items'); ProgressDialogUtils.hideProgressDialog(); if (_isSuccessCall(response)) { List<dynamic> items = response.body['items']; items = items .where((element) => element['categoryid'] == id.toString()) .toList(); response.body['items'] = items; onSuccess!(response.body); } else { onError!( response.hasError ? response.statusText : 'Something Went Wrong!', ); } } catch (error) { ProgressDialogUtils.hideProgressDialog(); onError!(error); } } Future fetchProduct( {Function(dynamic data)? onSuccess, Function(dynamic error)? onError, id}) async { ProgressDialogUtils.showProgressDialog(); try { await isNetworkConnected(); Response response = await httpClient.get( '/collections/${ApiData().ProductCollectionId}/items/${id.value}'); ProgressDialogUtils.hideProgressDialog(); if (_isSuccessCall(response)) { onSuccess!(response.body); } else { onError!( response.hasError ? response.statusText : 'Something Went Wrong!', ); } } catch (error) { ProgressDialogUtils.hideProgressDialog(); onError!(error); } } Future createItems( {Function(dynamic data)? onSuccess, Function(dynamic error)? onError, Map requestData = const {}}) async { ProgressDialogUtils.showProgressDialog(); try { await isNetworkConnected(); Response response = await httpClient.post( '/collections/${ApiData().WishListCollectionId}/items', body: requestData); ProgressDialogUtils.hideProgressDialog(); if (_isSuccessCall(response)) { onSuccess!(response.body); } else { onError!( response.hasError ? response.statusText : 'Something Went Wrong!', ); } } catch (error) { ProgressDialogUtils.hideProgressDialog(); onError!(error); } } Future createUser( {Function(dynamic data)? onSuccess, Function(dynamic error)? onError, Map requestData = const {}}) async { ProgressDialogUtils.showProgressDialog(); try { await isNetworkConnected(); Response response = await httpClient.post( '/collections/${ApiData().UserCollectionId}/items', body: requestData); ProgressDialogUtils.hideProgressDialog(); if (_isSuccessCall(response)) { onSuccess!(response.body); } else { onError!( response.hasError ? response.statusText : 'Something Went Wrong!', ); } } catch (error) { ProgressDialogUtils.hideProgressDialog(); onError!(error); } } Future fetchUser( {Function(dynamic data)? onSuccess, Function(dynamic error)? onError, String? item_id = ''}) async { ProgressDialogUtils.showProgressDialog(); try { await isNetworkConnected(); Response response = await httpClient .get('/collections/${ApiData().UserCollectionId}/items/'); ProgressDialogUtils.hideProgressDialog(); if (_isSuccessCall(response)) { List<dynamic> items = response.body['items']; items = items .where((element) => element['userid'] == item_id.toString()) .toList(); response.body['items'] = items; onSuccess!(response.body); } else { onError!( response.hasError ? response.statusText : 'Something Went Wrong!', ); } } catch (error) { ProgressDialogUtils.hideProgressDialog(); onError!(error); } } Future createAddress( {Function(dynamic data)? onSuccess, Function(dynamic error)? onError, Map requestData = const {}}) async { ProgressDialogUtils.showProgressDialog(); try { await isNetworkConnected(); Response response = await httpClient.post( '/collections/${ApiData().AddressCollectionId}/items', body: requestData); ProgressDialogUtils.hideProgressDialog(); if (_isSuccessCall(response)) { onSuccess!(response.body); } else { onError!( response.hasError ? response.statusText : 'Something Went Wrong!', ); } } catch (error) { ProgressDialogUtils.hideProgressDialog(); onError!(error); } } Future fetchAddress( {Function(dynamic data)? onSuccess, Function(dynamic error)? onError, Map requestData = const {}}) async { ProgressDialogUtils.showProgressDialog(); try { await isNetworkConnected(); Response response = await httpClient .get('/collections/${ApiData().AddressCollectionId}/items'); ProgressDialogUtils.hideProgressDialog(); if (_isSuccessCall(response)) { List items = response.body['items']; items = items .where((element) => element['userid'] == Get.find<PrefUtils>().getUserid()) .toList(); response.body['items'] = items; onSuccess!(response.body); } else { onError!( response.hasError ? response.statusText : 'Something Went Wrong!', ); } } catch (error) { ProgressDialogUtils.hideProgressDialog(); onError!(error); } } Future fetchWishlist( {Function(dynamic data)? onSuccess, Function(dynamic error)? onError, Map requestData = const {}}) async { ProgressDialogUtils.showProgressDialog(); try { await isNetworkConnected(); Response response = await httpClient .get('/collections/${ApiData().WishListCollectionId}/items'); ProgressDialogUtils.hideProgressDialog(); if (_isSuccessCall(response)) { List items = response.body['items']; // items = items // .where((element) => // element['userid'] == Get.find<PrefUtils>().getUserid()) // .toList(); response.body['items'] = items; onSuccess!(response.body); } else { onError!( response.hasError ? response.statusText : 'Something Went Wrong!', ); } } catch (error) { ProgressDialogUtils.hideProgressDialog(); onError!(error); } } }
0
mirrored_repositories/DhiBasket/lib
mirrored_repositories/DhiBasket/lib/core/app_export.dart
export 'package:get/get.dart'; export 'package:grocery_app/localization/app_localization.dart'; export 'package:grocery_app/core/constants/constants.dart'; export 'package:grocery_app/core/utils/image_constant.dart'; export 'package:grocery_app/core/utils/color_constant.dart'; export 'package:grocery_app/core/utils/math_utils.dart'; export 'package:grocery_app/core/utils/pref_utils.dart'; export 'package:grocery_app/core/utils/initial_bindings.dart'; export 'package:grocery_app/theme/app_style.dart'; export 'package:grocery_app/theme/app_decoration.dart'; export 'package:connectivity_plus/connectivity_plus.dart'; export 'package:grocery_app/routes/app_routes.dart'; export 'package:grocery_app/data/models/selectionPopupModel/selection_popup_model.dart'; export 'package:grocery_app/widgets/common_image_view.dart'; export 'package:grocery_app/core/errors/exceptions.dart'; export 'package:grocery_app/core/network/network_info.dart'; export 'package:grocery_app/core/utils/permission_manager.dart'; export 'package:permission_handler/permission_handler.dart'; export 'package:grocery_app/core/utils/file_upload_helper.dart';
0
mirrored_repositories/DhiBasket/lib/core
mirrored_repositories/DhiBasket/lib/core/network/network_info.dart
import 'package:connectivity_plus/connectivity_plus.dart'; // For checking internet connectivity abstract class NetworkInfoI { Future<bool> isConnected(); Future<ConnectivityResult> get connectivityResult; Stream<ConnectivityResult> get onConnectivityChanged; } class NetworkInfo implements NetworkInfoI { Connectivity connectivity; NetworkInfo(this.connectivity) { connectivity = this.connectivity; } ///checks internet is connected or not ///returns [true] if internet is connected ///else it will return [false] @override Future<bool> isConnected() async { final result = await connectivity.checkConnectivity(); if (result != ConnectivityResult.none) { return true; } return false; } // to check type of internet connectivity @override Future<ConnectivityResult> get connectivityResult async { return connectivity.checkConnectivity(); } //check the type on internet connection on changed of internet connection @override Stream<ConnectivityResult> get onConnectivityChanged => connectivity.onConnectivityChanged; }
0