repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/flutter_showcase/example/apps/plant_forms
mirrored_repositories/flutter_showcase/example/apps/plant_forms/lib/demo.dart
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'components/header.dart'; import 'components/stack_pages_route.dart'; import 'plant_form_summary.dart'; class PlantFormsDemo extends StatefulWidget { @override _PlantFormsDemoState createState() => _PlantFormsDemoState(); } class SharedFormState { Map<String, String> valuesByName = {}; SharedFormState(); } class _PlantFormsDemoState extends State<PlantFormsDemo> { GlobalKey<NavigatorState> navKey = new GlobalKey(); @override Widget build(BuildContext context) { return Stack( alignment: Alignment.center, children: <Widget>[ Header(), //Use provider to pass down a FormState to each of the form views, this way they can easily share and update the same state object Provider<SharedFormState>( builder: (_) => SharedFormState(), //Use WillPopScope to intercept hardware back taps, and instead pop the nested navigator child: WillPopScope( onWillPop: _handleBackPop, //Use a nested navigator to group the 3 form views under 1 parent view child: Navigator( key: navKey, onGenerateRoute: (route) { return StackPagesRoute(previousPages: [], enterPage: PlantFormSummary()); }, ), ), ), ], ); } Future<bool> _handleBackPop() async { if (navKey.currentState.canPop()) { //If the pop worked, return false, preventing any pops in the MaterialApp's navigator return !navKey.currentState.pop(); } return true; } }
0
mirrored_repositories/flutter_showcase/example/apps/plant_forms
mirrored_repositories/flutter_showcase/example/apps/plant_forms/lib/plant_form_payment.dart
import 'package:flutter/material.dart'; import 'package:plant_forms/demo.dart'; import 'package:provider/provider.dart'; import 'demo_data.dart'; import 'form_inputs/checkbox_input.dart'; import 'form_inputs/credit_card_input.dart'; import 'form_mixin.dart'; import 'form_page.dart'; import 'components/section_separator.dart'; import 'components/section_title.dart'; import 'styles.dart'; import 'components/submit_button.dart'; import 'form_inputs/text_input.dart'; class PlantFormPayment extends StatefulWidget { final double pageSize; const PlantFormPayment({Key key, this.pageSize}) : super(key: key); @override _PlantFormPaymentState createState() => _PlantFormPaymentState(); } class _PlantFormPaymentState extends State<PlantFormPayment> with FormMixin { final _formKey = GlobalKey<FormState>(); CreditCardNetwork _cardNetwork; SharedFormState sharedState; Map<String, String> get values => sharedState.valuesByName; @override void initState() { sharedState = Provider.of<SharedFormState>(context, listen: false); super.initState(); } @override Widget build(BuildContext context) { print("Rebuilding payments @ ${DateTime.now().millisecondsSinceEpoch}"); return FormPage( formKey: _formKey, pageSizeProportion: widget.pageSize ?? 0.85, title: 'Payment', children: [ Text('\$34.00', style: Styles.orderTotal), Separator(), _buildShippingSection(), Separator(), FormSectionTitle('Gift card or discount code'), _buildInputWithButton(), FormSectionTitle('Payment', padding: EdgeInsets.only(bottom: 16)), CreditCardInfoInput( key: ValueKey(FormKeys.ccNumber), label: 'Card Number', helper: '4111 2222 3333 4440', cardNetwork: _cardNetwork, onValidate: onItemValidate, onChange: _handleItemChange, inputType: CreditCardInputType.number, ), TextInput( key: ValueKey(FormKeys.ccName), label: 'Card Name', helper: 'Cardholder Name', onValidate: onItemValidate), Row( children: <Widget>[ Expanded( child: CreditCardInfoInput( key: ValueKey(FormKeys.ccExpDate), label: 'Expiration', helper: 'MM/YY', onValidate: onItemValidate, inputType: CreditCardInputType.expirationDate, )), SizedBox(width: 24), Expanded( child: CreditCardInfoInput( key: ValueKey(FormKeys.ccCode), cardNetwork: _cardNetwork, label: 'Security Code', helper: '000', onValidate: onItemValidate, inputType: CreditCardInputType.securityCode), ), ], ), FormSectionTitle('Shipping Notifications'), CheckBoxInput(label: 'Send shipping updates via email'), _buildSubmitButton() ], ); } @override void onItemValidate(String key, bool isValid, {String value}) { validInputsMap[key] = isValid; values[key] = value; Future.delayed( Duration(milliseconds: 500), () { if (this.mounted) setState(() { formCompletion = super.countValidItems() / validInputsMap.length; if (formCompletion == 1) isFormErrorVisible = false; }); }, ); } Widget _buildShippingSection() { return Column(children: <Widget>[ Row( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Container(constraints: BoxConstraints(minWidth: 85), child: Text('Contact', style: Styles.orderLabel)), Text(values[FormKeys.email], overflow: TextOverflow.clip, style: Styles.orderPrice), ], ), Padding( padding: const EdgeInsets.symmetric(vertical: 12.0), child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Container(constraints: BoxConstraints(minWidth: 85), child: Text('Ship to', style: Styles.orderLabel)), Text(_getShippingAddress(), overflow: TextOverflow.clip, style: Styles.orderPrice), ], ), ), Row( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Container(constraints: BoxConstraints(minWidth: 85), child: Text('Method', style: Styles.orderLabel)), Text('FREE', overflow: TextOverflow.clip, style: Styles.orderPrice), ], ) ]); } String _getShippingAddress() { String aptNumber = values[FormKeys.apt].isNotEmpty ? '#${values[FormKeys.apt]} ' : ''; String address = values[FormKeys.address]; String country = values[FormKeys.country]; String city = values[FormKeys.city]; String countrySubdivision = values[CountryData.getSubdivisionTitle(country)] ?? ''; String postalCode = values[FormKeys.postal]; return '$aptNumber$address\n$city, $countrySubdivision ${postalCode.toUpperCase()}\n${country.toUpperCase()}'; } Widget _buildInputWithButton() { return Row( children: <Widget>[ Expanded( flex: 4, child: TextInput( helper: '000 000 000 XX', type: InputType.number, onValidate: onItemValidate, isRequired: false, isActive: false, )), Expanded( flex: 2, child: Padding( padding: const EdgeInsets.only(bottom: 26.0, left: 12), child: MaterialButton( disabledColor: Styles.lightGrayColor, elevation: 0, color: Styles.secondaryColor, height: 56, child: Text('Apply', style: Styles.submitButtonText), onPressed: null, ), ), ) ], ); } Widget _buildSubmitButton() { return SubmitButton( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 18.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Text('Purchase', style: Styles.submitButtonText), Text('\$34', style: Styles.submitButtonText), ], ), ), percentage: formCompletion, isErrorVisible: isFormErrorVisible, onPressed: _handleSubmit, ); } void _handleSubmit() { if (_formKey.currentState.validate() && formCompletion == 1) { } else setState(() => isFormErrorVisible = true); } void _handleItemChange(CreditCardNetwork cardNetwork) { setState(() => _cardNetwork = cardNetwork); } @override void onItemChange(String name, String value) => values[name] = value; }
0
mirrored_repositories/flutter_showcase/example/apps/plant_forms/lib
mirrored_repositories/flutter_showcase/example/apps/plant_forms/lib/components/section_title.dart
import 'package:flutter/material.dart'; import '../styles.dart'; class FormSectionTitle extends StatelessWidget { final String title; final EdgeInsets padding; const FormSectionTitle(this.title, {this.padding = const EdgeInsets.all(0), Key key}) : super(key: key); @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.only(bottom: 10.0).add(padding), child: Text(title.toUpperCase(), style: Styles.formSection), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/plant_forms/lib
mirrored_repositories/flutter_showcase/example/apps/plant_forms/lib/components/section_separator.dart
import 'package:flutter/material.dart'; import '../styles.dart'; class Separator extends StatelessWidget { @override Widget build(BuildContext context) { return Container( margin: EdgeInsets.symmetric(vertical: 24.0), color: Styles.lightGrayColor, height: 1, ); } }
0
mirrored_repositories/flutter_showcase/example/apps/plant_forms/lib
mirrored_repositories/flutter_showcase/example/apps/plant_forms/lib/components/submit_button.dart
import 'package:flutter/material.dart'; import '../styles.dart'; class SubmitButton extends StatelessWidget { final double percentage; final Widget child; final Function onPressed; final bool isErrorVisible; final EdgeInsets padding; const SubmitButton({ Key key, @required this.onPressed, @required this.child, this.percentage = 1, this.isErrorVisible = false, this.padding = const EdgeInsets.all(0), }) : super(key: key); @override Widget build(BuildContext context) { return Container( margin: EdgeInsets.symmetric(vertical: Styles.vtFormPadding).add(padding), child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ RawMaterialButton( shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4)), elevation: 0, child: Stack( alignment: Alignment.center, children: <Widget>[ Align( alignment: Alignment.centerLeft, child: SizeTransition( sizeFactor: Tween<double>(begin: 0, end: 1) .animate(AlwaysStoppedAnimation(percentage.isNaN ? 0 : percentage)), axisAlignment: -1, axis: Axis.horizontal, child: Container( height: 48, decoration: BoxDecoration(color: Styles.secondaryColor, borderRadius: BorderRadius.circular(4)), ), ), ), child, ], ), fillColor: Styles.primaryColor, onPressed: onPressed, ), if (isErrorVisible) Padding( padding: EdgeInsets.only(top: 6.0), child: Text('You haven’t finished filling out your information', style: Styles.formError)) ], ), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/plant_forms/lib
mirrored_repositories/flutter_showcase/example/apps/plant_forms/lib/components/header.dart
import 'package:flutter/material.dart'; import '../main.dart'; import '../styles.dart'; class Header extends StatelessWidget { @override Widget build(BuildContext context) { Size screenSize = MediaQuery.of(context).size; return Align( alignment: Alignment.topCenter, child: Scaffold( body: Container( height: screenSize.height * .25, width: screenSize.width, decoration: BoxDecoration( image: DecorationImage( image: AssetImage('images/plant_header_background.png', package: App.pkg), fit: BoxFit.cover, colorFilter: ColorFilter.mode(Colors.white60, BlendMode.screen))), child: SafeArea( child: Padding( padding: const EdgeInsets.only(top: 8.0), child: Column( mainAxisSize: MainAxisSize.min, children: <Widget>[ Text('The'.toUpperCase(), style: Styles.appTitle1), Text('Plant Store', style: Styles.appTitle2), ], ), ), ), ), ), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/plant_forms/lib
mirrored_repositories/flutter_showcase/example/apps/plant_forms/lib/components/stack_pages_route.dart
import 'package:flutter/material.dart'; import 'header.dart'; class StackPagesRoute extends PageRouteBuilder { final Widget enterPage; final List<Widget> previousPages; StackPagesRoute({this.previousPages, this.enterPage}) : super( pageBuilder: ( BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, ) => enterPage, transitionsBuilder: ( BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child, ) { return Stack( overflow: Overflow.clip, fit: StackFit.expand, children: <Widget>[ Header(), for (int i = 0; i < previousPages.length; i++) SlideTransition( position: new Tween<Offset>( begin: Offset(0, ((previousPages.length - i) * -0.05) + 0.05), end: Offset(0, (previousPages.length - i) * -0.05), ).animate(CurvedAnimation(curve: Curves.easeInCubic, parent: animation)), child: previousPages[i], ), SlideTransition( position: new Tween<Offset>( begin: const Offset(0, 1.0), end: Offset.zero, ).animate(animation), child: enterPage, ) ], ); }, ); }
0
mirrored_repositories/flutter_showcase/example/apps/plant_forms/lib
mirrored_repositories/flutter_showcase/example/apps/plant_forms/lib/form_inputs/credit_card_input.dart
import 'package:flutter/material.dart'; import 'package:flutter_masked_text/flutter_masked_text.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import '../demo_data.dart'; import 'input_validator.dart'; import '../styles.dart'; class CreditCardInfoInput extends StatefulWidget { final String label; final String helper; final CreditCardInputType inputType; final CreditCardNetwork cardNetwork; final Function onValidate; final Function onChange; const CreditCardInfoInput( {Key key, this.label = '', this.helper = '', this.cardNetwork, @required this.inputType, @required this.onValidate, this.onChange}) : super(key: key); @override _CreditCardInfoInputState createState() => _CreditCardInfoInputState(); } class _CreditCardInfoInputState extends State<CreditCardInfoInput> { MaskedTextController _textController; CreditCardNetwork _creditCardType; bool _isAutoValidating = false; bool _isValid; String _value = ''; String _errorText = ''; String get keyValue => (widget.key as ValueKey).value as String; @override initState() { _textController = MaskedTextController(mask: '00'); super.initState(); } @override dispose() { super.dispose(); } set isValid(bool isValid) { if (isValid != _isValid) { _isValid = isValid; widget.onValidate(keyValue, _isValid, value: _value); } } @override Widget build(BuildContext context) { // set isValid isValid = false; //build input return Container( padding: EdgeInsets.only(top: widget.label.isNotEmpty ? 18 : 0), child: Stack( overflow: Overflow.visible, children: <Widget>[ if (widget.label.isNotEmpty) Positioned(top: -24, child: Text(widget.label, style: Styles.inputLabel)), TextFormField( controller: _textController, style: Styles.orderTotalLabel, onChanged: _handleChange, keyboardType: TextInputType.number, autovalidate: _isAutoValidating, validator: _validateField, decoration: Styles.getInputDecoration(helper: widget.helper), ), Positioned( top: 6, left: 12, child: Text(_getLabel().toUpperCase(), style: Styles.labelOptional), ), if (_errorText.isNotEmpty) Positioned( top: 8, right: 14, child: Text(_errorText.toUpperCase(), style: Styles.labelNotValid), ), if (widget.inputType == CreditCardInputType.number) Positioned(top: 15, right: 18, child: Icon(_getCreditCardIcon(), size: 28, color: Styles.darkGrayColor)) ], ), ); } IconData _getCreditCardIcon() { switch (_creditCardType) { case CreditCardNetwork.visa: return FontAwesomeIcons.ccVisa; case CreditCardNetwork.mastercard: return FontAwesomeIcons.ccMastercard; case CreditCardNetwork.amex: return FontAwesomeIcons.ccAmex; default: return Icons.credit_card; } } String _getLabel() { String label = ''; if (_value.isNotEmpty && widget.label.isEmpty) return widget.helper; return label; } void _handleChange(String value) { _value = value; Future.delayed(Duration(milliseconds: 100), () => setState(() {})); if (value.length == 2) _updateInputMask(); if (!_isAutoValidating) { setState(() { _isAutoValidating = true; }); } } String _validateField(String value) { // if is required if (value.isEmpty) { isValid = false; _errorText = 'Required'; return _errorText; } // validate when the input has a value else if (value.isNotEmpty && InputValidator.validate(widget.inputType, value, cardNetwork: widget.cardNetwork)) { isValid = true; _errorText = ''; return null; } // the value is not valid else { isValid = false; _errorText = 'Not Valid'; return _errorText; } } void _updateInputMask() { switch (widget.inputType) { case CreditCardInputType.number: // Visa if (_value.substring(0, 1).compareTo('4') == 0) { _creditCardType = CreditCardNetwork.visa; _textController.updateMask('0000 0000 0000 0000'); } // AMEX else if (_value.substring(0, 2) == '34' || _value.substring(0, 2) == '37') { _creditCardType = CreditCardNetwork.amex; _textController.updateMask('0000 000000 00000'); } // Mastercard else if (_value.substring(0, 2) == '51' || _value.substring(0, 2) == '52' || _value.substring(0, 2) == '53' || _value.substring(0, 2) == '54' || _value.substring(0, 2) == '55') { _creditCardType = CreditCardNetwork.mastercard; _textController.updateMask('0000 0000 0000 0000'); } else _creditCardType = null; break; case CreditCardInputType.expirationDate: _textController.updateMask('00/00'); _textController.beforeChange = (String previous, String next) { return next.length <= 5; }; break; case CreditCardInputType.securityCode: if (widget.cardNetwork == CreditCardNetwork.amex) _textController.updateMask('0000'); else _textController.updateMask('000'); break; } widget.onChange(_creditCardType); } }
0
mirrored_repositories/flutter_showcase/example/apps/plant_forms/lib
mirrored_repositories/flutter_showcase/example/apps/plant_forms/lib/form_inputs/dropdown_menu.dart
import 'package:flutter/material.dart'; import '../styles.dart'; class DropdownMenu extends StatefulWidget { final Function onValidate; final String label; final String defaultOption; final List<String> options; const DropdownMenu( {Key key, @required this.options, this.label, this.onValidate, this.defaultOption}) : super(key: key); @override _DropdownMenuState createState() => _DropdownMenuState(); } class _DropdownMenuState extends State<DropdownMenu> { String _selectedOption; bool _isValid; String get _keyValue => (widget.key as ValueKey).value as String; set isValid(bool isValid) { _isValid = isValid; widget.onValidate(_keyValue, _isValid, value: _selectedOption); } @override initState() { super.initState(); _selectedOption = widget.defaultOption ?? ""; } @override Widget build(BuildContext context) { if(_isValid == null && _selectedOption.isNotEmpty){ isValid = true; } var items = _buildMenuItems(); //items.forEach((i)=>print("----> ${i.value}")); return Stack( alignment: Alignment.topCenter, children: <Widget>[ DropdownButtonFormField( key: UniqueKey(), onChanged: (val){}, value: _selectedOption, items: items, validator: _validate, decoration: InputDecoration( contentPadding: EdgeInsets.symmetric(vertical: 8, horizontal: 12), focusedBorder: OutlineInputBorder(borderSide: BorderSide(color: Styles.secondaryColor)), errorBorder: OutlineInputBorder(borderSide: BorderSide(color: Styles.errorColor)), enabledBorder: OutlineInputBorder(borderSide: BorderSide(color: Styles.lightGrayColor)), border: OutlineInputBorder(), errorStyle: TextStyle(color: Colors.transparent), helperText: '', hintText: widget.label, hintStyle: Styles.helperStyle, ), ), Positioned( top: 10, right: 15, child: Text('▼', style: Styles.iconDropdown), ), GestureDetector( onTap: _showOptions, child: Container( width: double.infinity, height: 60, color: Colors.transparent, ), ), ], ); } List<DropdownMenuItem> _buildMenuItems() { var items = widget.options.map((o){ return DropdownMenuItem( value: o, child: Text(o, style: Styles.orderTotalLabel), ); }).toList(); return items; } String _validate(value) { if (value == null) return 'there is an error'; else return null; } _showOptions() async { _selectedOption = await Navigator.push( context, MaterialPageRoute( builder: (context) => DropdownOptions( title: widget.label, selectedOption: _selectedOption, options: widget.options, ), )); if (_selectedOption != null &&_selectedOption.isNotEmpty) isValid = true; setState(() {}); } } class DropdownOptions extends StatefulWidget { final String title; final List<String> options; final String selectedOption; const DropdownOptions({Key key, @required this.title, @required this.options, this.selectedOption}) : super(key: key); @override _DropdownOptionsState createState() => _DropdownOptionsState(); } class _DropdownOptionsState extends State<DropdownOptions> { final _scaffoldKey = GlobalKey<ScaffoldState>(); String _selectedOption; @override void initState() { _selectedOption = widget.selectedOption ?? ''; super.initState(); } @override Widget build(BuildContext context) { return Scaffold( key: _scaffoldKey, appBar: AppBar( backgroundColor: Colors.white, elevation: 0, brightness: Brightness.light, title: Center(child: Text(widget.title, style: Styles.optionsTitle)), actions: <Widget>[FlatButton(child: Text('Done', style: Styles.textButton), onPressed: _sendSelectedOption)], ), backgroundColor: Color(0xfff4f4f4), body: Container( decoration: BoxDecoration(border: Border(top: BorderSide(color: Styles.grayColor))), child: Flex( direction: Axis.vertical, children: <Widget>[ Expanded( child: ListView( children: <Widget>[for (String option in widget.options) _buildOption(option)], ), ), ], ), ), ); } Widget _buildOption(String option) { return GestureDetector( onTap: () => _selectOption(option), child: Container( padding: EdgeInsets.symmetric(horizontal: 40, vertical: 12), decoration: BoxDecoration(color: Colors.white, border: Border(bottom: BorderSide(color: Styles.lightGrayColor))), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Text(option, style: Styles.orderTotalLabel), Icon(Icons.check, color: _selectedOption == option ? Styles.secondaryColor : Colors.transparent, size: 40) ], ), ), ); } void _sendSelectedOption() { if (_selectedOption.isNotEmpty) Navigator.pop(context, _selectedOption); else _scaffoldKey.currentState.showSnackBar(SnackBar(content: Text('Select one of the options'))); } void _selectOption(String option) { setState(() { _selectedOption = option; }); } }
0
mirrored_repositories/flutter_showcase/example/apps/plant_forms/lib
mirrored_repositories/flutter_showcase/example/apps/plant_forms/lib/form_inputs/input_validator.dart
import 'package:plant_forms/demo_data.dart'; import 'package:plant_forms/demo_data.dart'; class InputValidator { const InputValidator(); static bool validate(type, String value, {CreditCardNetwork cardNetwork}) { if (type.runtimeType == InputType) { switch (type as InputType) { case InputType.email: return _validateEmail(value); case InputType.telephone: return _validatePhoneNumber(value); break; default: return true; } } if (type.runtimeType == CreditCardInputType) { switch (type as CreditCardInputType) { case CreditCardInputType.number: return _validateCreditCardNumber(value, cardNetwork); case CreditCardInputType.expirationDate: return _validateCreditCardExpirationDate(value); case CreditCardInputType.securityCode: return _validateCreditCardSecurityCode(value, cardNetwork); } } return false; } static bool _validateEmail(String value) { RegExp emailRegExp = RegExp(r"(^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$)"); return emailRegExp.hasMatch(value); } static bool _validatePhoneNumber(String value) { RegExp telRegExp = RegExp(r"(^(1\s?)?(\(\d{3}\)|\d{3})[\s\-]?\d{3}[\s\-]?\d{4}$)"); return telRegExp.hasMatch(value); } static bool _validateCreditCardNumber(String value, CreditCardNetwork cardNetwork) { // remove empty spaces String cardNumber = value.replaceAll(' ', ''); if (cardNetwork == CreditCardNetwork.amex) { return cardNumber.length == 15; } else { return cardNumber.length == 16; } } static bool _validateCreditCardSecurityCode(String value, CreditCardNetwork cardNetwork) { if (cardNetwork == CreditCardNetwork.amex) { return value.length == 4; } else { return value.length == 3; } } static bool _validateCreditCardExpirationDate(String value) { if (value.length > 3) { int month = int.parse(value.split('/').first); int year = int.parse(value.split('/').last); year += 2000; return month <= 12 && year >= DateTime.now().year; } else { return false; } } }
0
mirrored_repositories/flutter_showcase/example/apps/plant_forms/lib
mirrored_repositories/flutter_showcase/example/apps/plant_forms/lib/form_inputs/text_input.dart
import 'package:flutter/material.dart'; import '../demo_data.dart'; import 'input_validator.dart'; import '../styles.dart'; class TextInput extends StatefulWidget { final String label; final String helper; final String initialValue; final bool isRequired; final InputType type; final Function onValidate; final Function onChange; final bool isActive; final ValueNotifier valueNotifier; const TextInput({ Key key, this.helper = '', this.isRequired = true, this.initialValue = '', this.type = InputType.text, @required this.onValidate, this.label = '', this.isActive = true, this.onChange, this.valueNotifier, }) : super(key: key); @override _TextInputState createState() => _TextInputState(); } class _TextInputState extends State<TextInput> { bool _isAutoValidating = false; bool _isValid; String _value = ''; String _errorText = ''; String get _keyValue => (widget.key as ValueKey).value as String; @override initState() { super.initState(); // Reset the valid state on notifier change if (widget.valueNotifier != null) { widget.valueNotifier.addListener(()=>_isValid = false); } } @override dispose() { super.dispose(); } set isValid(bool isValid) { if (isValid != _isValid) { _isValid = isValid; widget.onValidate(_keyValue, _isValid, value: _value); } } @override Widget build(BuildContext context) { //Validate based on initial value, only do this once. We do it here instead of initState as it may trigger rebuilds up the tree if (_isValid == null) { if (widget.initialValue.isNotEmpty) { _validateField(widget.initialValue); } } //build input return Container( padding: EdgeInsets.only(top: widget.label.isNotEmpty ? 18 : 0), child: Stack( overflow: Overflow.visible, children: <Widget>[ if (widget.label.isNotEmpty) Positioned(top: -24, child: Text(widget.label, style: Styles.inputLabel)), TextFormField( initialValue: _getInitialValue(), style: Styles.orderTotalLabel, enabled: widget.isActive, onChanged: _handleChange, keyboardType: _setKeyboardType(), autovalidate: _isAutoValidating, validator: _validateField, decoration: Styles.getInputDecoration(helper: widget.helper), ), Positioned( top: 6, left: 12, child: Text(_getLabel().toUpperCase(), style: Styles.labelOptional), ), if (_errorText.isNotEmpty) Positioned( top: 8, right: 14, child: Text(_errorText.toUpperCase(), style: Styles.labelNotValid), ), ], ), ); } String _getLabel() { String label = ''; if (!widget.isRequired && _value.isEmpty) label = 'Optional'; if (_value.isNotEmpty && widget.label.isEmpty || _getInitialValue().isNotEmpty) return widget.helper; return label; } String _getInitialValue() { // initial value established from parent if (widget.initialValue != null && widget.initialValue.isNotEmpty) return widget.initialValue; return ''; } void _handleChange(String value) { // save value status _value = value; widget.onChange(_keyValue, value); // activate validation Future.delayed(Duration(milliseconds: 100), () => setState(() {})); if (!_isAutoValidating) setState(() { _isAutoValidating = true; }); } TextInputType _setKeyboardType() { TextInputType type; switch (widget.type) { case InputType.email: type = TextInputType.emailAddress; break; case InputType.telephone: type = TextInputType.numberWithOptions(decimal: true); break; case InputType.number: type = TextInputType.numberWithOptions(signed: true, decimal: true); break; case InputType.text: return TextInputType.text; default: return null; } return type; } String _validateField(String value) { _value = value; // if the value is required if (widget.isRequired && value.isEmpty) { isValid = false; _errorText = 'Required'; // Update error label, wait a frame because this was causing markAsBuild errors Future.delayed(Duration(milliseconds: 17), () => setState(() {})); return _errorText; } // if it is optional else if (!widget.isRequired && value.isEmpty) { isValid = true; _errorText = ''; return null; } // validate when the input has a value else if (value.isNotEmpty && InputValidator.validate(widget.type, value)) { isValid = true; _errorText = ''; return null; } // in other case, the item is not valid else { isValid = false; _errorText = 'Not Valid'; return _errorText; } } }
0
mirrored_repositories/flutter_showcase/example/apps/plant_forms/lib
mirrored_repositories/flutter_showcase/example/apps/plant_forms/lib/form_inputs/checkbox_input.dart
import 'package:flutter/material.dart'; import '../styles.dart'; class CheckBoxInput extends StatefulWidget { final String label; final Function onChange; const CheckBoxInput({Key key, this.label, this.onChange}) : super(key: key); @override _CheckBoxInputState createState() => _CheckBoxInputState(); } class _CheckBoxInputState extends State<CheckBoxInput> { bool _value = true; @override Widget build(BuildContext context) { return Container( height: 56, decoration: BoxDecoration( borderRadius: BorderRadius.circular(4), border: Border.all(color: Styles.lightGrayColor), ), child: Row( children: <Widget>[ Checkbox( activeColor: Styles.secondaryColor, onChanged: _handleChange, value: _value, ), Text(widget.label, style: Styles.inputLabel), ], ), ); } void _handleChange(bool value){ setState(() { _value = value; }); } }
0
mirrored_repositories/flutter_showcase/example/apps/drink_rewards_list
mirrored_repositories/flutter_showcase/example/apps/drink_rewards_list/lib/rounded_shadow.dart
import 'dart:math'; import 'package:flutter/material.dart'; class RoundedShadow extends StatelessWidget { final Widget child; final Color shadowColor; final double topLeftRadius; final double topRightRadius; final double bottomLeftRadius; final double bottomRightRadius; const RoundedShadow( {Key key, this.shadowColor, this.topLeftRadius = 48, this.topRightRadius = 48, this.bottomLeftRadius = 48, this.bottomRightRadius = 48, this.child}) : super(key: key); const RoundedShadow.fromRadius(double radius, {Key key, this.child, this.shadowColor}) : topLeftRadius=radius, topRightRadius=radius, bottomLeftRadius=radius, bottomRightRadius=radius; @override Widget build(BuildContext context) { //Create a border radius, the only applies to the bottom var r = BorderRadius.only( topLeft: Radius.circular(topLeftRadius), topRight: Radius.circular(topRightRadius), bottomLeft: Radius.circular(bottomLeftRadius), bottomRight: Radius.circular(bottomRightRadius), ); var sColor = shadowColor ?? Color(0x20000000); var maxRadius = [topLeftRadius, topRightRadius, bottomLeftRadius, bottomRightRadius].reduce(max); return Container( decoration: new BoxDecoration( borderRadius: r, boxShadow: [new BoxShadow(color: sColor, blurRadius: maxRadius * .5)], ), child: ClipRRect(borderRadius: r, child: child), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/drink_rewards_list
mirrored_repositories/flutter_showcase/example/apps/drink_rewards_list/lib/demo_data.dart
class DrinkData { final String title; final int requiredPoints; final String iconImage; DrinkData(this.title, this.requiredPoints, this.iconImage); } class DemoData{ //how many points this user has earned, in a real app this would be loaded from an online service. int earnedPoints = 150; //List of available drinks List<DrinkData> drinks = [ DrinkData("Coffee", 100, "Coffee.png"), DrinkData("Tea", 150, "Tea.png"), DrinkData("Latte", 250, "Latte.png"), DrinkData("Frappuccino", 350, "Frappuccino.png"), DrinkData("Pressed Juice", 450, "Juice.png"), ]; }
0
mirrored_repositories/flutter_showcase/example/apps/drink_rewards_list
mirrored_repositories/flutter_showcase/example/apps/drink_rewards_list/lib/syles.dart
import 'dart:ui'; import 'package:flutter/cupertino.dart'; import 'main.dart'; class AppColors { static Color orangeAccent = Color(0xfff1a35d); static Color orangeAccentLight = Color(0xffff7f33); static Color redAccent = Color(0xfff1a35d); static Color grey = Color(0xff4d4d4d); } class Styles { static TextStyle text(double size, Color color, bool bold, {double height}) { return TextStyle( fontSize: size, color: color, fontWeight: bold ? FontWeight.bold : FontWeight.normal, height: height, fontFamily: "Poppins", package: App.pkg ); } }
0
mirrored_repositories/flutter_showcase/example/apps/drink_rewards_list
mirrored_repositories/flutter_showcase/example/apps/drink_rewards_list/lib/liquid_painter.dart
import 'dart:math'; import 'package:flutter/material.dart'; class LiquidSimulation { int curveCount = 4; List<Offset> ctrlPts = []; List<Offset> endPts = []; List<Animation<double>> ctrlTweens = []; double endPtX1 = .5; double endPtY1 = 1; double duration; double time; double xOffset = 0; final ElasticOutCurve _ease = ElasticOutCurve(.3); double hzScale; double hzOffset; void start(AnimationController controller, bool flipY) { //Each time the controller ticks, update our control points, using the latest tween values controller.addListener(updateControlPointsFromTweens); //Calculate gap between each ctrl/end pt. var gap = 1 / (curveCount * 2.0); //Randomly scale and offset each simulation, for more variety hzScale = 1.25 + Random().nextDouble() * .5; hzOffset = -.2 + Random().nextDouble() * .4; //Create end points, these sit at yPos=0, and don't animate endPts.clear(); //For n curves, we need n + 2 endpoints //Create first end point endPts.insert(0, Offset(0, 0));//Start at 0,0 for (var i = 1; i < curveCount; i++) { endPts.add(Offset(gap * i * 2, 0)); } //Last endpoint at 1,0 endPts.add(Offset(1, 0)); //Create control points, these animate on the Y axis ctrlPts.clear(); for (var i = 0; i < curveCount + 1; i++) { //Choose random height for this control pt var height = (.5 + Random().nextDouble() * .5) * (i % 2 == 0 ? 1 : -1) * (flipY? -1 : 1); //Create a 3 part tween, does nothing for a bit, then easesOut to 'height', then elastic snaps back to 0 var animSequence = TweenSequence([ TweenSequenceItem<double>( tween: Tween<double>(begin: 0, end: 0), weight: 10.0, ), TweenSequenceItem<double>( tween: Tween<double>(begin: 0, end: height).chain(CurveTween(curve: Curves.linear)), weight: 10.0, ), TweenSequenceItem<double>( tween: Tween<double>(begin: height, end: 0).chain(CurveTween(curve: _ease)), weight: 60.0, ) ]).animate(controller); ctrlTweens.add(animSequence); ctrlPts.add(Offset(gap + gap * i * 2, height)); } } List<Offset> updateControlPointsFromTweens() { for(var i = 0; i < ctrlPts.length; i++){ var o = ctrlPts[i]; ctrlPts[i] = Offset(o.dx, ctrlTweens[i].value); } return ctrlPts; } } class LiquidPainter extends CustomPainter { final double fillLevel; final LiquidSimulation simulation1; final LiquidSimulation simulation2; final double waveHeight; LiquidPainter(this.fillLevel, this.simulation1, this.simulation2, {this.waveHeight = 200}); @override void paint(Canvas canvas, Size size) { _drawLiquidSim(simulation1, canvas, size, 0, Color(0xffC48D3B).withOpacity(.4)); _drawLiquidSim(simulation2, canvas, size, 5, Color(0xff9D7B32).withOpacity(.4)); } @override bool shouldRepaint(CustomPainter oldDelegate) { return false; } void _drawLiquidSim(LiquidSimulation simulation, Canvas canvas, Size size, double offsetY, Color color){ canvas.scale(simulation.hzScale, 1); canvas.translate(simulation.hzOffset * size.width, offsetY); //_drawOffsets(simulation, canvas, size); //Create a path around bottom and sides of card var path = Path() ..moveTo(size.width * 1.25, 0) ..lineTo(size.width * 1.25, size.height) ..lineTo(-size.width * .25, size.height) ..lineTo(-size.width * .25, 0); //Loop through simulation control and end points, drawing each as a pair for(var i = 0; i < simulation.curveCount; i++){ var ctrlPt = sizeOffset(simulation.ctrlPts[i], size); var endPt = sizeOffset(simulation.endPts[i + 1], size); path.quadraticBezierTo(ctrlPt.dx, ctrlPt.dy, endPt.dx, endPt.dy); } canvas.drawPath(path, Paint()..color = color); canvas.translate(-simulation.hzOffset * size.width, -offsetY); canvas.scale(1/simulation.hzScale, 1); } void _drawOffsets(LiquidSimulation simulation, Canvas canvas, Size size) { var floor = size.height; simulation1.endPts.forEach((pt) { canvas.drawCircle(sizeOffset(pt, size), 4, Paint()..color = Colors.red); }); simulation1.ctrlPts.forEach((pt) { canvas.drawCircle(sizeOffset(pt, size), 4, Paint()..color = Colors.green); }); } Offset sizeOffset(Offset pt, Size size) { return Offset(pt.dx * size.width, waveHeight * pt.dy ); } }
0
mirrored_repositories/flutter_showcase/example/apps/drink_rewards_list
mirrored_repositories/flutter_showcase/example/apps/drink_rewards_list/lib/main.dart
import 'package:flutter/material.dart'; import 'package:shared/env.dart'; import 'demo.dart'; void main() => runApp(App()); class App extends StatelessWidget { static String _pkg = "drink_rewards_list"; static String get pkg => Env.getPackage(_pkg); @override Widget build(BuildContext context) { return MaterialApp( home: SafeArea(child: DrinkRewardsListDemo()), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/drink_rewards_list
mirrored_repositories/flutter_showcase/example/apps/drink_rewards_list/lib/demo.dart
import 'dart:ui'; import 'package:flutter/material.dart'; import 'main.dart'; import 'syles.dart'; import 'demo_data.dart'; import 'rounded_shadow.dart'; import 'drink_card.dart'; class DrinkRewardsListDemo extends StatefulWidget { @override _DrinkRewardsListDemoState createState() => _DrinkRewardsListDemoState(); } class _DrinkRewardsListDemoState extends State<DrinkRewardsListDemo> { double _listPadding = 20; DrinkData _selectedDrink; ScrollController _scrollController = ScrollController(); List<DrinkData>_drinks; int _earnedPoints; @override void initState() { var demoData = DemoData(); _drinks = demoData.drinks; _earnedPoints = demoData.earnedPoints; super.initState(); } @override Widget build(BuildContext context) { bool isLandscape = MediaQuery.of(context).size.aspectRatio > 1; double headerHeight = MediaQuery.of(context).size.height * (isLandscape? .25 : .2); return Scaffold( backgroundColor: Color(0xff22222b), body: Theme( data: ThemeData(fontFamily: "Poppins", primarySwatch: Colors.orange), child: Stack( children: <Widget>[ ListView.builder( padding: EdgeInsets.only(bottom: 40, top: headerHeight + 10), itemCount: _drinks.length, scrollDirection: Axis.vertical, controller: _scrollController, itemBuilder: (context, index) => _buildListItem(index), ), _buildTopBg(headerHeight), _buildTopContent(headerHeight), ], ), ), ); } Widget _buildListItem(int index) { return Container( margin: EdgeInsets.symmetric(vertical: _listPadding / 2, horizontal: _listPadding), child: DrinkListCard( earnedPoints: _earnedPoints, drinkData: _drinks[index], isOpen: _drinks[index] == _selectedDrink, onTap: _handleDrinkTapped, ), ); } Widget _buildTopBg(double height) { return Container( alignment: Alignment.topCenter, height: height, child: RoundedShadow( topLeftRadius: 0, topRightRadius: 0, shadowColor: Color(0x0).withAlpha(65), child: Container( width: double.infinity, child: Image.asset("images/Header-Dark.png", fit: BoxFit.fill, package: App.pkg,), )), ); } Widget _buildTopContent(double height) { return SafeArea( child: Align( alignment: Alignment.topCenter, child: Container( padding: EdgeInsets.all(height * .08), constraints: BoxConstraints(maxHeight: height), child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Text("My Rewards", style: Styles.text(height * .13, Colors.white, true)), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Icon(Icons.star, color: AppColors.redAccent, size: height * .2), SizedBox(width: 8), Text("$_earnedPoints", style: Styles.text(height * .3, Colors.white, true)), ], ), Text("Your Points Balance", style: Styles.text(height * .1, Colors.white, false)), ], ), ), ), ); } void _handleDrinkTapped(DrinkData data) { setState(() { //If the same drink was tapped twice, un-select it if (_selectedDrink == data) { _selectedDrink = null; } //Open tapped drink card and scroll to it else { _selectedDrink = data; var selectedIndex = _drinks.indexOf(_selectedDrink); var closedHeight = DrinkListCard.nominalHeightClosed; //Calculate scrollTo offset, subtract a bit so we don't end up perfectly at the top var offset = selectedIndex * (closedHeight + _listPadding) - closedHeight * .35; _scrollController.animateTo(offset, duration: Duration(milliseconds: 700), curve: Curves.easeOutQuad); } }); } }
0
mirrored_repositories/flutter_showcase/example/apps/drink_rewards_list
mirrored_repositories/flutter_showcase/example/apps/drink_rewards_list/lib/drink_card.dart
import 'dart:math'; import 'package:flutter/material.dart'; import 'main.dart'; import 'liquid_painter.dart'; import 'rounded_shadow.dart'; import 'syles.dart'; import 'demo_data.dart'; class DrinkListCard extends StatefulWidget { static double nominalHeightClosed = 96; static double nominalHeightOpen = 290; final Function(DrinkData) onTap; final bool isOpen; final DrinkData drinkData; final int earnedPoints; const DrinkListCard({Key key, this.drinkData, this.onTap, this.isOpen = false, this.earnedPoints = 100}) : super(key: key); @override _DrinkListCardState createState() => _DrinkListCardState(); } class _DrinkListCardState extends State<DrinkListCard> with TickerProviderStateMixin { bool _wasOpen; Animation<double> _fillTween; Animation<double> _pointsTween; AnimationController _liquidSimController; //Create 2 simulations, that will be passed to the LiquidPainter to be drawn. LiquidSimulation _liquidSim1 = LiquidSimulation(); LiquidSimulation _liquidSim2 = LiquidSimulation(); @override void initState() { //Create a controller to drive the "fill" animations _liquidSimController = AnimationController(vsync: this, duration: Duration(milliseconds: 3000)); _liquidSimController.addListener(_rebuildIfOpen); //create tween to raise the fill level of the card _fillTween = Tween<double>(begin: 0, end: 1).animate( CurvedAnimation(parent: _liquidSimController, curve: Interval(.12, .45, curve: Curves.easeOut)), ); //create tween to animate the 'points remaining' text _pointsTween = Tween<double>(begin: 0, end: 1).animate( CurvedAnimation(parent: _liquidSimController, curve: Interval(.1, .5, curve: Curves.easeOutQuart)), ); super.initState(); } @override void dispose() { _liquidSimController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { //If our open state has changed... if (widget.isOpen != _wasOpen) { //Kickoff the fill animations if we're opening up if (widget.isOpen) { //Start both of the liquid simulations, they will initialize to random values _liquidSim1.start(_liquidSimController, true); _liquidSim2.start(_liquidSimController, false); //Run the animation controller, kicking off all tweens _liquidSimController.forward(from: 0); } _wasOpen = widget.isOpen; } //Determine the points required text value, using the _pointsTween var pointsRequired = widget.drinkData.requiredPoints; var pointsValue = pointsRequired - _pointsTween.value * min(widget.earnedPoints, pointsRequired); //Determine current fill level, based on _fillTween double _maxFillLevel = min(1, widget.earnedPoints / widget.drinkData.requiredPoints); double fillLevel = _maxFillLevel; //_maxFillLevel * _fillTween.value; double cardHeight = widget.isOpen ? DrinkListCard.nominalHeightOpen : DrinkListCard.nominalHeightClosed; return GestureDetector( onTap: _handleTap, //Use an animated container so we can easily animate our widget height child: AnimatedContainer( curve: !_wasOpen ? ElasticOutCurve(.9) : Curves.elasticOut, duration: Duration(milliseconds: !_wasOpen ? 1200 : 1500), height: cardHeight, //Wrap content in a rounded shadow widget, so it will be rounded on the corners but also have a drop shadow child: RoundedShadow.fromRadius( 12, child: Container( color: Color(0xff303238), child: Stack( fit: StackFit.expand, children: <Widget>[ //Background liquid layer AnimatedOpacity( opacity: widget.isOpen ? 1 : 0, duration: Duration(milliseconds: 500), child: _buildLiquidBackground(_maxFillLevel, fillLevel), ), //Card Content Container( margin: EdgeInsets.symmetric(horizontal: 24, vertical: 0), //Wrap content in a ScrollView, so there's no errors on over scroll. child: SingleChildScrollView( //We don't actually want the scrollview to scroll, disable it. physics: NeverScrollableScrollPhysics(), child: Column( children: [ SizedBox(height: 24), //Top Header Row _buildTopContent(), //Spacer SizedBox(height: 12), //Bottom Content, use AnimatedOpacity to fade AnimatedOpacity( duration: Duration(milliseconds: widget.isOpen ? 1000 : 500), curve: Curves.easeOut, opacity: widget.isOpen ? 1 : 0, //Bottom Content child: _buildBottomContent(pointsValue), ), ], ), ), ), ], ), ), ), ), ); } Stack _buildLiquidBackground(double _maxFillLevel, double fillLevel) { return Stack( fit: StackFit.expand, children: <Widget>[ Transform.translate( offset: Offset(0, DrinkListCard.nominalHeightOpen * 1.2 - DrinkListCard.nominalHeightOpen * _fillTween.value * _maxFillLevel * 1.2), child: CustomPaint( painter: LiquidPainter(fillLevel, _liquidSim1, _liquidSim2, waveHeight: 100), ), ), ], ); } Row _buildTopContent() { return Row( children: <Widget>[ //Icon Image.asset( "images/" + widget.drinkData.iconImage, fit: BoxFit.fitWidth, width: 50, package: App.pkg, ), SizedBox(width: 24), //Label Expanded( child: Text( widget.drinkData.title.toUpperCase(), style: Styles.text(18, Colors.white, true), ), ), //Star Icon Icon(Icons.star, size: 20, color: AppColors.orangeAccent), SizedBox(width: 4), //Points Text Text("${widget.drinkData.requiredPoints}", style: Styles.text(20, Colors.white, true)) ], ); } Column _buildBottomContent(double pointsValue) { bool isDisabled = widget.earnedPoints < widget.drinkData.requiredPoints; List<Widget> rowChildren = []; if (pointsValue == 0) { rowChildren.add(Text("Congratulations!", style: Styles.text(16, Colors.white, true))); } else { rowChildren.addAll([ Text("You're only ", style: Styles.text(12, Colors.white, false)), Text(" ${pointsValue.round()} ", style: Styles.text(16, AppColors.orangeAccent, true)), Text(" points away", style: Styles.text(12, Colors.white, false)), ]); } return Column( children: [ //Body Text Row( mainAxisAlignment: MainAxisAlignment.center, children: rowChildren, ), SizedBox(height: 16), Text( "Redeem your points for a cup of happiness! Our signature espresso is blanced with steamed milk and topped with a light layer of foam. ", textAlign: TextAlign.center, style: Styles.text(14, Colors.white, false, height: 1.5), ), SizedBox(height: 16), //Main Button ButtonTheme( minWidth: 200, height: 40, child: Opacity( opacity: isDisabled ? .6 : 1, child: FlatButton( //Enable the button if we have enough points. Can do this by assigning a onPressed listener, or not. onPressed: isDisabled ? () {} : null, color: AppColors.orangeAccent, disabledColor: AppColors.orangeAccent, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(24)), child: Text("REDEEM", style: Styles.text(16, Colors.white, true)), ), ), ) ], ); } void _handleTap() { if (widget.onTap != null) { widget.onTap(widget.drinkData); } } void _rebuildIfOpen() { if (widget.isOpen) { setState(() {}); } } }
0
mirrored_repositories/flutter_showcase/example/apps/basketball_ptr
mirrored_repositories/flutter_showcase/example/apps/basketball_ptr/lib/scores_app_bar.dart
import 'package:flutter/material.dart'; import 'main.dart'; class ScoresAppBar extends StatelessWidget { @override Widget build(context) { // Build a app bar that has a gradient, title and some buttons return Container( height: 90, decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.centerLeft, end: Alignment.centerRight, colors: [ const Color(0xFF1094A7), const Color(0xFFF37B4D), ], tileMode: TileMode.clamp, ), ), // Avoid cutting off the buttons with safe area child: SafeArea( top: true, child: Padding( padding: EdgeInsets.symmetric(vertical: 0.0, horizontal: 16.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Icon( Icons.arrow_back_ios, color: Colors.white, size: 20, ), Padding(padding: EdgeInsets.all(20)), Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text('LIVE SCORES', style: TextStyle(fontSize: 18, color: Colors.white, fontFamily: 'FjallaOne', package: App.pkg)), Text('OCT 24, 2019', style: TextStyle(fontSize: 10, color: Colors.white, fontFamily: 'OpenSans', package: App.pkg)), ], ), Padding(padding: EdgeInsets.all(20)), Icon( Icons.calendar_today, color: Colors.white, size: 20, ), ], ), ), ), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/basketball_ptr
mirrored_repositories/flutter_showcase/example/apps/basketball_ptr/lib/pull_to_refresh_container.dart
import 'package:flutter/material.dart'; import 'scaling_info.dart'; import 'notifications.dart'; import 'spinning_basketball.dart'; import 'main.dart'; class PullToRefreshContainer extends StatelessWidget { final double maxHeight; final double height; final ChangeNotifier refreshNotifier; PullToRefreshContainer({this.maxHeight, this.height, this.refreshNotifier}); @override Widget build(context) { final width = MediaQuery.of(context).size.width; return Container( height: height, width: width, child: ClipRect( child: Container( color: Color(0xFFF0F0F0), child: BasketballPTRContainerAnimation( maxHeight: maxHeight, height: height, refreshNotifier: refreshNotifier, ), ), ), ); } } class BasketballPTRContainerAnimation extends StatefulWidget { final double maxHeight; final double height; final ChangeNotifier refreshNotifier; BasketballPTRContainerAnimation({this.maxHeight = 180, this.height = 0, this.refreshNotifier}); @override State createState() { return _BasketballPTRContainerAnimationState(maxHeight, height, refreshNotifier); } } class _BasketballPTRContainerAnimationState extends State<BasketballPTRContainerAnimation> with SingleTickerProviderStateMixin { final double _maxHeight; double _height; AnimationController _controller; Animation<double> _scaleAnimation; ChangeNotifier _refreshNotifier; _BasketballPTRContainerAnimationState(this._maxHeight, this._height, this._refreshNotifier); @override void initState() { _controller = AnimationController(vsync: this, duration: const Duration(seconds: 2, milliseconds: 500)); _scaleAnimation = TweenSequence<double>([ TweenSequenceItem( tween: Tween<double>(begin: 0.5, end: 0.0).chain(CurveTween(curve: ElasticOutCurve(0.65)).chain( Tween<double>(begin: 0.0, end: 0.5), )), weight: 2.0, ), TweenSequenceItem( tween: Tween<double>(begin: 0.0, end: 0.0), weight: 5.0, ), ]).animate(_controller); _controller.addListener(() { setState(() {}); if (_controller.value > 0.9) { DoneLoadingNotification()..dispatch(context); } }); _controller.addStatusListener((status) { if (status == AnimationStatus.forward) { LoadingNotification()..dispatch(context); } }); _refreshNotifier.addListener(() { _controller.forward(from: 0.0); }); super.initState(); } @override void dispose() { _controller.dispose(); super.dispose(); } @override void didUpdateWidget(BasketballPTRContainerAnimation oldWidget) { if (oldWidget.height != widget.height) { setState(() { _height = widget.height; if (_height == 0) { _controller.reset(); } }); } super.didUpdateWidget(oldWidget); } @override Widget build(context) { final appSize = MediaQuery.of(context).size; final scale = 0.8 - Curves.easeIn.transform((_height / _maxHeight) / 2.0) * _scaleAnimation.value; final centerX = appSize.width / 2; final backboardWidth = 0.8 * _maxHeight * scale; final netWidth = 0.35 * _maxHeight * scale; final rimWidth = 0.4 * _maxHeight * scale; final backboardHeight = backboardWidth * 0.69375; final netHeight = netWidth * 0.984375; final rimHeight = rimWidth * 0.121739; final yOffset = _maxHeight * 0.08; final startY = yOffset * 3.0; final backboardY = startY + backboardHeight / 2; final rimY = backboardY + backboardHeight * 0.33; final netY = rimY + netHeight * 0.5; String refreshText = ''; if (_controller.value > 6 / 7) { refreshText = 'Updated!'; } else if (_controller.isAnimating) { refreshText = 'Checking for latest scores'; } else if (_height / _maxHeight >= 1.05) { refreshText = 'Release to refresh'; } else { refreshText = 'Pull down to refresh'; } // Position the backboard, net, rim and ball according to the animation progress List<Widget> children = <Widget>[ Positioned( left: 0, top: yOffset, width: appSize.width, child: Text(refreshText, textAlign: TextAlign.center, style: TextStyle( color: Color(0xFF808080), fontFamily: 'OpenSans', fontSize: 12, )), ), Positioned( left: centerX - backboardWidth / 2, top: backboardY - backboardHeight / 2, width: backboardWidth, child: Image(image: AssetImage('assets/backboard.png', package: App.pkg)), ), Positioned( left: centerX - netWidth / 2, top: netY - netHeight / 2, width: netWidth, child: Image(image: AssetImage('assets/net.png', package: App.pkg)), ), Positioned( left: centerX - rimWidth / 2, top: rimY - rimHeight / 2, width: rimWidth, child: Image(image: AssetImage('assets/rim.png', package: App.pkg)), ), ]; children.insert(_controller.value > 0.28 ? 2 : 4, SpinningBasketball(controller: _controller, maxHeight: _maxHeight)); return Stack( children: children, ); } }
0
mirrored_repositories/flutter_showcase/example/apps/basketball_ptr
mirrored_repositories/flutter_showcase/example/apps/basketball_ptr/lib/notifications.dart
import 'package:flutter/material.dart'; class LoadingNotification extends Notification {} class DoneLoadingNotification extends LoadingNotification {}
0
mirrored_repositories/flutter_showcase/example/apps/basketball_ptr
mirrored_repositories/flutter_showcase/example/apps/basketball_ptr/lib/spinning_basketball.dart
import 'dart:math' as math; import 'package:flutter/material.dart'; import 'package:shared/ui/animated_sprite.dart'; import 'scaling_info.dart'; import 'main.dart'; class SineCurve extends Curve { final double start; final double length; SineCurve({this.start = 0.0, this.length = math.pi * 2}); @override double transformInternal(double d) { return math.sin(start + d * length) * 0.5 + 0.5; } } class SpinningBasketball extends StatefulWidget { final AnimationController controller; final double maxHeight; SpinningBasketball({this.controller, this.maxHeight}) : super(key: ValueKey(controller)); @override State createState() { return _SpinningBasketballState(controller, maxHeight); } } class _SpinningBasketballState extends State<SpinningBasketball> with SingleTickerProviderStateMixin { double _maxHeight; AnimationController _controller; Animation<double> _spriteAnimation; Animation<double> _xAnimation; Animation<double> _yAnimation; Animation<double> _scaleAnimation; _SpinningBasketballState(this._controller, this._maxHeight); @override void initState() { final cosCurve = SineCurve(start: -math.pi / 2, length: math.pi * 4); final sineCurve = SineCurve(length: math.pi * 4); _spriteAnimation = TweenSequence<double>([ TweenSequenceItem( tween: Tween<double>(begin: 0.0, end: 19.0), weight: 2, ), TweenSequenceItem( tween: Tween<double>(begin: 20.0, end: 39.0), weight: 2, ), TweenSequenceItem( tween: Tween<double>(begin: 20.0, end: 39.0), weight: 2, ), TweenSequenceItem( tween: Tween<double>(begin: 40.0, end: 59.0), weight: 1, ), ]).animate(_controller); _xAnimation = TweenSequence<double>([ TweenSequenceItem( tween: Tween<double>(begin: 0.0, end: 0.08), weight: 1.2, ), TweenSequenceItem( tween: Tween<double>(begin: 0.08, end: 0.12), weight: 0.6, ), TweenSequenceItem( tween: Tween<double>(begin: 0.12, end: -0.12) .chain(CurveTween(curve: cosCurve)), weight: 4.2, ), TweenSequenceItem( tween: Tween<double>(begin: 0.12, end: 0.0) .chain(CurveTween(curve: Curves.easeInSine)), weight: 1, ), ]).animate(_controller); _yAnimation = TweenSequence<double>([ TweenSequenceItem( tween: Tween<double>(begin: 1.70, end: -0.72) .chain(CurveTween(curve: Curves.easeOutSine)), weight: 1.3, ), TweenSequenceItem( tween: Tween<double>(begin: -0.72, end: 0.02) .chain(CurveTween(curve: SineCurve(start: -math.pi / 2, length: math.pi))), weight: 0.7, ), TweenSequenceItem( tween: ConstantTween<double>(0.02), weight: 4.00, ), TweenSequenceItem( tween: Tween<double>(begin: 0.02, end: 0.30) .chain(CurveTween(curve: Curves.easeInCubic)), weight: 1, ), ]).animate(_controller); _scaleAnimation = TweenSequence<double>([ TweenSequenceItem( tween: ConstantTween<double>(1.0), weight: 2, ), TweenSequenceItem( tween: Tween<double>(begin: 1.05, end: 0.9).chain(CurveTween(curve: sineCurve)), weight: 4, ), TweenSequenceItem( tween: ConstantTween<double>(1.0), weight: 1, ), ]).animate(_controller); _controller.addListener(() { setState(() {}); }); super.initState(); } @override Widget build(context) { final appSize = MediaQuery.of(context).size; double scaledWidth = 0.3 * _maxHeight * _scaleAnimation.value * 0.8; double scaledHeight = 0.3 * _maxHeight * _scaleAnimation.value * 0.8; final yOffset = _maxHeight * 0.08; final backboardWidth = 0.8 * _maxHeight * 0.8; final backboardHeight = backboardWidth * 0.69375; final startY = yOffset * 3.0; final backboardY = startY + backboardHeight / 2; final rimY = backboardY + backboardHeight * 0.33; // Draw the ball from a sprite sheet, position according to the animation return Positioned( left: _xAnimation.value * 160 * ScalingInfo.scaleX + appSize.width / 2 - scaledWidth / 2, top: _yAnimation.value * _maxHeight / 2 + rimY - scaledHeight, width: scaledWidth, height: scaledHeight, child: AnimatedSprite( image: AssetImage('assets/basketball.png', package: App.pkg), frameWidth: 400, frameHeight: 400, animation: _spriteAnimation, ), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/basketball_ptr
mirrored_repositories/flutter_showcase/example/apps/basketball_ptr/lib/theme_info.dart
import 'package:flutter/material.dart'; import 'main.dart'; class ThemeInfo { static Color background0 = Color(0xFFB4B4B4); static Color accent0 = Color(0xFFFF6826); static Color accent1 = Color(0xFF262626); static Color accent2 = Color(0xFFFF733E); static Color accent3 = Color(0xFFF5F5F5); static TextStyle textStyleTeam = TextStyle(fontFamily: 'OpenSans', fontSize: 10, package: App.pkg); static TextStyle textStyleHighlights = TextStyle(fontFamily: 'OpenSans', fontSize: 8, fontWeight: FontWeight.w600, package: App.pkg); }
0
mirrored_repositories/flutter_showcase/example/apps/basketball_ptr
mirrored_repositories/flutter_showcase/example/apps/basketball_ptr/lib/demo_data.dart
import 'dart:math' as math; enum BasketballGameQuarter { Q1, Q2, HALF_TIME, Q3, Q4, FINISHED, } class BasketballGameData { final BasketballGameQuarter quarter; final Duration time; final int homeTeamScore; final int awayTeamScore; final String homeTeamName; final String awayTeamName; final String homeTeamCity; final String awayTeamCity; final String homeTeamLogoPath; final String awayTeamLogoPath; BasketballGameData({ this.quarter, this.time, this.homeTeamScore, this.awayTeamScore, this.homeTeamName, this.awayTeamName, this.homeTeamCity, this.awayTeamCity, this.homeTeamLogoPath, this.awayTeamLogoPath, }); } class BasketballGameModel { final List<BasketballGameData> basketballGames; BasketballGameModel() : basketballGames = [ BasketballGameData( quarter: BasketballGameQuarter.HALF_TIME, homeTeamScore: 63, awayTeamScore: 53, homeTeamName: 'Knights', awayTeamName: 'Flutters', homeTeamCity: 'New York', awayTeamCity: 'Edmonton', homeTeamLogoPath: 'assets/viking.png', awayTeamLogoPath: 'assets/f.png', ), BasketballGameData( quarter: BasketballGameQuarter.Q4, time: Duration(minutes: 7, seconds: 6), homeTeamScore: 115, awayTeamScore: 105, homeTeamName: 'Birds', awayTeamName: 'Stars', homeTeamCity: 'Birmingham', awayTeamCity: 'Seattle', homeTeamLogoPath: 'assets/flutter.png', awayTeamLogoPath: 'assets/badge.png', ), BasketballGameData( quarter: BasketballGameQuarter.Q4, time: Duration(minutes: 10, seconds: 28), homeTeamScore: 85, awayTeamScore: 88, homeTeamName: 'Dribblers', awayTeamName: 'Cannons', homeTeamCity: 'LA', awayTeamCity: 'Dallas', homeTeamLogoPath: 'assets/light.png', awayTeamLogoPath: 'assets/maroon.png', ), BasketballGameData( quarter: BasketballGameQuarter.FINISHED, homeTeamScore: 97, awayTeamScore: 109, homeTeamName: 'Knights', awayTeamName: 'Birds', homeTeamCity: 'New York', awayTeamCity: 'Birmingham', homeTeamLogoPath: 'assets/viking.png', awayTeamLogoPath: 'assets/flutter.png', ), BasketballGameData( quarter: BasketballGameQuarter.FINISHED, homeTeamScore: 112, awayTeamScore: 102, homeTeamName: 'Flutters', awayTeamName: 'Dribblers', homeTeamCity: 'Edmonton', awayTeamCity: 'LA', homeTeamLogoPath: 'assets/f.png', awayTeamLogoPath: 'assets/light.png', ), BasketballGameData( quarter: BasketballGameQuarter.HALF_TIME, homeTeamScore: 63, awayTeamScore: 53, homeTeamName: 'Knights', awayTeamName: 'Flutters', homeTeamCity: 'New York', awayTeamCity: 'Edmonton', homeTeamLogoPath: 'assets/viking.png', awayTeamLogoPath: 'assets/f.png', ), BasketballGameData( quarter: BasketballGameQuarter.Q4, time: Duration(minutes: 7, seconds: 6), homeTeamScore: 115, awayTeamScore: 105, homeTeamName: 'Birds', awayTeamName: 'Stars', homeTeamCity: 'Birmingham', awayTeamCity: 'Seattle', homeTeamLogoPath: 'assets/flutter.png', awayTeamLogoPath: 'assets/badge.png', ), BasketballGameData( quarter: BasketballGameQuarter.Q4, time: Duration(minutes: 10, seconds: 28), homeTeamScore: 85, awayTeamScore: 88, homeTeamName: 'Dribblers', awayTeamName: 'Cannons', homeTeamCity: 'LA', awayTeamCity: 'Dallas', homeTeamLogoPath: 'assets/light.png', awayTeamLogoPath: 'assets/maroon.png', ), BasketballGameData( quarter: BasketballGameQuarter.FINISHED, homeTeamScore: 97, awayTeamScore: 109, homeTeamName: 'Knights', awayTeamName: 'Birds', homeTeamCity: 'New York', awayTeamCity: 'Birmingham', homeTeamLogoPath: 'assets/viking.png', awayTeamLogoPath: 'assets/flutter.png', ), BasketballGameData( quarter: BasketballGameQuarter.FINISHED, homeTeamScore: 112, awayTeamScore: 102, homeTeamName: 'Flutters', awayTeamName: 'Dribblers', homeTeamCity: 'Edmonton', awayTeamCity: 'LA', homeTeamLogoPath: 'assets/f.png', awayTeamLogoPath: 'assets/light.png', ), ]; BasketballGameModel.randomize() : basketballGames = <BasketballGameData>[] { final rng = math.Random(); const List<String> teamCities = [ 'Seattle', 'Edmonton', 'Birmingham', 'LA', 'Dallas', 'New York', ]; const List<String> teamNames = [ 'Stars', 'Flutters', 'Birds', 'Dribblers', 'Cannons', 'Knights', ]; const List<String> logoPaths = [ 'assets/badge.png', 'assets/f.png', 'assets/flutter.png', 'assets/light.png', 'assets/maroon.png', 'assets/viking.png', ]; for (int i = 0; i < 10; ++i) { int homeTeam = rng.nextInt(6); int awayTeam; do { awayTeam = rng.nextInt(6); } while (awayTeam == homeTeam); basketballGames.add( BasketballGameData( quarter: BasketballGameQuarter.values[rng.nextInt(BasketballGameQuarter.values.length)], time: Duration(minutes: rng.nextInt(30), seconds: rng.nextInt(60)), homeTeamScore: rng.nextInt(160), awayTeamScore: rng.nextInt(160), homeTeamName: teamNames[homeTeam], awayTeamName: teamNames[awayTeam], homeTeamCity: teamCities[homeTeam], awayTeamCity: teamCities[awayTeam], homeTeamLogoPath: logoPaths[homeTeam], awayTeamLogoPath: logoPaths[awayTeam], ), ); } } BasketballGameData getGameData(int index) { return basketballGames[index]; } }
0
mirrored_repositories/flutter_showcase/example/apps/basketball_ptr
mirrored_repositories/flutter_showcase/example/apps/basketball_ptr/lib/game_time.dart
import 'package:flutter/material.dart'; import './theme_info.dart'; import './demo_data.dart'; import './main.dart'; class GameTime extends StatelessWidget { final BasketballGameData data; GameTime({@required this.data}); @override Widget build(context) { String quarterString; switch (data.quarter) { case BasketballGameQuarter.Q1: quarterString = 'Q1'; break; case BasketballGameQuarter.Q2: quarterString = 'Q2'; break; case BasketballGameQuarter.Q3: quarterString = 'Q3'; break; case BasketballGameQuarter.Q4: quarterString = 'Q4'; break; default: break; } // Use the dart spread operator to change the ui based off of the data model return Row(children: [ if (data.quarter == BasketballGameQuarter.HALF_TIME) ...{ Container( color: ThemeInfo.accent2, padding: EdgeInsets.symmetric(vertical: 2, horizontal: 14), child: Text('Half Time', style: TextStyle(color: Colors.white, fontSize: 8, fontWeight: FontWeight.w600, fontFamily: 'OpenSans', package: App.pkg)), ), } else if (data.quarter == BasketballGameQuarter.FINISHED) ...{ Container( color: ThemeInfo.accent3, padding: EdgeInsets.symmetric(vertical: 2, horizontal: 14), child: Text('Final Score', style: TextStyle(color: Colors.black, fontSize: 8, fontWeight: FontWeight.w600, fontFamily: 'OpenSans', package: App.pkg)), ), } else ...{ Container( color: ThemeInfo.accent2, padding: EdgeInsets.symmetric(vertical: 2, horizontal: 14), child: Text(quarterString, style: TextStyle(color: Colors.white, fontSize: 8, fontWeight: FontWeight.w600, fontFamily: 'OpenSans', package: App.pkg)), ), Container( color: ThemeInfo.accent3, padding: EdgeInsets.symmetric(vertical: 2, horizontal: 14), child: Text('${data.time.inMinutes}:${(data.time.inSeconds - (data.time.inMinutes * 60)).toString().padLeft(2, '0')}', style: TextStyle(color: Colors.black, fontSize: 8, fontWeight: FontWeight.w600, fontFamily: 'OpenSans', package: App.pkg)), ), } ]); } }
0
mirrored_repositories/flutter_showcase/example/apps/basketball_ptr
mirrored_repositories/flutter_showcase/example/apps/basketball_ptr/lib/game_score.dart
import 'package:flutter/material.dart'; import './theme_info.dart'; import './demo_data.dart'; import './main.dart'; class GameScore extends StatefulWidget { final BasketballGameData data; GameScore({@required this.data}); @override State createState() { return _GameScoreState(data); } } class _GameScoreState extends State<GameScore> with SingleTickerProviderStateMixin { BasketballGameData _data; BasketballGameData _newData; AnimationController _controller; Animation<double> _scoreAnimation; _GameScoreState(this._data); @override void initState() { _controller = AnimationController(vsync: this, duration: const Duration(milliseconds: 200)); _scoreAnimation = Tween<double>( begin: 0.0, end: -1.0, ).animate(_controller); _controller.addStatusListener((status) { if (status == AnimationStatus.completed) { setState(() { _data = _newData; _newData = null; }); _controller.reset(); } }); _controller.addListener(() { setState(() {}); }); super.initState(); } @override void dispose() { _controller.dispose(); super.dispose(); } @override void didUpdateWidget(GameScore oldWidget) { if (oldWidget.data != widget.data) { _newData = widget.data; _controller.forward(from: 0.0); } super.didUpdateWidget(oldWidget); } @override Widget build(context) { return Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Container( width: 50, height: 36, child: Stack( children: _buildTeamScores(true), ), ), Padding(padding: EdgeInsets.all(8)), Text('-', style: TextStyle(fontSize: 28, color: ThemeInfo.accent1, fontFamily: 'FjallaOne', package: App.pkg)), Padding(padding: EdgeInsets.all(8)), Container( width: 50, height: 36, child: Stack( children: _buildTeamScores(false), ), ), ], ); } List<Widget> _buildTeamScores(bool homeTeam) { final currentColor = (homeTeam ? _data.homeTeamScore > _data.awayTeamScore : _data.awayTeamScore > _data.homeTeamScore) && _data.quarter == BasketballGameQuarter.FINISHED ? ThemeInfo.accent0 : ThemeInfo.accent1; List<Widget> results = <Widget>[]; results.add(Positioned( top: _scoreAnimation.value * 36.0, width: 50, child: Text(homeTeam ? _data.homeTeamScore.toString() : _data.awayTeamScore.toString(), textAlign: homeTeam ? TextAlign.right : TextAlign.left, style: TextStyle(fontSize: 28, color: currentColor, fontFamily: 'FjallaOne', package: App.pkg)))); if (_newData != null) { final newColor = (homeTeam ? _newData.homeTeamScore > _newData.awayTeamScore : _newData.awayTeamScore > _newData.homeTeamScore) && _newData.quarter == BasketballGameQuarter.FINISHED ? ThemeInfo.accent0 : ThemeInfo.accent1; results.add(Positioned( top: _scoreAnimation.value * 36.0 + 36.0, width: 50, child: Text(homeTeam ? _newData.homeTeamScore.toString() : _newData.awayTeamScore.toString(), textAlign: homeTeam ? TextAlign.right : TextAlign.left, style: TextStyle(fontSize: 28, color: newColor, fontFamily: 'FjallaOne', package: App.pkg)))); } return results; } }
0
mirrored_repositories/flutter_showcase/example/apps/basketball_ptr
mirrored_repositories/flutter_showcase/example/apps/basketball_ptr/lib/game_list_item.dart
import 'package:flutter/material.dart'; import './theme_info.dart'; import './demo_data.dart'; import './game_time.dart'; import './game_score.dart'; import 'main.dart'; class GameListItem extends StatelessWidget { final BasketballGameData data; GameListItem({@required this.data}); @override Widget build(context) { return Container( height: 140, color: Colors.white, padding: EdgeInsets.symmetric(vertical: 6, horizontal: 9), child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [ Column(mainAxisAlignment: MainAxisAlignment.center, children: [ // Home team logo SizedBox( width: 64, height: 64, child: Image( image: AssetImage(data.homeTeamLogoPath, package: App.pkg), ), ), Text(data.homeTeamCity, style: ThemeInfo.textStyleTeam), Text(data.homeTeamName, style: ThemeInfo.textStyleTeam), ]), Padding(padding: EdgeInsets.all(4)), Column(mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ // Propagate data down to the widgets that need it GameTime(data: data), GameScore(data: data), // The Highlights text has a rounded border Container( decoration: ShapeDecoration( shape: RoundedRectangleBorder( side: BorderSide(color: ThemeInfo.background0), borderRadius: BorderRadius.circular(12), ), ), padding: EdgeInsets.symmetric(vertical: 4, horizontal: 18), child: Text( 'HIGHLIGHTS', style: ThemeInfo.textStyleHighlights, ), ), ]), Padding(padding: EdgeInsets.all(4)), Column(mainAxisAlignment: MainAxisAlignment.center, children: [ // Away team logo SizedBox( width: 64, height: 64, child: Image( image: AssetImage(data.awayTeamLogoPath, package: App.pkg), ), ), Text(data.awayTeamCity, style: ThemeInfo.textStyleTeam), Text(data.awayTeamName, style: ThemeInfo.textStyleTeam), ]), ]), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/basketball_ptr
mirrored_repositories/flutter_showcase/example/apps/basketball_ptr/lib/scaling_info.dart
import 'package:flutter/material.dart'; class ScalingInfo { static double _scaleX; static double _scaleY; static void init(MediaQueryData data) { final appSize = data.size; _scaleX = (appSize.width / 320).clamp(1, 1.5); } static double get scaleX => _scaleX; static double get scaleY => _scaleY; }
0
mirrored_repositories/flutter_showcase/example/apps/basketball_ptr
mirrored_repositories/flutter_showcase/example/apps/basketball_ptr/lib/game_list_view.dart
import 'package:flutter/material.dart'; import './theme_info.dart'; import './demo_data.dart'; import './game_list_item.dart'; class GameListView extends StatelessWidget { final ScrollController controller; final ScrollPhysics physics; final BasketballGameModel model; final EdgeInsetsGeometry padding; GameListView({@required this.controller, this.physics, @required this.model, this.padding = EdgeInsets.zero}); @override Widget build(context) { // Build a simple container that shows the content, use the custom scroll controller and physics to enable // the pull to refresh behavior return Expanded( child: Container( color: ThemeInfo.background0, child: ListView( physics: physics, controller: controller, padding: padding, scrollDirection: Axis.vertical, // Fetch the data for the children from the fake model children: [ GameListItem(data: model.getGameData(0)), Padding(padding: EdgeInsets.only(top: 1)), GameListItem(data: model.getGameData(1)), Padding(padding: EdgeInsets.only(top: 1)), GameListItem(data: model.getGameData(2)), Padding(padding: EdgeInsets.only(top: 1)), GameListItem(data: model.getGameData(3)), Padding(padding: EdgeInsets.only(top: 1)), GameListItem(data: model.getGameData(4)), Padding(padding: EdgeInsets.only(top: 1)), GameListItem(data: model.getGameData(5)), Padding(padding: EdgeInsets.only(top: 1)), GameListItem(data: model.getGameData(6)), Padding(padding: EdgeInsets.only(top: 1)), GameListItem(data: model.getGameData(7)), Padding(padding: EdgeInsets.only(top: 1)), GameListItem(data: model.getGameData(8)), Padding(padding: EdgeInsets.only(top: 1)), GameListItem(data: model.getGameData(9)), ], ), ), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/basketball_ptr
mirrored_repositories/flutter_showcase/example/apps/basketball_ptr/lib/main.dart
import 'package:flutter/material.dart'; import 'package:shared/env.dart'; import './demo.dart'; void main() => runApp(App()); class App extends StatelessWidget { static String _pkg = "basketball_ptr"; static String get pkg => Env.getPackage(_pkg); @override Widget build(BuildContext context) { return BasketballPTRDemo(); } }
0
mirrored_repositories/flutter_showcase/example/apps/basketball_ptr
mirrored_repositories/flutter_showcase/example/apps/basketball_ptr/lib/demo.dart
import 'package:flutter/material.dart'; import './scaling_info.dart'; import './demo_data.dart'; import './scores_app_bar.dart'; import './notifications.dart'; import './game_list_view.dart'; import './pull_to_refresh_container.dart'; class BasketballPTRDemo extends StatelessWidget { @override Widget build(context) { return MaterialApp( home: SafeArea(child: Material(child: BasketballPTRHome())), ); } } class BasketballPTRHome extends StatefulWidget { @override State createState() { return _BasketballPTRHomeState(); } } class _BasketballPTRHomeState extends State<BasketballPTRHome> with SingleTickerProviderStateMixin { BasketballGameModel _model; ScrollController _scrollController; AnimationController _controller; Animation<double> _pullAnimation; double _percentage = 0.0; bool _isLoading = false; double _maxHeight; ValueNotifier<bool> _refreshNotifier; @override void initState() { _scrollController = ScrollController(); _controller = AnimationController( vsync: this, duration: const Duration(milliseconds: 400), upperBound: 1.0); _pullAnimation = Tween<double>(begin: 1.2, end: 0.0).animate(_controller); _pullAnimation.addListener(() { setState(() { _percentage = _pullAnimation.value; }); }); _model = BasketballGameModel(); _refreshNotifier = ValueNotifier(false); super.initState(); } @override void dispose() { _controller.dispose(); _scrollController.dispose(); _refreshNotifier.dispose(); super.dispose(); } @override Widget build(context) { ScalingInfo.init(MediaQuery.of(context)); // Determine the max height of the pull to refresh area if (_maxHeight == null) { _maxHeight = (MediaQuery.of(context).size.height * 0.325).clamp(0.0, 180.0); } // Build a simple scaffold of the various app components return Column( children: [ ScoresAppBar(), // For triggering the animation detect on start and on end loading NotificationListener<LoadingNotification>( onNotification: _handleLoadingNotification, child: PullToRefreshContainer( maxHeight: _maxHeight, height: _percentage * _maxHeight, refreshNotifier: _refreshNotifier, ), ), // For controlling the scrolling, listen to the scrolling notifications that bubble up from the scroll view NotificationListener<OverscrollIndicatorNotification>( onNotification: _handleOverscrollNotification, child: NotificationListener<ScrollNotification>( onNotification: _handleScrollNotification, child: GameListView( controller: _scrollController, physics: BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics()), model: _model ), ), ) ], ); } bool _handleScrollNotification(ScrollNotification notification) { double deltaOffset = 0.0; if (notification is ScrollEndNotification) { if (!_isLoading) { if (_percentage < 1.05) { _reset(); } else { _refreshNotifier.value = !_refreshNotifier.value; _relax(); } } } if (notification is ScrollUpdateNotification) { if (notification.dragDetails == null && _percentage >= 1.2 && notification.scrollDelta != 0) { _scrollController.jumpTo(_scrollController.offset); } if (notification.scrollDelta > 0.0) { deltaOffset += notification.scrollDelta; } else if (_scrollController.offset < 0) { deltaOffset += notification.scrollDelta; } } if (notification is OverscrollNotification) { if (notification.overscroll < 0.0) { deltaOffset += notification.overscroll; } } if (_percentage > 0.0) { // We are scrolling the ptr area not the view so make sure the view stays static _scrollController.position.correctPixels(0); } _pull(deltaOffset); return false; } Future<void> _pull(double offset) async { // Wait until next event loop to call setState of flutter will yell at you await Future<void>.value(); if (!_isLoading) { setState(() { _percentage += (-offset / _maxHeight); _percentage = _percentage.clamp(0.0, 1.2); }); } } bool _handleOverscrollNotification(OverscrollIndicatorNotification notification) { if (notification.depth != 0 || !notification.leading) return false; notification.disallowGlow(); return false; } bool _handleLoadingNotification(LoadingNotification notification) { if (notification is DoneLoadingNotification) { _reset(); } else { _isLoading = true; } return false; } Future<void> _reset() async { // Wait until next event loop to advance animation and call setState or flutter will yell at you await Future<void>.value(); _controller.forward(from: 1.0 - _percentage * 0.83); if (_isLoading) { setState(() { _model = BasketballGameModel.randomize(); }); } _isLoading = false; } Future<void> _relax() async { await Future<void>.value(); _controller.value = 1.0 - _percentage * 0.83; _controller.animateTo(0.22); } }
0
mirrored_repositories/flutter_showcase/example/apps/dog_slider
mirrored_repositories/flutter_showcase/example/apps/dog_slider/lib/dog_slider.dart
import 'dart:math'; import 'package:dog_slider/dog_flare_controller.dart'; import 'dog_slider_bg_painter.dart'; import 'main.dart'; import 'moving_character_physics_2d.dart'; import 'package:flare_flutter/flare_actor.dart'; import 'package:flare_flutter/flare_controls.dart'; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'bouncing_icon.dart'; class DogSlider extends StatefulWidget { final double arcRadius; final ValueChanged<double> onChanged; final double width; final double hzPadding; final double startValue; const DogSlider({Key key, @required this.onChanged, this.width = 100, this.arcRadius = 15, this.hzPadding = 40, this.startValue = .5}) : super(key: key); @override _DogSliderState createState() => _DogSliderState(); } class _DogSliderState extends State<DogSlider> with TickerProviderStateMixin { static const double _offscreenX = -50; static const double _bottomPadding = 15; AnimationController _ballAnim; double _slidePosX = 230; double _sliderValue = 0; double _dogWidth = 100; Ticker _dogTicker; MovingCharacterPhysics2d _dogPhysics; DogFlareControls _dogController; @override void initState() { //Move slider to start pos _slidePosX = widget.hzPadding + widget.startValue * (widget.width - widget.hzPadding); _sliderValue = widget.startValue; //animationController to handle our ball _ballAnim = AnimationController(vsync: this)..addListener(() => setState(() {})); //Dog controller to handle animations _dogController = DogFlareControls(); //Character physics for dog _dogPhysics = MovingCharacterPhysics2d( //Start dog offscreen startX: _offscreenX, //If value is 0, keep dog offscreen, otherwise, set target to the current slider pos targetX: _sliderValue == 0 ? _offscreenX : _slidePosX, //Play walk anim when moving onMoveStarted: () => _dogController.play("walk"), //play sit animation when we reach our destination onDestinationReached: () => _dogController.play("sit-front"), ); //Use Ticker to redraw view, and update dog physics _dogTicker = Ticker((elapsed) { setState(() => _dogPhysics.update(elapsed)); }); _startDogTicker(); super.initState(); } @override void dispose() { _dogTicker.dispose(); super.dispose(); } @override Widget build(BuildContext context) { double width = max(widget.width, 100.0); double height = 100; double ballSize = widget.arcRadius * 1.35; return GestureDetector( behavior: HitTestBehavior.translucent, onPanUpdate: (_) => _handlePanUpdate(_.localPosition.dx), onPanDown: (_) => handlePanDown(), onPanCancel: () => handlePanEnd(), onPanEnd: (_) => handlePanEnd(), child: Container( width: width, height: height, //color: Colors.red.shade50, child: Stack( children: <Widget>[ //The background lines/floor Positioned( left: 0, child: CustomPaint( foregroundPainter: DogSliderBgPainter( xPos: _slidePosX, arcRadius: widget.arcRadius, arcScaleY: max(0, 1 - _ballAnim.value * 2), bottomPadding: _bottomPadding, ), size: Size(width, height), ), ), //Running dog _buildFlareActor(), //The ball Positioned( bottom: _bottomPadding + 4 + _ballAnim.value * 30, left: _slidePosX - ballSize * .5, width: ballSize, height: ballSize, child: _buildBallAndArrowStack(), ), ], ), ), ); } Widget _buildBallAndArrowStack() { return Stack( children: <Widget>[ Image.asset("images/ball.png", package: App.pkg), Transform.translate( offset: Offset(26, -2), child: BouncingWidget( isVisible: _sliderValue == 0 && _ballAnim.value < .2, child: Icon(Icons.arrow_forward_ios, size: 22, color: Color(0xff174d4c)), ), ), ], ); } Widget _buildFlareActor() { //Set the position of the dog, according to the character physics var dogPosition = _dogPhysics.position; var walkingDog = FlareActor( "packages/dog_slider/assets/DogAnimation.flr", controller: _dogController, fit: BoxFit.fitWidth, alignment: Alignment.bottomCenter, snapToEnd: true, ); return Positioned( bottom: _bottomPadding + 6, left: dogPosition, child: Container( alignment: Alignment.center, //color: Colors.blue, transform: Matrix4.diagonal3Values(_dogPhysics.flipView ? -1 : 1, 1, 1), width: _dogWidth, height: _dogWidth, child: Transform( child: walkingDog, //Offset the dog half-way on the X, so it's center-aligned when flipping transform: Matrix4.translationValues(-_dogWidth * .5, 0, 0), ), ), ); } void _handlePanUpdate(double xPos) { //Ff ticker is not going, fire it up if (!_dogTicker.isTicking) { _dogTicker.start(); } //calculate current xPos and dispatch change events setState(() { //Inject targetX into dogPhysics _slidePosX = xPos.clamp(widget.hzPadding, widget.width - widget.hzPadding); _sliderValue = (_slidePosX - widget.hzPadding) / (widget.width - widget.hzPadding * 2); if (widget.onChanged != null) { widget.onChanged(_sliderValue); } _dogPhysics.targetX = _sliderValue == 0 ? _offscreenX : _slidePosX; }); } void handlePanDown() { _ballAnim.animateTo(1, duration: Duration(milliseconds: 300), curve: Curves.easeOutBack); } void handlePanEnd() { _ballAnim.animateTo(0, duration: Duration(milliseconds: 600), curve: ElasticOutCurve(.3)); } void _startDogTicker() async { await Future.delayed(Duration(milliseconds: 500)); _dogTicker.start(); } }
0
mirrored_repositories/flutter_showcase/example/apps/dog_slider
mirrored_repositories/flutter_showcase/example/apps/dog_slider/lib/moving_character_physics_2d.dart
import 'dart:ui'; class MovingCharacterPhysics2d { double get position => _x; bool get flipView => _flipView; bool get atDestination => _atDestination; Function onDestinationReached; Function onMoveStarted; double targetX; double acc; double maxSpeed; double friction; double chaseDelay; double stopDistance; double _x = 50; double _vel = 0; bool _canChase = false; bool _flipView = false; bool _atDestination = true; double _lastTickTime = 0; int _lastArrivalTime = 0; MovingCharacterPhysics2d( {startX, this.targetX = 100, this.onDestinationReached, this.onMoveStarted, this.acc = .3, this.maxSpeed = 3.5, this.friction = .11, this.chaseDelay = 0, this.stopDistance = 30}) { _x = startX ?? 0; } void update(Duration elapsed) { //Update internal state _canChase = _getElapsed(_lastArrivalTime) > chaseDelay; //Tick physics double t = elapsed.inMicroseconds * 1.0e-6; if (_lastTickTime == null) { _lastTickTime = t; } _updatePhysics(t - _lastTickTime); _lastTickTime = t; } void _updatePhysics(double dt) { //Apply velocity _x += _vel * dt * 60; //Apply friction _vel *= (1 - friction); //If we're not close to our target, accelerate towards it if (_canChase && (_x - targetX).abs() > stopDistance) { if (_atDestination && onMoveStarted != null) { onMoveStarted(); } _atDestination = false; //Accelerate //print(_vel); var dir = (targetX - _x).sign; _vel += acc * dir; // * dt * 60; //Make sure we don't exceed topSpeed if (_vel.abs() > maxSpeed) { _vel = maxSpeed * _vel.sign; } _flipView = _vel < 0; } //Zero-out velocity when it gets too small if (_vel.abs() < .1) { _vel = 0; } if (!_atDestination && _vel == 0 && _canChase) { _atDestination = true; _lastArrivalTime = DateTime.now().millisecondsSinceEpoch; if (onDestinationReached != null) { onDestinationReached(); } } } int _getElapsed(int value) { return DateTime.now().millisecondsSinceEpoch - value; } }
0
mirrored_repositories/flutter_showcase/example/apps/dog_slider
mirrored_repositories/flutter_showcase/example/apps/dog_slider/lib/bouncing_icon.dart
import 'package:flutter/material.dart'; class BouncingWidget extends StatefulWidget { final bool isVisible; final Widget child; final double maxBounce; const BouncingWidget({Key key, this.isVisible, this.child, this.maxBounce = 20}) : super(key: key); @override _BouncingWidgetState createState() => _BouncingWidgetState(); } class _BouncingWidgetState extends State<BouncingWidget> { double _offsetY = 0; Duration _bounceDuration = Duration(milliseconds: 700); Curve _bounceCurve = Curves.easeOut; @override void initState() { _bounceIcon(true); super.initState(); } void _bounceIcon(bool up) async { _bounceCurve = up? Curves.easeOut : Curves.easeIn; setState(() => _offsetY = up? 0 : 20); await Future.delayed(_bounceDuration); if(mounted){ _bounceIcon(!up); } } @override Widget build(BuildContext context) { return AnimatedOpacity( opacity: widget.isVisible? 1 : 0, duration: Duration(milliseconds: 350), child: TweenAnimationBuilder( tween: Tween<double>(begin: 0, end: _offsetY), curve: _bounceCurve, duration: _bounceDuration, builder: (context, value, child) { return Transform.translate( offset: Offset(value, 0), child: widget.child, ); }, ), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/dog_slider
mirrored_repositories/flutter_showcase/example/apps/dog_slider/lib/dog_slider_bg_painter.dart
import 'package:flutter/material.dart'; class DogSliderBgPainter extends CustomPainter { final double xPos; final double arcScaleY; final double arcRadius; final double bottomPadding; DogSliderBgPainter({ this.xPos = 230, this.arcScaleY = 1, this.arcRadius = 20, this.bottomPadding = 10, }); @override void paint(Canvas canvas, Size size) { var arcHeight = arcScaleY * arcRadius; var lineY = size.height - arcRadius - bottomPadding; var strokeWidth = 4.0; var paint = Paint() ..style = PaintingStyle.stroke ..strokeWidth = strokeWidth ..color = Color(0xff357171); var radius = Radius.elliptical(arcRadius, arcHeight); bool arcClockwise = arcHeight.sign < 0; //Paint accent portion of line var path = Path(); path.moveTo(0, lineY); path.lineTo(xPos - arcRadius, lineY); path.arcToPoint(Offset(xPos, lineY + arcHeight), radius: radius, clockwise: arcClockwise); canvas.drawPath(path, paint); //Paint grey portion of line paint.color = Color(0xffd1d0da); path = Path(); path.moveTo(xPos, lineY + arcHeight); path.arcToPoint(Offset(xPos + arcRadius, lineY), radius: radius, clockwise: arcClockwise); path.lineTo(size.width, lineY); canvas.drawPath(path, paint); } @override bool shouldRepaint(CustomPainter oldDelegate) { var oldPainter = (oldDelegate as DogSliderBgPainter); return oldPainter.xPos != xPos || oldPainter.arcScaleY != arcScaleY; } }
0
mirrored_repositories/flutter_showcase/example/apps/dog_slider
mirrored_repositories/flutter_showcase/example/apps/dog_slider/lib/main.dart
import 'package:flutter/material.dart'; import 'package:shared/env.dart'; import 'demo.dart'; void main() => runApp(App()); class App extends StatelessWidget { static String _pkg = "dog_slider"; static String get pkg => Env.getPackage(_pkg); @override Widget build(BuildContext context) { return MaterialApp( home: DogSliderDemo() ); } }
0
mirrored_repositories/flutter_showcase/example/apps/dog_slider
mirrored_repositories/flutter_showcase/example/apps/dog_slider/lib/demo.dart
import 'dog_slider.dart'; import 'package:flutter/material.dart'; import 'main.dart'; class DogSliderDemo extends StatefulWidget { @override _DogSliderDemoState createState() => _DogSliderDemoState(); } class _DogSliderDemoState extends State<DogSliderDemo> { static const darkGreen = Color(0xff174d4c); TextStyle baseStyle = TextStyle(fontFamily: "Quicksand", package: App.pkg); int _numTreats = 0; int _maxTreats = 10; double _maxContentWidth = 500; void _handleSliderChanged(double value) { setState(() { _numTreats = ((value * _maxTreats)).round(); }); } @override Widget build(BuildContext context) { var size = MediaQuery.of(context).size; return SafeArea( child: Scaffold( body: Container( //padding: const EdgeInsets.all(8.0), child: Column( children: <Widget>[ _buildTopNav(), SizedBox(height: 20), Expanded( child: Stack( fit: StackFit.expand, children: <Widget>[ _buildBackground(40), _buildTopContent(), Center( child: DogSlider( startValue: _numTreats / _maxTreats, onChanged: _handleSliderChanged, width: size.width, ), ), _buildBottomContent(), ], ), ), _buildBottomMenu(), ], ), ), ), ); } Align _buildBottomContent() { double contentFontSize = 13; return Align( alignment: Alignment.bottomCenter, child: FractionallySizedBox( heightFactor: .5, child: Container( width: _maxContentWidth, padding: EdgeInsets.only(top: 40, bottom: 40, left: 26, right: 26), child: Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text("PRODUCT DETAIL", style: baseStyle.copyWith(fontSize: 14, fontWeight: FontWeight.w600)), SizedBox(height: 12), Text("Fetch Tennis Ball - 2.0 inch", style: baseStyle.copyWith(fontSize: contentFontSize, fontWeight: FontWeight.bold)), SizedBox(height: 12), Text("Colour: Green", style: baseStyle.copyWith(fontSize: contentFontSize)), Text("Size: 2.5 inch", style: baseStyle.copyWith(fontSize: contentFontSize)), SizedBox(height: 12), Text( "For stimulating playtime that encouages pets to leap and chase. Made from a high-quality natural latex and designed for the game of fetch. ", style: baseStyle.copyWith(fontSize: contentFontSize)), ], ), ), ), ); } Container _buildTopContent() { return Container( width: 400, padding: EdgeInsets.symmetric(horizontal: 32), child: Column( children: <Widget>[ Text("How many fetch balls\ndoes your dog want?", textAlign: TextAlign.center, style: baseStyle.copyWith(fontSize: 26, fontWeight: FontWeight.w300)), SizedBox( height: 24, ), Text(_numTreats.toString(), textAlign: TextAlign.center, style: baseStyle.copyWith(fontSize: 48, color: Color(0xff00a6a4), fontWeight: FontWeight.w600)) ], ), ); } Container _buildBottomMenu() { return Container( padding: EdgeInsets.symmetric(horizontal: 22), height: 100, width: double.infinity, decoration: BoxDecoration(color: Colors.white, boxShadow: [BoxShadow(color: Colors.black.withOpacity(.1), blurRadius: 20)]), child: Center( child: Container( width: _maxContentWidth, child: Row( children: <Widget>[ Text("TOTAL", style: baseStyle.copyWith(fontSize: 16)), SizedBox( width: 6, ), Text("\$${_numTreats * 6} CAD", style: baseStyle.copyWith(fontSize: 16, fontWeight: FontWeight.bold)), Expanded( child: SizedBox(), ), _buildAddToCartBtn() ], ), ), ), ); } FlatButton _buildAddToCartBtn() { return FlatButton( color: Color(0xff2cb5b5), shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), padding: EdgeInsets.symmetric(horizontal: 32, vertical: 16), child: Text("ADD TO CART", style: baseStyle.copyWith(fontSize: 16, color: Colors.white)), onPressed: () {}, ); } Widget _buildTopNav() { return Container( padding: EdgeInsets.all(12), //color: Colors.green, child: Row( children: <Widget>[ IconButton( icon: Icon( Icons.keyboard_backspace, color: darkGreen, ), iconSize: 32, onPressed: () {}), Expanded( child: Container( child: Image.asset("images/logo.png", fit: BoxFit.fitHeight, height: 26, package: App.pkg), ), ), IconButton( icon: Icon( Icons.shopping_basket, color: darkGreen, ), iconSize: 32, onPressed: () {}), ], ), ); } Widget _buildBackground(double topPadding) { double topFraction = .5; return Padding( padding: EdgeInsets.only(top: topPadding), child: Stack( children: <Widget>[ FractionallySizedBox( heightFactor: topFraction, child: Align( alignment: Alignment.bottomCenter, child: Image.asset("images/background.png", height: 150, fit: BoxFit.fitHeight, package: App.pkg), ), ), Align( alignment: Alignment.bottomCenter, child: FractionallySizedBox( heightFactor: 1 - topFraction, child: Align( alignment: Alignment(0, -.8), child: Image.asset("images/ground.png", fit: BoxFit.fitHeight, height: 80, package: App.pkg), ), ), ) ], ), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/dog_slider
mirrored_repositories/flutter_showcase/example/apps/dog_slider/lib/dog_flare_controller.dart
import 'package:flare_flutter/flare.dart'; import 'package:flare_flutter/flare_actor.dart'; import 'package:flare_flutter/flare_controller.dart'; import 'package:flare_dart/math/mat2d.dart'; //A simple FlareController that does not worry about mixing, and only plays a single layer at a time. class DogFlareControls extends FlareController { Function(String) onCompleted; FlutterActorArtboard _artBoard; FlareAnimationLayer _animationLayer; String _animationName; @override void initialize(FlutterActorArtboard artBoard) { _artBoard = artBoard; } // Create new animation, and assign it as current void play(String name) { _animationName = name; //Exit early if name or artboard are null if (_animationName == null || _artBoard == null) return; //Check if animation actually exists ActorAnimation animation = _artBoard.getAnimation(_animationName); if (animation != null) { //If all is good, start new animation _animationLayer = FlareAnimationLayer() ..name = _animationName ..animation = animation; isActive.value = true; } } // Advance animation and call onComplete when a non-looping anim has finished. @override bool advance(FlutterActorArtboard artboard, double elapsed) { if(_animationLayer == null){ return false; } FlareAnimationLayer layer = _animationLayer; layer.time += elapsed; //Loop? if (layer.animation.isLooping) { layer.time %= layer.animation.duration; } //Advance animation, with full mix layer.animation.apply(layer.time, _artBoard, 1); //Remove anim if it's complete if (layer.time > layer.animation.duration) { //Stop animation from playing _animationLayer = null; if (onCompleted != null) { onCompleted(layer.animation.name); } } return _animationLayer != null; } @override void setViewTransform(Mat2D viewTransform) {} }
0
mirrored_repositories/flutter_showcase/example/apps/ticket_fold
mirrored_repositories/flutter_showcase/example/apps/ticket_fold/lib/flight_summary.dart
import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; import 'demo_data.dart'; import 'main.dart'; enum SummaryTheme { dark, light } class FlightSummary extends StatelessWidget { final BoardingPassData boardingPass; final SummaryTheme theme; final bool isOpen; const FlightSummary({Key key, this.boardingPass, this.theme = SummaryTheme.light, this.isOpen = false}) : super(key: key); Color get mainTextColor { Color textColor; if (theme == SummaryTheme.dark) textColor = Colors.white; if (theme == SummaryTheme.light) textColor = Color(0xFF083e64); return textColor; } Color get secondaryTextColor { Color textColor; if (theme == SummaryTheme.dark) textColor = Color(0xff61849c); if (theme == SummaryTheme.light) textColor = Color(0xFF838383); return textColor; } Color get separatorColor { Color color; if (theme == SummaryTheme.light) color = Color(0xffeaeaea); if (theme == SummaryTheme.dark) color = Color(0xff396583); return color; } TextStyle get bodyTextStyle => TextStyle(color: mainTextColor, fontSize: 13, fontFamily: 'Oswald', package: App.pkg); @override Widget build(BuildContext context) { return Container( decoration: _getBackgroundDecoration(), width: double.infinity, height: double.infinity, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 16.0), child: Column( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ _buildLogoHeader(), _buildSeparationLine(), _buildTicketHeader(context), Padding( padding: const EdgeInsets.symmetric(horizontal: 18.0), child: Stack( children: <Widget>[ Align(alignment: Alignment.centerLeft, child: _buildTicketOrigin()), Align(alignment: Alignment.center, child: _buildTicketDuration()), Align(alignment: Alignment.centerRight, child: _buildTicketDestination()) ], ), ), _buildBottomIcon() ], ), ), ); } _getBackgroundDecoration() { if (theme == SummaryTheme.light) return BoxDecoration( borderRadius: BorderRadius.circular(4.0), color: Colors.white, ); if (theme == SummaryTheme.dark) return BoxDecoration( borderRadius: BorderRadius.circular(4.0), image: DecorationImage(image: AssetImage('images/bg_blue.png', package: App.pkg), fit: BoxFit.cover), ); } _buildLogoHeader() { if (theme == SummaryTheme.light) return Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Padding( padding: const EdgeInsets.symmetric(horizontal: 4.0), child: Image.asset('images/flutter-logo.png', width: 8, package: App.pkg), ), Text('Fluttair'.toUpperCase(), style: TextStyle( color: mainTextColor, fontFamily: 'OpenSans', fontSize: 10, fontWeight: FontWeight.bold, letterSpacing: 1.5, package: App.pkg)) ], ); if (theme == SummaryTheme.dark) return Padding( padding: const EdgeInsets.only(top: 2.0), child: Image.asset('images/logo_white.png', height: 12, package: App.pkg), ); } Widget _buildSeparationLine() { return Container( width: double.infinity, height: 1, color: separatorColor, ); } Widget _buildTicketHeader(context) { var headerStyle = TextStyle(fontFamily: 'OpenSans', fontWeight: FontWeight.bold, fontSize: 11, color: Color(0xFFe46565), package: App.pkg); return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Text(boardingPass.passengerName.toUpperCase(), style: headerStyle), Text('BOARDING ${boardingPass.boardingTime.format(context)}', style: headerStyle), ], ); } Widget _buildTicketOrigin() { return Column( children: <Widget>[ Text( boardingPass.origin.code.toUpperCase(), style: bodyTextStyle.copyWith(fontSize: 42), ), Text(boardingPass.origin.city, style: bodyTextStyle.copyWith(color: secondaryTextColor)), ], ); } Widget _buildTicketDuration() { String planeRoutePath; if (theme == SummaryTheme.light) planeRoutePath = 'images/planeroute_blue.png'; if (theme == SummaryTheme.dark) planeRoutePath = 'images/planeroute_white.png'; return Container( child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ Container( width: 120, height: 58, child: Stack( alignment: Alignment.center, children: <Widget>[ Image.asset(planeRoutePath, fit: BoxFit.cover, package: App.pkg), if (theme == SummaryTheme.light) Image.asset('images/airplane_blue.png', height: 20, fit: BoxFit.contain, package: App.pkg), if (theme == SummaryTheme.dark) _AnimatedSlideToRight( child: Image.asset('images/airplane_white.png', height: 20, fit: BoxFit.contain, package: App.pkg), isOpen: isOpen, ) ], ), ), Text(boardingPass.duration.toString(), textAlign: TextAlign.center, style: bodyTextStyle), ], ), ); } Widget _buildTicketDestination() { return Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( boardingPass.destination.code.toUpperCase(), style: bodyTextStyle.copyWith(fontSize: 42), ), Text( boardingPass.destination.city, style: bodyTextStyle.copyWith(color: secondaryTextColor), ), ], ); } Widget _buildBottomIcon() { IconData icon; if (theme == SummaryTheme.light) icon = Icons.keyboard_arrow_down; if (theme == SummaryTheme.dark) icon = Icons.keyboard_arrow_up; return Icon( icon, color: mainTextColor, size: 18, ); } } class _AnimatedSlideToRight extends StatefulWidget { final Widget child; final bool isOpen; const _AnimatedSlideToRight({Key key, this.child, @required this.isOpen}) : super(key: key); @override _AnimatedSlideToRightState createState() => _AnimatedSlideToRightState(); } class _AnimatedSlideToRightState extends State<_AnimatedSlideToRight> with SingleTickerProviderStateMixin { AnimationController _controller; @override void initState() { super.initState(); _controller = AnimationController(vsync: this, duration: Duration(milliseconds: 1700)); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { if (widget.isOpen) _controller.forward(from: 0); return SlideTransition( position: Tween(begin: Offset(-2, 0), end: Offset(1, 0)).animate(CurvedAnimation(curve: Curves.easeOutQuad, parent: _controller)), child: widget.child, ); } }
0
mirrored_repositories/flutter_showcase/example/apps/ticket_fold
mirrored_repositories/flutter_showcase/example/apps/ticket_fold/lib/flight_barcode.dart
import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; import 'main.dart'; class FlightBarcode extends StatelessWidget { @override Widget build(BuildContext context) => Container( width: double.infinity, decoration: BoxDecoration(borderRadius: BorderRadius.circular(4.0), color: Colors.white), child: Padding( padding: const EdgeInsets.symmetric(vertical: 14.0), child: MaterialButton( child: Image.asset('images/barcode.png', package: App.pkg), onPressed: () { print('Button was pressed'); }), )); }
0
mirrored_repositories/flutter_showcase/example/apps/ticket_fold
mirrored_repositories/flutter_showcase/example/apps/ticket_fold/lib/demo_data.dart
import 'package:flutter/material.dart'; class BoardingPassData { String passengerName; _Airport origin; _Airport destination; _Duration duration; TimeOfDay boardingTime; DateTime departs; DateTime arrives; String gate; int zone; String seat; String flightClass; String flightNumber; BoardingPassData({ this.passengerName, this.origin, this.destination, this.duration, this.boardingTime, this.departs, this.arrives, this.gate, this.zone, this.seat, this.flightClass, this.flightNumber, }); } class _Airport { String code; String city; _Airport({this.city, this.code}); } class _Duration { int hours; int minutes; _Duration({this.hours, this.minutes}); @override String toString() { return '\t${hours}H ${minutes}M'; } } class DemoData { List<BoardingPassData> _boardingPasses = [ BoardingPassData( passengerName: 'Ms. Jane Doe', origin: _Airport(code: 'YEG', city: 'Edmonton'), destination: _Airport(code: 'LAX', city: 'Los Angeles'), duration: _Duration(hours: 3, minutes: 30), boardingTime: TimeOfDay(hour: 7, minute: 10), departs: DateTime(2019, 10, 17, 23, 45), arrives: DateTime(2019, 10, 18, 02, 15), gate: '50', zone: 3, seat: '12A', flightClass: 'Economy', flightNumber: 'AC237'), BoardingPassData( passengerName: 'Ms. Jane Doe', origin: _Airport(code: 'YYC', city: 'Calgary'), destination: _Airport(code: 'YOW', city: 'Ottawa'), duration: _Duration(hours: 3, minutes: 50), boardingTime: TimeOfDay(hour: 12, minute: 15), departs: DateTime(2019, 10, 17, 23, 45), arrives: DateTime(2019, 10, 18, 02, 15), gate: '22', zone: 1, seat: '17C', flightClass: 'Economy', flightNumber: 'AC237'), BoardingPassData( passengerName: 'Ms. Jane Doe', origin: _Airport(code: 'YEG', city: 'Edmonton'), destination: _Airport(code: 'MEX', city: 'Mexico'), duration: _Duration(hours: 4, minutes: 15), boardingTime: TimeOfDay(hour: 16, minute: 45), departs: DateTime(2019, 10, 17, 23, 45), arrives: DateTime(2019, 10, 18, 02, 15), gate: '30', zone: 2, seat: '22B', flightClass: 'Economy', flightNumber: 'AC237'), BoardingPassData( passengerName: 'Ms. Jane Doe', origin: _Airport(code: 'YYC', city: 'Calgary'), destination: _Airport(code: 'YOW', city: 'Ottawa'), duration: _Duration(hours: 3, minutes: 50), boardingTime: TimeOfDay(hour: 12, minute: 15), departs: DateTime(2019, 10, 17, 23, 45), arrives: DateTime(2019, 10, 18, 02, 15), gate: '22', zone: 1, seat: '17C', flightClass: 'Economy', flightNumber: 'AC237'), ]; get boardingPasses => _boardingPasses; getBoardingPass(int index) { return _boardingPasses.elementAt(index); } }
0
mirrored_repositories/flutter_showcase/example/apps/ticket_fold
mirrored_repositories/flutter_showcase/example/apps/ticket_fold/lib/ticket.dart
import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; import 'demo_data.dart'; import 'flight_barcode.dart'; import 'flight_details.dart'; import 'flight_summary.dart'; import 'folding_ticket.dart'; class Ticket extends StatefulWidget { static const double nominalOpenHeight = 400; static const double nominalClosedHeight = 160; final BoardingPassData boardingPass; final Function onClick; const Ticket({Key key, @required this.boardingPass, @required this.onClick}) : super(key: key); @override State<StatefulWidget> createState() => _TicketState(); } class _TicketState extends State<Ticket> { FlightSummary frontCard; FlightSummary topCard; FlightDetails middleCard; FlightBarcode bottomCard; bool _isOpen; Widget get backCard => Container(decoration: BoxDecoration(borderRadius: BorderRadius.circular(4.0), color: Color(0xffdce6ef))); @override void initState() { super.initState(); _isOpen = false; frontCard = FlightSummary(boardingPass: widget.boardingPass); middleCard = FlightDetails(widget.boardingPass); bottomCard = FlightBarcode(); } @override Widget build(BuildContext context) { return FoldingTicket(entries: _getEntries(), isOpen: _isOpen, onClick: _handleOnTap); } List<FoldEntry> _getEntries() { return [ FoldEntry(height: 160.0, front: topCard), FoldEntry(height: 160.0, front: middleCard, back: frontCard), FoldEntry(height: 80.0, front: bottomCard, back: backCard) ]; } void _handleOnTap() { widget.onClick(); setState(() { _isOpen = !_isOpen; topCard = FlightSummary(boardingPass: widget.boardingPass, theme: SummaryTheme.dark, isOpen: _isOpen); }); } }
0
mirrored_repositories/flutter_showcase/example/apps/ticket_fold
mirrored_repositories/flutter_showcase/example/apps/ticket_fold/lib/main.dart
import 'package:flutter/material.dart'; import 'package:shared/env.dart'; import 'demo.dart'; void main() => runApp(App()); class App extends StatelessWidget { static String _pkg = "ticket_fold"; static String get pkg => Env.getPackage(_pkg); @override Widget build(BuildContext context) { const title = 'Ticket Fold Demo'; return MaterialApp( title: title, home: TicketFoldDemo(), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/ticket_fold
mirrored_repositories/flutter_showcase/example/apps/ticket_fold/lib/demo.dart
import 'dart:math'; import 'package:flutter/material.dart'; import 'demo_data.dart'; import 'main.dart'; import 'ticket.dart'; class TicketFoldDemo extends StatefulWidget { @override _TicketFoldDemoState createState() => _TicketFoldDemoState(); } class _TicketFoldDemoState extends State<TicketFoldDemo> { final List<BoardingPassData> _boardingPasses = DemoData().boardingPasses; final Color _backgroundColor = Color(0xFFf0f0f0); final ScrollController _scrollController = ScrollController(); final List<int> _openTickets = []; @override Widget build(BuildContext context) { return Scaffold( backgroundColor: _backgroundColor, appBar: _buildAppBar(), body: Container( child: Flex(direction: Axis.vertical, children: <Widget>[ Expanded( child: ListView.builder( controller: _scrollController, physics: BouncingScrollPhysics(), itemCount: _boardingPasses.length, itemBuilder: (BuildContext context, int index) { return Ticket( boardingPass: _boardingPasses.elementAt(index), onClick: () => _handleClickedTicket(index), ); }, ), ), ]), ), ); } bool _handleClickedTicket(int clickedTicket) { // Scroll to ticket position // Add or remove the item of the list of open tickets _openTickets.contains(clickedTicket) ? _openTickets.remove(clickedTicket) : _openTickets.add(clickedTicket); // Calculate heights of the open and closed elements before the clicked item double openTicketsOffset = Ticket.nominalOpenHeight * _getOpenTicketsBefore(clickedTicket); double closedTicketsOffset = Ticket.nominalClosedHeight * (clickedTicket - _getOpenTicketsBefore(clickedTicket)); double offset = openTicketsOffset + closedTicketsOffset - (Ticket.nominalClosedHeight * .5); // Scroll to the clicked element _scrollController.animateTo(max(0, offset), duration: Duration(seconds: 1), curve: Interval(.25, 1, curve: Curves.easeOutQuad)); // Return true to stop the notification propagation return true; } _getOpenTicketsBefore(int ticketIndex) { // Search all indexes that are smaller to the current index in the list of indexes of open tickets return _openTickets.where((int index) => index < ticketIndex).length; } Widget _buildAppBar() { Color appBarIconsColor = Color(0xFF212121); return AppBar( leading: Icon(Icons.arrow_back, color: appBarIconsColor), actions: <Widget>[ Padding( padding: const EdgeInsets.only(right: 18.0), child: Icon(Icons.more_horiz, color: appBarIconsColor, size: 28), ) ], brightness: Brightness.light, backgroundColor: _backgroundColor, elevation: 0, title: Container( width: double.infinity, alignment: Alignment.center, child: Text('Boarding Passes'.toUpperCase(), textAlign: TextAlign.center, style: TextStyle(fontSize: 15, letterSpacing: 0.5, color: appBarIconsColor, fontFamily: 'OpenSans', fontWeight: FontWeight.bold, package: App.pkg)), ), ); } }
0
mirrored_repositories/flutter_showcase/example/apps/ticket_fold
mirrored_repositories/flutter_showcase/example/apps/ticket_fold/lib/flight_details.dart
import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'demo_data.dart'; import 'main.dart'; class FlightDetails extends StatelessWidget { final BoardingPassData boardingPass; final TextStyle titleTextStyle = TextStyle( fontFamily: 'OpenSans', fontSize: 11, height: 1, letterSpacing: .2, fontWeight: FontWeight.w600, color: Color(0xffafafaf), package: App.pkg); final TextStyle contentTextStyle = TextStyle(fontFamily: 'Oswald', fontSize: 16, height: 1.8, letterSpacing: .3, color: Color(0xff083e64), package: App.pkg); FlightDetails(this.boardingPass); @override Widget build(BuildContext context) => Container( decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(4.0), ), width: double.infinity, height: double.infinity, child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ Column(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text('Gate'.toUpperCase(), style: titleTextStyle), Text(boardingPass.gate, style: contentTextStyle), ]), Column(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text('Zone'.toUpperCase(), style: titleTextStyle), Text(boardingPass.zone.toString(), style: contentTextStyle), ]), Column(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text('Seat'.toUpperCase(), style: titleTextStyle), Text(boardingPass.seat, style: contentTextStyle), ]), Column(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text('Class'.toUpperCase(), style: titleTextStyle), Text(boardingPass.flightClass, style: contentTextStyle), ]), ], ), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ Column(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text('Flight'.toUpperCase(), style: titleTextStyle), Text(boardingPass.flightNumber, style: contentTextStyle), ]), Column(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text('Departs'.toUpperCase(), style: titleTextStyle), Text(DateFormat('MMM d, H:mm').format(boardingPass.departs).toUpperCase(), style: contentTextStyle), ]), Column(crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text('Arrives'.toUpperCase(), style: titleTextStyle), Text(DateFormat('MMM d, H:mm').format(boardingPass.arrives).toUpperCase(), style: contentTextStyle) ]), ], ), ], ), ); }
0
mirrored_repositories/flutter_showcase/example/apps/ticket_fold
mirrored_repositories/flutter_showcase/example/apps/ticket_fold/lib/folding_ticket.dart
import 'dart:math'; import 'package:flutter/material.dart'; class FoldingTicket extends StatefulWidget { static const double padding = 16.0; final bool isOpen; final List<FoldEntry> entries; final Function onClick; final Duration duration; FoldingTicket({this.duration, @required this.entries, this.isOpen = false, this.onClick}); @override _FoldingTicketState createState() => _FoldingTicketState(); } class _FoldingTicketState extends State<FoldingTicket> with SingleTickerProviderStateMixin { List<FoldEntry> _entries; double _ratio = 0.0; AnimationController _controller; double get openHeight => _entries.fold(0.0, (val, o) => val + o.height) + FoldingTicket.padding * 2; double get closedHeight => _entries[0].height + FoldingTicket.padding * 2; bool get isOpen => widget.isOpen; @override void initState() { super.initState(); _controller = AnimationController(vsync: this); _controller.addListener(_tick); _updateFromWidget(); } @override void didUpdateWidget(FoldingTicket oldWidget) { // Opens or closes the ticked if the status changed _updateFromWidget(); super.didUpdateWidget(oldWidget); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Container( padding: EdgeInsets.all(FoldingTicket.padding), height: closedHeight + (openHeight - closedHeight) * Curves.easeOut.transform(_ratio), child: Container( decoration: BoxDecoration( boxShadow: [BoxShadow(color: Colors.black.withOpacity(.1), blurRadius: 10, spreadRadius: 1)], ), child: _buildEntry(0)), ); } Widget _buildEntry(int index) { FoldEntry entry = _entries[index]; int count = _entries.length - 1; double ratio = max(0.0, min(1.0, _ratio * count + 1.0 - index * 1.0)); Matrix4 mtx = Matrix4.identity() ..setEntry(3, 2, 0.001) ..setEntry(1, 2, 0.2) ..rotateX(pi * (ratio - 1.0)); Widget card = SizedBox(height: entry.height, child: ratio < 0.5 ? entry.back : entry.front); return Transform( alignment: Alignment.topCenter, transform: mtx, child: GestureDetector( onTap: widget.onClick, child: SingleChildScrollView( physics: NeverScrollableScrollPhysics(), // Note: Container supports a transform property, but not alignment for it. child: (index == count || ratio <= 0.5) ? card : // Don't build a stack if it isn't needed. Column(children: [ card, _buildEntry(index + 1), ]), ), )); } void _updateFromWidget() { _entries = widget.entries; _controller.duration = widget.duration ?? Duration(milliseconds: 400 * (_entries.length - 1)); isOpen ? _controller.forward() : _controller.reverse(); } void _tick() { setState(() { _ratio = Curves.easeInQuad.transform(_controller.value); }); } } class FoldEntry { final Widget front; Widget back; final double height; FoldEntry({@required this.front, @required this.height, Widget back}) { this.back = Transform( alignment: FractionalOffset.center, transform: Matrix4.identity() ..setEntry(3, 2, .001) ..rotateX(pi), child: back); } }
0
mirrored_repositories/Flutter-Portfolio
mirrored_repositories/Flutter-Portfolio/lib/main.dart
import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'package:flutter_portfolio/Views/home.dart'; void main() async{ WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(MyApp()); } class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Onkar Shaligram', debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.blue, ), home: Home(), ); } }
0
mirrored_repositories/Flutter-Portfolio/lib
mirrored_repositories/Flutter-Portfolio/lib/Views/projects.dart
import 'package:flutter/material.dart'; import 'package:flutter_portfolio/Helpers/Media_query.dart'; import 'package:flutter_portfolio/Helpers/projectView.dart'; import 'package:flutter_portfolio/Helpers/projects_helper.dart'; class Projects extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( iconTheme: IconThemeData( color: Colors.black, ), title: Center( child: Text( "Projects", style: TextStyle(color: Colors.black), )), backgroundColor: Colors.white, ), body: MediaQuerys( largeScreen: Container( decoration: BoxDecoration( color: Color(0xff333340), ), child: GridView.count( padding: EdgeInsets.all(16.0), crossAxisCount: 3, childAspectRatio: MediaQuery.of(context).size.width / (MediaQuery.of(context).size.height / 1.3), children: List.generate( projects.length, (index) => ProjectView(project: projects[index],)), ), ), mediumScreen: Container( decoration: BoxDecoration( color: Color(0xff333340), ), child: ListView.builder( itemCount: projects.length, itemBuilder: (context, index) => ProjectView( project: projects[index], ) ) ), smallScreen: Container( decoration: BoxDecoration( color: Color(0xff333340), ), child: ListView.builder( itemCount: projects.length, itemBuilder: (context, index) => ProjectView( project: projects[index], ) ) ), ), ); } }
0
mirrored_repositories/Flutter-Portfolio/lib
mirrored_repositories/Flutter-Portfolio/lib/Views/contact_me.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:flutter_portfolio/Helpers/Media_query.dart'; import 'package:flutter_portfolio/Helpers/constants.dart'; class ContactMe extends StatefulWidget { @override _ContactMeState createState() => _ContactMeState(); } class _ContactMeState extends State<ContactMe> { TextEditingController nameEditingController = TextEditingController(); TextEditingController emailEditingController = TextEditingController(); TextEditingController subjectEditingController = TextEditingController(); TextEditingController messageEditingController = TextEditingController(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( iconTheme: IconThemeData( color: Colors.black, ), title: Center( child: Text( "Contact Me", style: TextStyle(color: Colors.black), )), backgroundColor: Colors.white, ), body: MediaQuerys( largeScreen: Container( color: Color(0xff333340), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 150.0, vertical: 50), child: Column( mainAxisAlignment: MainAxisAlignment.start, children: [ Text( "I am ready for Freelance Work and Collaborations", style: TextStyle( color: Colors.white, fontSize: 30, fontWeight: FontWeight.w500), ), SizedBox( height: 60, ), TextField( maxLines: 1, controller: nameEditingController, decoration: InputDecoration( filled: true, fillColor: Colors.white70, hintText: "Name", hintStyle: TextStyle(color: Colors.black), border: InputBorder.none), ), SizedBox( height: 10, ), TextField( maxLines: 1, controller: emailEditingController, decoration: InputDecoration( filled: true, fillColor: Colors.white70, hintText: "Email", hintStyle: TextStyle(color: Colors.black), border: InputBorder.none), ), SizedBox( height: 10, ), TextField( maxLines: 2, controller: subjectEditingController, decoration: InputDecoration( filled: true, fillColor: Colors.white70, hintText: "Subject", hintStyle: TextStyle(color: Colors.black), border: InputBorder.none), ), SizedBox( height: 10, ), TextField( maxLines: 5, controller: messageEditingController, decoration: InputDecoration( filled: true, fillColor: Colors.white70, hintText: "Message", hintStyle: TextStyle(color: Colors.black), border: InputBorder.none), ), SizedBox( height: 10, ), MaterialButton( onPressed: () async { await FirebaseFirestore.instance .collection("forms") .doc(uploadTime) .set({ 'name': nameEditingController.text, 'email': emailEditingController.text, 'subject': subjectEditingController.text, 'message': messageEditingController.text, 'uploadTime': uploadTime }).catchError((onError) { print(onError); }).whenComplete(() { setState(() { nameEditingController.text = emailEditingController.text = subjectEditingController.text = messageEditingController.text = ""; }); }); }, height: 60, minWidth: double.infinity, color: Colors.white, child: Text("Submit"), ) ], ), ), ), smallScreen: Container( color: Color(0xff333340), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 50), child: Column( mainAxisAlignment: MainAxisAlignment.start, children: [ Text( "I am ready for Freelance Work and Collaborations", style: TextStyle( color: Colors.white, fontSize: 30, fontWeight: FontWeight.w500), ), SizedBox( height: 60, ), TextField( maxLines: 1, controller: nameEditingController, decoration: InputDecoration( filled: true, fillColor: Colors.white70, hintText: "Name", hintStyle: TextStyle(color: Colors.black), border: InputBorder.none), ), SizedBox( height: 10, ), TextField( maxLines: 1, controller: emailEditingController, decoration: InputDecoration( filled: true, fillColor: Colors.white70, hintText: "Email", hintStyle: TextStyle(color: Colors.black), border: InputBorder.none), ), SizedBox( height: 10, ), TextField( maxLines: 2, controller: subjectEditingController, decoration: InputDecoration( filled: true, fillColor: Colors.white70, hintText: "Subject", hintStyle: TextStyle(color: Colors.black), border: InputBorder.none), ), SizedBox( height: 10, ), TextField( maxLines: 5, controller: messageEditingController, decoration: InputDecoration( filled: true, fillColor: Colors.white70, hintText: "Message", hintStyle: TextStyle(color: Colors.black), border: InputBorder.none), ), SizedBox( height: 10, ), MaterialButton( onPressed: () async { await FirebaseFirestore.instance .collection("forms") .doc(uploadTime) .set({ 'name': nameEditingController.text, 'email': emailEditingController.text, 'subject': subjectEditingController.text, 'message': messageEditingController.text, 'uploadTime': uploadTime }).catchError((onError) { print(onError); }).whenComplete(() { setState(() { nameEditingController.text = emailEditingController.text = subjectEditingController.text = messageEditingController.text = ""; }); }); }, height: 60, minWidth: double.infinity, color: Colors.white, child: Text("Submit"), ) ], ), ), ), ) ); } }
0
mirrored_repositories/Flutter-Portfolio/lib
mirrored_repositories/Flutter-Portfolio/lib/Views/aboutme.dart
import 'package:flutter/material.dart'; import 'package:url_launcher/url_launcher.dart'; class AboutMe extends StatelessWidget { Future<void> launchUrl(String url) async { if (await canLaunch(url)) { await launch( url, forceSafariVC: false, forceWebView: false, headers: <String, String>{'my_header_key': 'my_header_value'}, ); } else { throw 'Could not launch $url'; } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( iconTheme: IconThemeData( color: Colors.black, ), title: Center(child: Text("About Me", style: TextStyle(color: Colors.black),)), backgroundColor: Colors.white, ), body: SingleChildScrollView( physics: ClampingScrollPhysics(), child: Container( // decoration: BoxDecoration( // color: Colors.black, // image: DecorationImage( // colorFilter: new ColorFilter.mode( // Colors.black.withOpacity(0.4), BlendMode.darken), // image: NetworkImage(bgImgUrl), // fit: BoxFit.cover, // ), // ), color: Color(0xff333340), //width: MediaQuery.of(context).size.width, //height: MediaQuery.of(context).size.height, child: Column( children: [ Container( //color: Colors.black, child: Row( children: [ Padding( padding: const EdgeInsets.all(15.0), child: Text("Hi,", style: TextStyle(fontSize: 120, color: Colors.white, fontWeight: FontWeight.w500),), ), SizedBox(width: 800,), Container( child: Image.network("https://raw.githubusercontent.com/onkar-shaligram/onkar-shaligram/master/prog.gif", height: 300, width: 300,)), ], ), ), SizedBox(height: 20,), Container( alignment: Alignment.centerLeft, padding: EdgeInsets.all(15), child: Text("I'm Onkar Shaligram, a 19-year-old undergrad, currently living in Bhopal (MP), India. Originally from Pune (MH), India.", style: TextStyle(fontSize: 30, color: Colors.white, fontWeight: FontWeight.w500), ) ), SizedBox(height: 10,), Container( alignment: Alignment.centerLeft, padding: EdgeInsets.all(15), child: Text("I am a programmer with intermidiate knowledge of front-end & back-end techniques. I love spending time on fixing little details and optimizing web apps. Also I like working in a team, as you learn faster and much more. As the saying goes: Two heads are better than one.!!'.", style: TextStyle(fontSize: 30, color: Colors.white, fontWeight: FontWeight.w500), ) ), SizedBox(height: 10,), Container( alignment: Alignment.centerLeft, padding: EdgeInsets.all(15), child: Text("I will be earning a degree in Bachelor of Technology in Computer Science from VIT Bhopal University probably in 2023.", style: TextStyle(fontSize: 30, color: Colors.white, fontWeight: FontWeight.w500), ) ), SizedBox(height: 10,), Container( alignment: Alignment.centerLeft, padding: EdgeInsets.all(15), child: Text("If you wish to connect with me, then find me at Twitter, Linkedin and also on Github.", style: TextStyle(fontSize: 30, color: Colors.white, fontWeight: FontWeight.w500),) ), SizedBox(height: 10,), Container( alignment: Alignment.centerLeft, padding: EdgeInsets.all(15), child: GestureDetector( onTap: () { launchUrl("https://rzp.io/l/4l0UoiD"); }, child: Text("Did you like the website? or got inspired? or copied the theme? No problem! Just buy me a starbucks and make me happy!!!.", style: TextStyle(fontSize: 26, color: Colors.red, fontWeight: FontWeight.w500),)) ), ], ), ), ), ); } }
0
mirrored_repositories/Flutter-Portfolio/lib
mirrored_repositories/Flutter-Portfolio/lib/Views/home.dart
import 'package:flutter/material.dart'; import 'package:flutter_portfolio/Helpers/constants.dart'; import 'package:flutter_portfolio/Views/aboutme.dart'; import 'package:flutter_portfolio/Views/contact_me.dart'; import 'package:flutter_portfolio/Views/projects.dart'; import 'package:url_launcher/url_launcher.dart'; import 'dart:html' as html; class Home extends StatefulWidget { @override _HomeState createState() => _HomeState(); } class _HomeState extends State<Home> { Future<void> launchUrl(String url) async { if (await canLaunch(url)) { await launch( url, forceSafariVC: false, forceWebView: false, headers: <String, String>{'my_header_key': 'my_header_value'}, ); } else { throw 'Could not launch $url'; } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Colors.white, actions: [ Expanded( child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ InkWell( onTap: () { Navigator.push(context, MaterialPageRoute(builder: (context) => AboutMe())); }, child: Text( "About", style: TextStyle( color: Colors.black, fontSize: 20, fontWeight: FontWeight.w500), )), SizedBox( width: 30, ), InkWell( onTap: () { Navigator.push(context, MaterialPageRoute(builder: (context) => Projects())); }, child: Text( "Projects", style: TextStyle( color: Colors.black, fontSize: 20, fontWeight: FontWeight.w500), )), SizedBox( width: 30, ), InkWell( onTap: () { Navigator.push(context, MaterialPageRoute(builder: (context) => ContactMe())); }, child: Text( "Contact Me", style: TextStyle( color: Colors.black, fontSize: 20, fontWeight: FontWeight.w500), )), ], ), ), ], ), body: Container( height: MediaQuery.of(context).size.height, decoration: BoxDecoration( color: Colors.black, image: DecorationImage( colorFilter: new ColorFilter.mode( Colors.black.withOpacity(0.4), BlendMode.darken), image: NetworkImage(bgImgUrl), fit: BoxFit.cover, ), ), child: Center( child: Column( children: [ SizedBox( height: 100, ), CircleAvatar( radius: 150, backgroundImage: Image.network(myImgUrl).image, ), Text( "Onkar Shaligram", style: TextStyle( fontSize: 50, fontWeight: FontWeight.w700, color: Colors.white), ), SizedBox( height: 20, ), Text( "Android Developer | Flutter Enthusiast", style: TextStyle( color: Colors.white70, fontSize: 20, fontWeight: FontWeight.w600), ), SizedBox( height: 30, ), Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ FlatButton.icon( icon: SizedBox( width: 25, height: 25, child: Image.network(githubImgUrl)), label: Text( 'Github', style: TextStyle(color: Colors.white), ), onPressed: () { html.window .open("https://github.com/onkar-shaligram", "name"); }, ), FlatButton.icon( icon: SizedBox( width: 25, height: 25, child: Image.network(twitterImgUrl)), label: Text( 'Twitter', style: TextStyle(color: Colors.white), ), onPressed: () { html.window .open("https://twitter.com/shaligram_onkar", "name"); }, ), FlatButton.icon( icon: SizedBox( width: 25, height: 25, child: Image.network(linkedinImgUrl)), label: Text( 'LinkedIn', style: TextStyle(color: Colors.white), ), onPressed: () { html.window.open( "https://www.linkedin.com/in/onkar-shaligram-a9799b190/", "name"); }, ) ], ), SizedBox( height: 60, ), RichText( text: TextSpan( style: TextStyle( color: Colors.white70, fontSize: 20, fontWeight: FontWeight.w600), children: [ TextSpan(text: 'Made with '), WidgetSpan( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 2.0), child: Icon(Icons.favorite_rounded, color: Colors.red,) ), ), TextSpan(text: ' Using Flutter'), ], ), ) ], ), ), ), ); } }
0
mirrored_repositories/Flutter-Portfolio/lib
mirrored_repositories/Flutter-Portfolio/lib/Helpers/Media_query.dart
import 'package:flutter/material.dart'; class MediaQuerys extends StatelessWidget { final Widget largeScreen; final Widget mediumScreen; final Widget smallScreen; const MediaQuerys( {Key key, @required this.largeScreen, this.mediumScreen, this.smallScreen}) : super(key: key); static bool isSmallScreen(BuildContext context) { return MediaQuery.of(context).size.width < 800; } static bool isLargeScreen(BuildContext context) { return MediaQuery.of(context).size.width > 800; } static bool isMediumScreen(BuildContext context) { return MediaQuery.of(context).size.width > 800 && MediaQuery.of(context).size.width < 1200; } @override Widget build(BuildContext context) { return LayoutBuilder( builder: (context, constraints) { if (constraints.maxWidth > 950) { return largeScreen; } else if (constraints.maxWidth < 1200 && constraints.maxWidth > 800) { return smallScreen; } else { return smallScreen; } }, ); } }
0
mirrored_repositories/Flutter-Portfolio/lib
mirrored_repositories/Flutter-Portfolio/lib/Helpers/projectView.dart
import 'package:flutter/material.dart'; import 'package:flutter_portfolio/Helpers/project_class.dart'; import 'package:url_launcher/url_launcher.dart'; class ProjectView extends StatelessWidget { Project project; ProjectView({this.project}); Future<void> launchUrl(String url) async { if (await canLaunch(url)) { await launch( url, forceSafariVC: false, forceWebView: false, headers: <String, String>{'my_header_key': 'my_header_value'}, ); } else { throw 'Could not launch $url'; } } @override Widget build(BuildContext context) { final height = MediaQuery.of(context).size.height; return Card( elevation: 10, margin: EdgeInsets.all(18.0), child: InkWell( onTap: () { launchUrl(project.link); }, child: Padding( padding: const EdgeInsets.all(10.0), child: Row( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ Expanded( flex: 40, child: ClipRRect( borderRadius: BorderRadius.circular(10), child: Center( child: Image.network( project.image, fit: BoxFit.cover, ), ), )), Expanded( flex: 3, child: Container(), ), Expanded( flex: 70, child: Container( padding: EdgeInsets.only(top: 10.0), child: Wrap( direction: Axis.horizontal, children: [ Text( project.name, style: Theme.of(context).textTheme.headline6, ), SizedBox( height: height * .01, ), Text( project.description, textScaleFactor: 1.25, style: Theme.of(context).textTheme.caption, ), ], ), ), ) ], ), ), ), ); } }
0
mirrored_repositories/Flutter-Portfolio/lib
mirrored_repositories/Flutter-Portfolio/lib/Helpers/projects_helper.dart
import 'package:flutter_portfolio/Helpers/project_class.dart'; int i = 0; List<Project> projects = [ Project( name: 'CoffeeWala App', image: "https://mir-s3-cdn-cf.behance.net/project_modules/max_1200/0eabca74119511.5c22f20609b48.png", description: "A Full-fledged Coffee Delivering System. Bundled with Admin console", link: "https://github.com/onkar-shaligram/CoffeeWala-App", ), Project( name: 'DSC Events App', image: "https://dsccu.in/images/footerLogo.png", description: "App that notifies Students about new events happening at DSC", link: "https://github.com/onkar-shaligram/DSC-Events-App", ), Project( name: 'Name No. ${i++}', image: "https://flutter.dev/images/catalog-widget-placeholder.png", description: "description No. ${i++}", link: "https://onkar-shaligram.netlify.app/", ), Project( name: 'Name No. ${i++}', image: "https://flutter.dev/images/catalog-widget-placeholder.png", description: "description No. ${i++}", link: "https://onkar-shaligram.netlify.app/", ), Project( name: 'Name No. ${i++}', image: "https://flutter.dev/images/catalog-widget-placeholder.png", description: "description No. ${i++}", link: "https://onkar-shaligram.netlify.app/", ), Project( name: 'Name No. ${i++}', image: "https://flutter.dev/images/catalog-widget-placeholder.png", description: "description No. ${i++}", link: "https://onkar-shaligram.netlify.app/", ), Project( name: 'Name No. ${i++}', image: "https://flutter.dev/images/catalog-widget-placeholder.png", description: "description No. ${i++}", link: "https://onkar-shaligram.netlify.app/", ), Project( name: 'Name No. ${i++}', image: "https://flutter.dev/images/catalog-widget-placeholder.png", description: "description No. ${i++}", link: "https://onkar-shaligram.netlify.app/", ), Project( name: 'Name No. ${i++}', image: "https://flutter.dev/images/catalog-widget-placeholder.png", description: "description No. ${i++}", link: "https://onkar-shaligram.netlify.app/", ), Project( name: 'Name No. ${i++}', image: "https://flutter.dev/images/catalog-widget-placeholder.png", description: "description No. ${i++}", link: "https://onkar-shaligram.netlify.app/", ), Project( name: 'Name No. ${i++}', image: "https://flutter.dev/images/catalog-widget-placeholder.png", description: "description No. ${i++}", link: "https://onkar-shaligram.netlify.app/", ), Project( name: 'Name No. ${i++}', image: "https://flutter.dev/images/catalog-widget-placeholder.png", description: "description No. ${i++}", link: "https://onkar-shaligram.netlify.app/", ), Project( name: 'Name No. ${i++}', image: "https://flutter.dev/images/catalog-widget-placeholder.png", description: "description No. ${i++}", link: "https://onkar-shaligram.netlify.app/", ), Project( name: 'Name No. ${i++}', image: "https://flutter.dev/images/catalog-widget-placeholder.png", description: "description No. ${i++}", link: "https://onkar-shaligram.netlify.app/", ), ];
0
mirrored_repositories/Flutter-Portfolio/lib
mirrored_repositories/Flutter-Portfolio/lib/Helpers/constants.dart
String myImgUrl = "https://raw.githubusercontent.com/onkar-shaligram/onkar-shaligram.github.io/master/DSC_1032-reduced.jpg"; String bgImgUrl = "https://raw.githubusercontent.com/onkar-shaligram/onkar-shaligram.github.io/master/assets/images/image2copy_blur.jpg"; String githubImgUrl = "https://www.flaticon.com/svg/static/icons/svg/2111/2111425.svg"; String twitterImgUrl = "https://www.flaticon.com/svg/static/icons/svg/733/733579.svg"; String linkedinImgUrl = "https://www.flaticon.com/svg/static/icons/svg/174/174857.svg"; String uploadTime = DateTime.now().day.toString() + DateTime.now().month.toString() + DateTime.now().year.toString() + DateTime.now().hour.toString() + DateTime.now().minute.toString() + DateTime.now().second.toString() + DateTime.now().millisecond.toString();
0
mirrored_repositories/Flutter-Portfolio/lib
mirrored_repositories/Flutter-Portfolio/lib/Helpers/project_class.dart
class Project { String name; String image; String description; String link; Project({this.name, this.image, this.description, this.link}); }
0
mirrored_repositories/Flutter-Portfolio
mirrored_repositories/Flutter-Portfolio/integration_test/driver.dart
// This file is provided as a convenience for running integration tests via the // flutter drive command. // // flutter drive --driver integration_test/driver.dart --target integration_test/app_test.dart import 'package:integration_test/integration_test_driver.dart'; Future<void> main() => integrationDriver();
0
mirrored_repositories/Flutter-Portfolio
mirrored_repositories/Flutter-Portfolio/integration_test/app_test.dart
// This is a basic Flutter integration 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:integration_test/integration_test.dart'; import 'package:flutter_portfolio/main.dart' as app; void main() => run(_testMain); void _testMain() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. app.main(); // Trigger a frame. await tester.pumpAndSettle(); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/Flutter-Portfolio
mirrored_repositories/Flutter-Portfolio/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_portfolio/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/Futter_WatchOS
mirrored_repositories/Futter_WatchOS/lib/main_staging.dart
import 'package:flutter_watch/app/app.dart'; import 'package:flutter_watch/bootstrap.dart'; void main() { bootstrap(() => const App()); }
0
mirrored_repositories/Futter_WatchOS
mirrored_repositories/Futter_WatchOS/lib/main_production.dart
import 'package:flutter_watch/app/app.dart'; import 'package:flutter_watch/bootstrap.dart'; void main() { bootstrap(() => const App()); }
0
mirrored_repositories/Futter_WatchOS
mirrored_repositories/Futter_WatchOS/lib/main.dart
import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({super.key, required this.title}); final String title; @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { setState(() { _counter++; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ const Text( 'You have pushed the button this many times:', ), Text( '$_counter', style: Theme.of(context).textTheme.headlineMedium, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: const Icon(Icons.add), ), // This trailing comma makes auto-formatting nicer for build methods. ); } }
0
mirrored_repositories/Futter_WatchOS
mirrored_repositories/Futter_WatchOS/lib/bootstrap.dart
import 'dart:async'; import 'dart:developer'; import 'package:bloc/bloc.dart'; import 'package:flutter/widgets.dart'; class AppBlocObserver extends BlocObserver { @override void onChange(BlocBase<dynamic> bloc, Change<dynamic> change) { super.onChange(bloc, change); log('onChange(${bloc.runtimeType}, $change)'); } @override void onError(BlocBase<dynamic> bloc, Object error, StackTrace stackTrace) { log('onError(${bloc.runtimeType}, $error, $stackTrace)'); super.onError(bloc, error, stackTrace); } } Future<void> bootstrap(FutureOr<Widget> Function() builder) async { FlutterError.onError = (details) { log(details.exceptionAsString(), stackTrace: details.stack); }; Bloc.observer = AppBlocObserver(); await runZonedGuarded( () async => runApp(await builder()), (error, stackTrace) => log(error.toString(), stackTrace: stackTrace), ); }
0
mirrored_repositories/Futter_WatchOS
mirrored_repositories/Futter_WatchOS/lib/main_development.dart
import 'package:flutter_watch/app/app.dart'; import 'package:flutter_watch/bootstrap.dart'; void main() { bootstrap(() => const App()); }
0
mirrored_repositories/Futter_WatchOS/lib
mirrored_repositories/Futter_WatchOS/lib/app/app.dart
export 'view/app.dart';
0
mirrored_repositories/Futter_WatchOS/lib/app
mirrored_repositories/Futter_WatchOS/lib/app/view/app.dart
import 'package:flutter/material.dart'; import 'package:flutter_watch/counter/counter.dart'; import 'package:flutter_watch/l10n/l10n.dart'; class App extends StatelessWidget { const App({super.key}); @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData( appBarTheme: const AppBarTheme(color: Color(0xFF13B9FF)), colorScheme: ColorScheme.fromSwatch( accentColor: const Color(0xFF13B9FF), ), ), localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, home: const CounterPage(), ); } }
0
mirrored_repositories/Futter_WatchOS/lib
mirrored_repositories/Futter_WatchOS/lib/counter/counter.dart
export 'cubit/counter_cubit.dart'; export 'view/counter_page.dart';
0
mirrored_repositories/Futter_WatchOS/lib/counter
mirrored_repositories/Futter_WatchOS/lib/counter/view/counter_page.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_watch/counter/counter.dart'; import 'package:flutter_watch/l10n/l10n.dart'; class CounterPage extends StatelessWidget { const CounterPage({super.key}); // ignore: avoid_field_initializers_in_const_classes final MethodChannel _channel = const MethodChannel('flutter_watch'); @override Widget build(BuildContext context) { return BlocProvider( create: (_) => CounterCubit( channel: _channel, ), child: CounterView( channel: _channel, ), ); } } class CounterView extends StatefulWidget { const CounterView({ required this.channel, super.key, }); final MethodChannel channel; @override State<CounterView> createState() => _CounterViewState(); } class _CounterViewState extends State<CounterView> { @override void initState() { super.initState(); widget.channel.setMethodCallHandler((call) async { final methodName = call.method; final args = call.arguments; if (methodName != 'updateFromWatch') { return; } // ignore: avoid_dynamic_calls final text = args['text'] as String; if (text == 'increment') { context.read<CounterCubit>().increment(); } else if (text == 'decrement') { context.read<CounterCubit>().decrement(); } }); } @override Widget build(BuildContext context) { final l10n = context.l10n; return Scaffold( appBar: AppBar(title: Text(l10n.counterAppBarTitle)), body: const Center(child: CounterText()), floatingActionButton: Column( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.end, children: [ FloatingActionButton( onPressed: () => context.read<CounterCubit>().increment(), child: const Icon(Icons.add), ), const SizedBox(height: 8), FloatingActionButton( onPressed: () => context.read<CounterCubit>().decrement(), child: const Icon(Icons.remove), ), ], ), ); } } class CounterText extends StatelessWidget { const CounterText({super.key}); @override Widget build(BuildContext context) { final theme = Theme.of(context); final count = context.select((CounterCubit cubit) => cubit.state); return Text('$count', style: theme.textTheme.displayLarge); } }
0
mirrored_repositories/Futter_WatchOS/lib/counter
mirrored_repositories/Futter_WatchOS/lib/counter/cubit/counter_cubit.dart
import 'package:bloc/bloc.dart'; import 'package:flutter/services.dart'; const String kSendToWatchMethod = 'sendToWatch'; const String kRemoteMethod = 'updateFromApp'; class CounterCubit extends Cubit<int> { CounterCubit({ this.channel, }) : super(0); final MethodChannel? channel; void increment() { final newState = state + 1; _sendToWatch(newState.toString()); emit(newState); } void decrement() { final newState = state - 1; _sendToWatch(newState.toString()); emit(newState); } void _sendToWatch(String text) { channel?.invokeMethod(kSendToWatchMethod, { 'method': kRemoteMethod, 'data': { 'text': text, }, }); } }
0
mirrored_repositories/Futter_WatchOS/lib
mirrored_repositories/Futter_WatchOS/lib/l10n/l10n.dart
import 'package:flutter/widgets.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; export 'package:flutter_gen/gen_l10n/app_localizations.dart'; extension AppLocalizationsX on BuildContext { AppLocalizations get l10n => AppLocalizations.of(this); }
0
mirrored_repositories/Futter_WatchOS
mirrored_repositories/Futter_WatchOS/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility in the flutter_test package. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_watch/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/Futter_WatchOS/test/app
mirrored_repositories/Futter_WatchOS/test/app/view/app_test.dart
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_watch/app/app.dart'; import 'package:flutter_watch/counter/counter.dart'; void main() { group('App', () { testWidgets('renders CounterPage', (tester) async { await tester.pumpWidget(const App()); expect(find.byType(CounterPage), findsOneWidget); }); }); }
0
mirrored_repositories/Futter_WatchOS/test/counter
mirrored_repositories/Futter_WatchOS/test/counter/view/counter_page_test.dart
import 'package:bloc_test/bloc_test.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_watch/counter/counter.dart'; import 'package:mocktail/mocktail.dart'; import '../../helpers/helpers.dart'; class MockChannel extends Mock implements MethodChannel {} class MockCounterCubit extends MockCubit<int> implements CounterCubit {} void main() { group('CounterPage', () { testWidgets('renders CounterView', (tester) async { await tester.pumpApp(const CounterPage()); expect(find.byType(CounterView), findsOneWidget); }); }); group('CounterView', () { late CounterCubit counterCubit; late MethodChannel channel; setUp(() { counterCubit = MockCounterCubit(); channel = MockChannel(); }); testWidgets('renders current count', (tester) async { const state = 42; when(() => counterCubit.state).thenReturn(state); await tester.pumpApp( BlocProvider.value( value: counterCubit, child: CounterView( channel: channel, ), ), ); expect(find.text('$state'), findsOneWidget); }); testWidgets('calls increment when increment button is tapped', (tester) async { when(() => counterCubit.state).thenReturn(0); when(() => counterCubit.increment()).thenReturn(null); await tester.pumpApp( BlocProvider.value( value: counterCubit, child: CounterView( channel: channel, ), ), ); await tester.tap(find.byIcon(Icons.add)); verify(() => counterCubit.increment()).called(1); }); testWidgets('calls decrement when decrement button is tapped', (tester) async { when(() => counterCubit.state).thenReturn(0); when(() => counterCubit.decrement()).thenReturn(null); await tester.pumpApp( BlocProvider.value( value: counterCubit, child: CounterView( channel: channel, ), ), ); await tester.tap(find.byIcon(Icons.remove)); verify(() => counterCubit.decrement()).called(1); }); }); }
0
mirrored_repositories/Futter_WatchOS/test/counter
mirrored_repositories/Futter_WatchOS/test/counter/cubit/counter_cubit_test.dart
import 'package:bloc_test/bloc_test.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_watch/counter/cubit/counter_cubit.dart'; import 'package:mocktail/mocktail.dart'; class MocPlatformChannel extends Mock implements MethodChannel {} void main() { group('CounterCubit', () { test('initial state is 0', () { expect(CounterCubit().state, equals(0)); }); blocTest<CounterCubit, int>( 'emits [1] when increment is called', build: CounterCubit.new, act: (cubit) => cubit.increment(), expect: () => [equals(1)], ); blocTest<CounterCubit, int>( 'emits [-1] when decrement is called', build: CounterCubit.new, act: (cubit) => cubit.decrement(), expect: () => [equals(-1)], ); }); }
0
mirrored_repositories/Futter_WatchOS/test
mirrored_repositories/Futter_WatchOS/test/helpers/helpers.dart
export 'pump_app.dart';
0
mirrored_repositories/Futter_WatchOS/test
mirrored_repositories/Futter_WatchOS/test/helpers/pump_app.dart
import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_watch/l10n/l10n.dart'; extension PumpApp on WidgetTester { Future<void> pumpApp(Widget widget) { return pumpWidget( MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, home: widget, ), ); } }
0
mirrored_repositories/flux_cloud_note
mirrored_repositories/flux_cloud_note/lib/checkerLogin.dart
import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:flux_cloud/pages/homepage.dart'; import 'package:flux_cloud/pages/login.dart'; class CheckerLogin extends StatelessWidget { @override Widget build(BuildContext context) { return StreamBuilder( stream: FirebaseAuth.instance.authStateChanges(), builder: (BuildContext context, AsyncSnapshot snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return Center(child: CircularProgressIndicator()); } else if (snapshot.hasData) { return HomePage( user: snapshot.data!, ); } else if (snapshot.data == null) { return AnoLogin(); } return Container(); }); } }
0
mirrored_repositories/flux_cloud_note
mirrored_repositories/flux_cloud_note/lib/main.dart
import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'package:flux_cloud/checkerLogin.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData( primarySwatch: Colors.pink, ), debugShowCheckedModeBanner: false, home: CheckerLogin(), ); } }
0
mirrored_repositories/flux_cloud_note/lib
mirrored_repositories/flux_cloud_note/lib/pages/editpage.dart
import 'package:flutter/material.dart'; import 'package:flux_cloud/model/note_model.dart'; import 'package:flux_cloud/services/note_services.dart'; class EditPage extends StatefulWidget { final NoteModel noteModel; EditPage({required this.noteModel}); @override _EditPageState createState() => _EditPageState(); } class _EditPageState extends State<EditPage> { late TextEditingController _title; late TextEditingController _desc; @override void initState() { super.initState(); _title = TextEditingController(text: widget.noteModel.title); _desc = TextEditingController(text: widget.noteModel.desc); } @override void dispose() { _desc.dispose(); _title.dispose(); super.dispose(); } GlobalKey<FormState> _key = GlobalKey<FormState>(); bool _isLoading = false; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Edit Page"), ), body: Form( key: _key, child: ListView( children: [ TextFormField( validator: (val) { if (val!.isEmpty) return "Field is Empty"; return null; }, controller: _title, decoration: InputDecoration( border: InputBorder.none, hintText: "Enter a title", ), ), TextFormField( validator: (val) { if (val!.isEmpty) return "Field is Empty"; return null; }, controller: _desc, maxLength: 500, maxLines: 10, decoration: InputDecoration( border: InputBorder.none, hintText: "Enter a description", ), ), SizedBox( height: 10, ), _isLoading ? Center( child: Container( width: 50, height: 50, child: CircularProgressIndicator(), ), ) : ElevatedButton( onPressed: () async { final isValid = _key.currentState!.validate(); if (!isValid) { return; } else { setState(() { _isLoading = true; }); _key.currentState!.save(); await NoteFirestoreServices.updateNote( widget.noteModel.id.toString(), _title.text, _desc.text, ); ScaffoldMessenger.of(context).showSnackBar( SnackBar( duration: Duration( seconds: 2, ), content: Text("Updated"), ), ); Navigator.pop(context); } }, child: Text( "Update".toUpperCase(), style: TextStyle( fontSize: Theme.of(context).textTheme.button!.fontSize, ), ), ), ], ), ), ); } }
0
mirrored_repositories/flux_cloud_note/lib
mirrored_repositories/flux_cloud_note/lib/pages/addpage.dart
import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:flux_cloud/services/note_services.dart'; class AddPage extends StatefulWidget { final User uid; AddPage({required this.uid}); @override _AddPageState createState() => _AddPageState(); } class _AddPageState extends State<AddPage> { late TextEditingController _title; late TextEditingController _desc; @override void initState() { super.initState(); _title = TextEditingController(); _desc = TextEditingController(); } @override void dispose() { _desc.dispose(); _title.dispose(); super.dispose(); } GlobalKey<FormState> _key = GlobalKey<FormState>(); bool _isLoading = false; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Add Page"), ), body: Form( key: _key, child: ListView( children: [ TextFormField( validator: (val) { if (val!.isEmpty) return "Field is Empty"; return null; }, controller: _title, decoration: InputDecoration( border: InputBorder.none, hintText: "Enter a title", ), ), TextFormField( validator: (val) { if (val!.isEmpty) return "Field is Empty"; return null; }, controller: _desc, maxLength: 500, maxLines: 10, decoration: InputDecoration( border: InputBorder.none, hintText: "Enter a description", ), ), SizedBox( height: 10, ), _isLoading ? Center( child: Container( width: 50, height: 50, child: CircularProgressIndicator(), ), ) : ElevatedButton( onPressed: () async { final isValid = _key.currentState!.validate(); if (!isValid) { return; } else { setState(() { _isLoading = true; }); _key.currentState!.save(); await NoteFirestoreServices.insertNote( _title.text, _desc.text, widget.uid.uid); ScaffoldMessenger.of(context).showSnackBar( SnackBar( duration: Duration( seconds: 2, ), content: Text("Added"), ), ); Navigator.pop(context); } }, child: Text( "Add".toUpperCase(), style: TextStyle( fontSize: Theme.of(context).textTheme.button!.fontSize, ), ), ), ], ), ), ); } }
0
mirrored_repositories/flux_cloud_note/lib
mirrored_repositories/flux_cloud_note/lib/pages/homepage.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:flux_cloud/model/note_model.dart'; import 'package:flux_cloud/pages/addpage.dart'; import 'package:flux_cloud/pages/editpage.dart'; import 'package:flux_cloud/widget/delete_note_widget.dart'; import 'package:flux_cloud/widget/drawer_widget.dart'; class HomePage extends StatefulWidget { final User user; HomePage({required this.user}); @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { FirebaseFirestore firebaseFirestore = FirebaseFirestore.instance; @override Widget build(BuildContext context) { return Scaffold( floatingActionButton: FloatingActionButton( child: Icon(Icons.add), onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (_) => AddPage( uid: widget.user, ))); }, ), appBar: AppBar( title: Text("Flux Cloud"), ), drawer: EasyDrawer(), body: StreamBuilder<QuerySnapshot>( stream: firebaseFirestore .collection('notes') .orderBy( "timeStamp", descending: true, ) .snapshots(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return Center( child: CircularProgressIndicator(), ); } else if (snapshot.connectionState == ConnectionState.active) { if (snapshot.data!.docs.isNotEmpty) { return ListView.builder( itemCount: snapshot.data!.docs.length, itemBuilder: (context, index) { NoteModel noteModel = NoteModel.fromJson(snapshot.data!.docs[index]); return ListTile( title: Text(noteModel.title ?? ""), subtitle: Text(noteModel.desc ?? ""), onTap: () { Navigator.push( context, MaterialPageRoute( builder: (_) => EditPage( noteModel: noteModel, ), ), ); }, onLongPress: () async { await deleteDialog(context, noteModel); }, ); }); } else { return LinearProgressIndicator( color: Colors.red, backgroundColor: Colors.indigo, ); } } return Text("Something is Error"); }, ), ); } }
0
mirrored_repositories/flux_cloud_note/lib
mirrored_repositories/flux_cloud_note/lib/pages/login.dart
import 'package:flutter/material.dart'; import 'package:flux_cloud/checkerLogin.dart'; import 'package:flux_cloud/services/auth_service.dart'; class AnoLogin extends StatefulWidget { @override _AnoLoginState createState() => _AnoLoginState(); } class _AnoLoginState extends State<AnoLogin> { @override Widget build(BuildContext context) { return Scaffold( body: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ makeStraightLine(context), Center( child: InkWell( onTap: () async { await AuthService.anomonouslogin(); Navigator.pushAndRemoveUntil( context, MaterialPageRoute(builder: (_) => CheckerLogin()), (route) => false); }, child: CircleAvatar( radius: 30, backgroundColor: Colors.indigo, child: Text( "go", style: TextStyle( color: Colors.white, fontSize: Theme.of(context).textTheme.bodyText2!.fontSize, fontWeight: FontWeight.bold, ), ), ), ), ), makeStraightLine(context), ], ), ); } Widget makeStraightLine(BuildContext context) { return ClipRRect( borderRadius: BorderRadius.circular(30), child: Container( height: MediaQuery.of(context).size.height * 0.06, width: 10, color: Colors.grey, ), ); } }
0
mirrored_repositories/flux_cloud_note/lib
mirrored_repositories/flux_cloud_note/lib/model/note_model.dart
import 'package:cloud_firestore/cloud_firestore.dart'; class NoteModel { String? id; String? title; String? desc; Timestamp? timestamp; Timestamp? dateTime; String? uid; NoteModel({ this.id, this.title, this.desc, this.timestamp, this.dateTime, this.uid, }); factory NoteModel.fromJson(DocumentSnapshot snapshot) { return NoteModel( id: snapshot.id, // document id title: snapshot['title'], uid: snapshot['userId'], // unique id of user desc: snapshot['desc'], dateTime: snapshot['dateTime'], timestamp: snapshot['timeStamp']); } }
0
mirrored_repositories/flux_cloud_note/lib
mirrored_repositories/flux_cloud_note/lib/widget/drawer_widget.dart
import 'package:flutter/material.dart'; import 'package:flux_cloud/checkerLogin.dart'; import 'package:flux_cloud/services/auth_service.dart'; class EasyDrawer extends StatelessWidget { const EasyDrawer({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { return Drawer( child: ListView( padding: EdgeInsets.all(0), children: [ UserAccountsDrawerHeader( currentAccountPicture: ClipRRect( borderRadius: BorderRadius.circular(50), child: Image.network( "https://images.unsplash.com/photo-1580429361231-bd93065f3b2a?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80", fit: BoxFit.cover, ), ), accountName: Text("Anonymously Account"), accountEmail: Text("anonymouslyaccount@kishor.com"), ), ListTile( title: Text("Logout"), onTap: () async { await AuthService.logout(); Navigator.pushAndRemoveUntil( context, MaterialPageRoute(builder: (_) => CheckerLogin()), (route) => false); }, ), ], ), ); } }
0
mirrored_repositories/flux_cloud_note/lib
mirrored_repositories/flux_cloud_note/lib/widget/delete_note_widget.dart
import 'package:flutter/material.dart'; import 'package:flux_cloud/model/note_model.dart'; import 'package:flux_cloud/services/note_services.dart'; deleteDialog(BuildContext context, NoteModel noteModel) async { showDialog( context: context, builder: (_) { return AlertDialog( title: Text("Delete"), content: Text("Are you sure to delete?"), actions: [ TextButton( onPressed: () async { await NoteFirestoreServices.deleteNote(noteModel.id.toString()); Navigator.pop(context); }, child: Text("Yes"), ), TextButton( onPressed: () { Navigator.pop(context); }, child: Text("No"), ), ], ); }); }
0
mirrored_repositories/flux_cloud_note/lib
mirrored_repositories/flux_cloud_note/lib/services/auth_service.dart
import 'package:firebase_auth/firebase_auth.dart'; class AuthService { static FirebaseAuth _auth = FirebaseAuth.instance; static Future anomonouslogin() async { return await _auth.signInAnonymously(); } static logout() async { return await _auth.signOut(); } }
0
mirrored_repositories/flux_cloud_note/lib
mirrored_repositories/flux_cloud_note/lib/services/note_services.dart
import 'package:cloud_firestore/cloud_firestore.dart'; class NoteFirestoreServices { static FirebaseFirestore _firebaseFirestore = FirebaseFirestore.instance; static Future insertNote(String title, String desc, String uid) async { try { await _firebaseFirestore.collection('notes').add({ 'title': title, 'desc': desc, 'dateTime': DateTime.now(), 'userId': uid, 'timeStamp': Timestamp.now(), }); } catch (e) { print(e); } } static Future updateNote(String docId, String title, String desc) async { try { await _firebaseFirestore.collection('notes').doc(docId).update({ 'title': title, 'desc': desc, 'timeStamp': Timestamp.now(), 'dateTime': DateTime.now(), }); } catch (e) { print(e); } } static Future deleteNote(String docId) async { try { await _firebaseFirestore.collection('notes').doc(docId).delete(); } catch (e) { print(e); } } }
0
mirrored_repositories/flux_cloud_note
mirrored_repositories/flux_cloud_note/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:flux_cloud/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/note_keep_up
mirrored_repositories/note_keep_up/lib/main.dart
import 'package:flutter/material.dart'; import 'package:note_app/app/app.dart'; import 'package:note_app/app/di/get_it.dart' as di; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Future.wait([di.init()]); runApp(const NoteApp()); }
0
mirrored_repositories/note_keep_up/lib
mirrored_repositories/note_keep_up/lib/app/app.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:note_app/core/core.dart'; import 'package:note_app/features/presentation/blocs/blocs.dart'; import 'provider/app_provider.dart'; class NoteApp extends StatelessWidget { const NoteApp({super.key}); @override Widget build(BuildContext context) { AppDevice.setStatusBart(context); return AppProviders( child: AnnotatedRegion( value: const SystemUiOverlayStyle(), child: BlocBuilder<ThemeCubit, ThemeState>( builder: (context, state) { if (state is LoadedTheme) { return MaterialApp.router( debugShowCheckedModeBanner: false, title: 'Note App Version 2', theme: AppTheme.light, darkTheme: AppTheme.dark, themeMode: state.themeMode, routeInformationParser: AppRouter.router.routeInformationParser, routerDelegate: AppRouter.router.routerDelegate, routeInformationProvider: AppRouter.router.routeInformationProvider, ); } return const SizedBox.shrink(); }, ), ), ); } }
0
mirrored_repositories/note_keep_up/lib/app
mirrored_repositories/note_keep_up/lib/app/di/get_it.dart
import 'package:get_it/get_it.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../../features/data/datasources/local/hive/note_local_data_source_with_hive_impl.dart'; import '../../features/data/datasources/local/note_local_data_source.dart'; import '../../features/data/repositories/repositories_impl.dart'; import '../../features/domain/repositories/repositories.dart'; import '../../features/domain/usecases/add_note.dart'; import '../../features/domain/usecases/detele_note.dart'; import '../../features/domain/usecases/get_note_by_id.dart'; import '../../features/domain/usecases/get_notes.dart'; import '../../features/domain/usecases/update_note.dart'; import '../../features/presentation/blocs/blocs.dart'; final gI = GetIt.I; Future<void> init() async { //=> BloC // gI.registerFactory( () => NoteBloc( getNotes: gI(), getNoteById: gI(), addNote: gI(), updateNote: gI(), deleteNote: gI(), ), ); gI.registerFactory(() => StatusIconsCubit()); gI.registerFactory(() => StatusGridCubit()); gI.registerFactory(() => ProfileCubit(sharedPreferences: gI())); gI.registerFactory(() => ThemeCubit(sharedPreferences: gI())); gI.registerFactory(() => SearchCubit(getNotes: gI())); //=> Usecases gI.registerLazySingleton(() => GetNotesUsecase(noteRepositories: gI())); gI.registerLazySingleton(() => GetNoteByIdUsecase(noteRepositories: gI())); gI.registerLazySingleton(() => AddNoteUsecase(noteRepositories: gI())); gI.registerLazySingleton(() => UpdateNoteUsecase(noteRepositories: gI())); gI.registerLazySingleton(() => DeleteNoteUsecase(noteRepositories: gI())); //=> Repository gI.registerLazySingleton<NoteRepositories>( () => NoteRepositoriesImpl(noteLocalDataSourse: gI()), ); //=> Datasourse gI.registerLazySingleton<NoteLocalDataSourse>( () => NoteLocalDataSourceWithHiveImpl(), ); await gI<NoteLocalDataSourse>().initDb(); //! Core !// //! External!// final sharedPreferences = await SharedPreferences.getInstance(); gI.registerLazySingleton(() => sharedPreferences); // }
0
mirrored_repositories/note_keep_up/lib/app
mirrored_repositories/note_keep_up/lib/app/provider/app_provider.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:note_app/core/core.dart'; import 'package:note_app/app/di/get_it.dart' as di; import '../../features/presentation/blocs/blocs.dart'; class AppProviders extends StatelessWidget { final Widget child; const AppProviders({ Key? key, required this.child, }) : super(key: key); @override Widget build(BuildContext context) { return MultiBlocProvider( providers: [ BlocProvider( create: (_) => di.gI<NoteBloc>() ..add(const LoadNotes(drawerSectionView: DrawerSectionView.home)), ), BlocProvider(create: (_) => di.gI<StatusGridCubit>()), BlocProvider(create: (_) => di.gI<StatusIconsCubit>()), BlocProvider(create: (_) => di.gI<ProfileCubit>()), BlocProvider(create: (_) => di.gI<SearchCubit>()), BlocProvider(create: (_) => di.gI<ThemeCubit>()..getCurrentThemeMode()), ], child: child, ); } }
0
mirrored_repositories/note_keep_up/lib/features/data
mirrored_repositories/note_keep_up/lib/features/data/model/note_model.dart
import '../../domain/entities/note.dart'; class NoteModel extends Note { const NoteModel({ required super.id, required super.title, required super.content, required super.colorIndex, required super.modifiedTime, required super.stateNote, }); }
0
mirrored_repositories/note_keep_up/lib/features/data/datasources
mirrored_repositories/note_keep_up/lib/features/data/datasources/local/note_local_data_source.dart
import 'package:dartz/dartz.dart'; import '../../model/note_model.dart'; abstract class NoteLocalDataSourse { Future<bool> initDb(); Future<List<NoteModel>> getAllNote(); Future<NoteModel> getNoteById(String noteModelById); Future<Unit> addNote(NoteModel noteModel); Future<Unit> updateNote(NoteModel noteModel); Future<Unit> deleteNote(String noteModelId); }
0
mirrored_repositories/note_keep_up/lib/features/data/datasources/local
mirrored_repositories/note_keep_up/lib/features/data/datasources/local/hive/note_local_data_source_with_hive_impl.dart
import 'package:dartz/dartz.dart'; import 'package:hive_flutter/adapters.dart'; import 'package:note_app/core/core.dart'; import 'package:path_provider/path_provider.dart'; import 'note_hive.dart'; import '../note_local_data_source.dart'; import '../../../model/note_model.dart'; import 'state_note_hive.dart'; class NoteLocalDataSourceWithHiveImpl implements NoteLocalDataSourse { final String _boxNote = 'note_box'; @override Future<bool> initDb() async { try { final appDocumentDir = await getApplicationDocumentsDirectory(); Hive.init(appDocumentDir.path); Hive.registerAdapter(NoteHiveAdapter()); Hive.registerAdapter(StateNoteHiveAdapter()); await Hive.openBox<NoteHive>(_boxNote); return true; } catch (_) { throw ConnectionException(); } } @override Future<List<NoteModel>> getAllNote() async { try { final noteBox = Hive.box<NoteHive>(_boxNote); final List<NoteModel> resultNotes = noteBox.values .map( (note) => NoteModel( id: note.id, title: note.title, content: note.content, colorIndex: note.colorIndex, modifiedTime: note.modifiedTime, stateNote: note.stateNoteHive.stateNote, ), ) .toList(); return resultNotes; } catch (_) { throw NoDataException(); } } @override Future<NoteModel> getNoteById(String noteModelById) async { try { final noteBox = Hive.box<NoteHive>(_boxNote); final NoteHive resultNote = noteBox.values.firstWhere( (element) => element.id == noteModelById, ); return NoteModel( id: resultNote.id, title: resultNote.title, content: resultNote.content, colorIndex: resultNote.colorIndex, modifiedTime: resultNote.modifiedTime, stateNote: resultNote.stateNoteHive.stateNote, ); } catch (_) { throw NoDataException(); } } @override Future<Unit> addNote(NoteModel noteModel) async { try { final noteBox = Hive.box<NoteHive>(_boxNote); final noteKey = noteModel.id; final NoteHive noteHive = NoteHive( id: noteModel.id, title: noteModel.title, content: noteModel.content, colorIndex: noteModel.colorIndex, modifiedTime: noteModel.modifiedTime, stateNoteHive: noteModel.stateNote.stateNoteHive, ); await noteBox.put(noteKey, noteHive); return unit; } catch (_) { throw NoDataException(); } } @override Future<Unit> updateNote(NoteModel noteModel) async { try { final noteBox = Hive.box<NoteHive>(_boxNote); final indexNoteId = noteModel.id; final NoteHive noteHive = NoteHive( id: noteModel.id, title: noteModel.title, content: noteModel.content, colorIndex: noteModel.colorIndex, modifiedTime: noteModel.modifiedTime, stateNoteHive: noteModel.stateNote.stateNoteHive, ); await noteBox.put(indexNoteId, noteHive); return unit; } catch (_) { throw NoDataException(); } } @override Future<Unit> deleteNote(String noteModelId) async { try { final noteBox = Hive.box<NoteHive>(_boxNote); await noteBox.delete(noteModelId); return unit; } catch (_) { throw NoDataException(); } } }
0
mirrored_repositories/note_keep_up/lib/features/data/datasources/local
mirrored_repositories/note_keep_up/lib/features/data/datasources/local/hive/state_note_hive.dart
import 'package:hive/hive.dart'; @HiveType(typeId: 2) enum StateNoteHive { @HiveField(0) unspecified, @HiveField(1) pinned, @HiveField(2) archived, @HiveField(3) trash, } class StateNoteHiveAdapter extends TypeAdapter<StateNoteHive> { @override final int typeId = 2; @override StateNoteHive read(BinaryReader reader) { return StateNoteHive.values[reader.readByte()]; } @override void write(BinaryWriter writer, StateNoteHive obj) { writer.writeByte(obj.index); } }
0
mirrored_repositories/note_keep_up/lib/features/data/datasources/local
mirrored_repositories/note_keep_up/lib/features/data/datasources/local/hive/note_hive.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'note_hive.dart'; // ************************************************************************** // TypeAdapterGenerator // ************************************************************************** class NoteHiveAdapter extends TypeAdapter<NoteHive> { @override final int typeId = 0; @override NoteHive read(BinaryReader reader) { final numOfFields = reader.readByte(); final fields = <int, dynamic>{ for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(), }; return NoteHive( id: fields[0] as String, title: fields[1] as String, content: fields[2] as String, colorIndex: fields[3] as int, modifiedTime: fields[4] as DateTime, stateNoteHive: fields[5] as StateNoteHive, ); } @override void write(BinaryWriter writer, NoteHive obj) { writer ..writeByte(6) ..writeByte(0) ..write(obj.id) ..writeByte(1) ..write(obj.title) ..writeByte(2) ..write(obj.content) ..writeByte(3) ..write(obj.colorIndex) ..writeByte(4) ..write(obj.modifiedTime) ..writeByte(5) ..write(obj.stateNoteHive); } @override int get hashCode => typeId.hashCode; @override bool operator ==(Object other) => identical(this, other) || other is NoteHiveAdapter && runtimeType == other.runtimeType && typeId == other.typeId; } class StateNoteAdapter extends TypeAdapter<StateNoteHive> { @override final int typeId = 2; @override StateNoteHive read(BinaryReader reader) { switch (reader.readByte()) { case 0: return StateNoteHive.unspecified; case 1: return StateNoteHive.pinned; case 2: return StateNoteHive.archived; case 3: return StateNoteHive.trash; default: return StateNoteHive.unspecified; } } @override void write(BinaryWriter writer, StateNoteHive obj) { switch (obj) { case StateNoteHive.unspecified: writer.writeByte(0); break; case StateNoteHive.pinned: writer.writeByte(1); break; case StateNoteHive.archived: writer.writeByte(2); break; case StateNoteHive.trash: writer.writeByte(3); break; } } @override int get hashCode => typeId.hashCode; @override bool operator ==(Object other) => identical(this, other) || other is StateNoteAdapter && runtimeType == other.runtimeType && typeId == other.typeId; }
0
mirrored_repositories/note_keep_up/lib/features/data/datasources/local
mirrored_repositories/note_keep_up/lib/features/data/datasources/local/hive/note_hive.dart
import 'package:hive/hive.dart'; import 'state_note_hive.dart'; part 'note_hive.g.dart'; @HiveType(typeId: 0) class NoteHive extends HiveObject { @HiveField(0) String id; @HiveField(1) String title; @HiveField(2) String content; @HiveField(3) int colorIndex; @HiveField(4) DateTime modifiedTime; @HiveField(5) StateNoteHive stateNoteHive; NoteHive({ required this.id, required this.title, required this.content, required this.colorIndex, required this.modifiedTime, required this.stateNoteHive, }); }
0
mirrored_repositories/note_keep_up/lib/features/data
mirrored_repositories/note_keep_up/lib/features/data/repositories/repositories_impl.dart
import 'package:dartz/dartz.dart'; import '../../../core/util/util.dart'; import '../../domain/entities/note.dart'; import '../../domain/repositories/repositories.dart'; import '../datasources/local/note_local_data_source.dart'; import '../model/note_model.dart'; class NoteRepositoriesImpl implements NoteRepositories { final NoteLocalDataSourse noteLocalDataSourse; NoteRepositoriesImpl({ required this.noteLocalDataSourse, }); @override Future<Either<Failure, List<Note>>> getAllNotes() async { try { final response = await noteLocalDataSourse.getAllNote(); return Right(response); } on NoDataException { return Left(NoDataFailure()); } } @override Future<Either<Failure, Note>> getNoteById(String noteId) async { try { final response = await noteLocalDataSourse.getNoteById(noteId); return Right(response); } on NoDataException { return Left(NoDataFailure()); } } @override Future<Either<Failure, Unit>> addNote(Note note) async { try { if (note.title.isEmpty && note.content.isEmpty) { return Left(EmpytInputFailure()); } else { final NoteModel convertToNoteModel = NoteModel( id: note.id, title: note.title, content: note.content, colorIndex: note.colorIndex, modifiedTime: note.modifiedTime, stateNote: note.stateNote, ); await noteLocalDataSourse.addNote(convertToNoteModel); return const Right(unit); } } on NoDataException { return Left(NoDataFailure()); } } @override Future<Either<Failure, Unit>> updateNote(Note note) async { try { final NoteModel convertToNoteModel = NoteModel( id: note.id, title: note.title, content: note.content, colorIndex: note.colorIndex, modifiedTime: note.modifiedTime, stateNote: note.stateNote, ); await noteLocalDataSourse.updateNote(convertToNoteModel); return const Right(unit); } on NoDataException { return Left(NoDataFailure()); } } @override Future<Either<Failure, Unit>> deleteNote(String noteId) async { try { await noteLocalDataSourse.deleteNote(noteId); return const Right(unit); } on NoDataException { return Left(NoDataFailure()); } } // Future<Either<Failure, T>> executeAndHandleError<T>( // Future<T> Function() function, // ) async { // try { // final result = await function(); // return Right(result); // } on NoDataException { // return Left(NoDataFailure()); // } // } }
0