repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/Flutter-Udacity/hello_rectangle
mirrored_repositories/Flutter-Udacity/hello_rectangle/lib/main.dart
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; void main() { runApp( MaterialApp( debugShowCheckedModeBanner: false, title: 'Hello Rectangle', home: Scaffold( appBar: AppBar( title: Text('Hello Rectangle'), ), body: HelloRectangle(), ), ), ); } class HelloRectangle extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: Container( color: Colors.greenAccent, height: 400.0, width: 300.0, child: Center( child: Text( 'Hello!', style: TextStyle(fontSize: 40.0), textAlign: TextAlign.center, ), ), ), ); } }
0
mirrored_repositories/Flutter-Udacity/hello_rectangle
mirrored_repositories/Flutter-Udacity/hello_rectangle/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:hello_rectangle/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. // await tester.pumpWidget(new MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/Flutter-Udacity/ex_04_backdrop
mirrored_repositories/Flutter-Udacity/ex_04_backdrop/lib/category_tile.dart
import 'package:ex_04_backdrop/category.dart'; import 'package:flutter/material.dart'; import 'package:ex_04_backdrop/unit_converter.dart'; const _rowHeight = 100.0; final _borderRadius = BorderRadius.circular(_rowHeight / 2); class CategoryTile extends StatelessWidget { final Category category; final ValueChanged<Category> onTap; /// The [CategoryTile] shows the name and color of a [Category] for unit /// conversions. /// /// Tapping on it brings you to the unit converter. const CategoryTile({ Key key, @required this.category, this.onTap, }) : assert(category != null), super(key: key); /// Navigates to the [UnitConverter]. void _navigateToConverter(BuildContext context) { Navigator.of(context).push(MaterialPageRoute<Null>( builder: (BuildContext context) { return Scaffold( appBar: AppBar( elevation: 1.0, title: Text( category.name, style: Theme.of(context).textTheme.display1, ), centerTitle: true, backgroundColor: category.color, ), body: UnitConverter(category: category), // This prevents the attempt to resize the screen when the keyboard // is opened resizeToAvoidBottomPadding: false, ); }, )); } @override Widget build(BuildContext context) { return Material( color: onTap == null ? Color.fromRGBO(50, 50, 50, 0.2) : Colors.transparent, child: Container( height: _rowHeight, child: InkWell( borderRadius: _borderRadius, highlightColor: category.color['hightlight'], splashColor: category.color['splash'], onTap: onTap == null ? null : () => onTap(category), child: Padding( padding: EdgeInsets.all(8.0), child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ Padding( padding: EdgeInsets.all(16.0), child: Image.asset(category.iconLocation), ), Center( child: Text( category.name, textAlign: TextAlign.center, style: Theme.of(context).textTheme.headline, ), ) ], ), ), ), ), ); } }
0
mirrored_repositories/Flutter-Udacity/ex_04_backdrop
mirrored_repositories/Flutter-Udacity/ex_04_backdrop/lib/unit_converter.dart
import 'dart:async'; import 'package:ex_04_backdrop/api.dart'; import 'package:ex_04_backdrop/category.dart'; import 'package:ex_04_backdrop/unit.dart'; import 'package:flutter/material.dart'; const _padding = EdgeInsets.all(16.0); /// [UnitConverter] where users can input amounts to convert in one [Unit] /// and retrieve the conversion in another [Unit] for a specific [Category]. class UnitConverter extends StatefulWidget { /// The current [Category] for unit conversion. final Category category; /// This [UnitConverter] takes in a [Category] with [Units]. It can't be null. const UnitConverter({ @required this.category, }) : assert(category != null); @override _UnitConverterState createState() => _UnitConverterState(); } class _UnitConverterState extends State<UnitConverter> { Unit _fromValue; Unit _toValue; double _inputValue; String _convertedValue = ''; List<DropdownMenuItem> _unitMenuItems; bool _showValidationError = false; final _inputKey = GlobalKey(debugLabel: 'inputText'); bool _showErrorUI = false; @override void initState() { super.initState(); _createDropdownMenuItems(); _setDefaults(); } @override void didUpdateWidget(UnitConverter old) { super.didUpdateWidget(old); // We update our [DropdownMenuItem] units when we switch [Categories]. if (old.category != widget.category) { _createDropdownMenuItems(); _setDefaults(); } } /// Creates fresh list of [DropdownMenuItem] widgets, given a list of [Unit]s. void _createDropdownMenuItems() { var newItems = <DropdownMenuItem>[]; for (var unit in widget.category.units) { newItems.add(DropdownMenuItem( value: unit.name, child: Container( child: Text( unit.name, softWrap: true, ), ), )); } setState(() { _unitMenuItems = newItems; }); } /// Sets the default values for the 'from' and 'to' [Dropdown]s, and the /// updated output value if a user had previously entered an input. void _setDefaults() { setState(() { _fromValue = widget.category.units[0]; _toValue = widget.category.units[1]; }); if (_inputValue != null) { _updateConversion(); } } /// Clean up conversion; trim trailing zeros, e.g. 5.500 -> 5.5, 10.0 -> 10 String _format(double conversion) { var outputNum = conversion.toStringAsPrecision(7); if (outputNum.contains('.') && outputNum.endsWith('0')) { var i = outputNum.length - 1; while (outputNum[i] == '0') { i -= 1; } outputNum = outputNum.substring(0, i + 1); } if (outputNum.endsWith('.')) { return outputNum.substring(0, outputNum.length - 1); } return outputNum; } Future<void> _updateConversion() async { // Our API has a handy convert function, so we can use that for // the Currency [Category] if (widget.category.name == apiCategory['name']) { final api = Api(); final conversion = await api.convert(apiCategory['route'], _inputValue.toString(), _fromValue.name, _toValue.name); // API error or not connected to the internet if (conversion == null) { setState(() { _showErrorUI = true; }); } else { setState(() { _convertedValue = _format(conversion); }); } } else { // For the static units, we do the conversion ourselves setState(() { _convertedValue = _format( _inputValue * (_toValue.conversion / _fromValue.conversion)); }); } } void _updateInputValue(String input) { setState(() { if (input == null || input.isEmpty) { _convertedValue = ''; } else { // Even though we are using the numerical keyboard, we still have to check // for non-numerical input such as '5..0' or '6 -3' try { final inputDouble = double.parse(input); _showValidationError = false; _inputValue = inputDouble; _updateConversion(); } on Exception catch (e) { print('Error: $e'); _showValidationError = true; } } }); } Unit _getUnit(String unitName) { return widget.category.units.firstWhere( (Unit unit) { return unit.name == unitName; }, orElse: null, ); } void _updateFromConversion(dynamic unitName) { setState(() { _fromValue = _getUnit(unitName); }); if (_inputValue != null) { _updateConversion(); } } void _updateToConversion(dynamic unitName) { setState(() { _toValue = _getUnit(unitName); }); if (_inputValue != null) { _updateConversion(); } } Widget _createDropdown(String currentValue, ValueChanged<dynamic> onChanged) { return Container( margin: EdgeInsets.only(top: 16.0), decoration: BoxDecoration( // This sets the color of the [DropdownButton] itself color: Colors.grey[50], border: Border.all( color: Colors.grey[400], width: 1.0, ), ), padding: EdgeInsets.symmetric(vertical: 8.0), child: Theme( // This sets the color of the [DropdownMenuItem] data: Theme.of(context).copyWith( canvasColor: Colors.grey[50], ), child: DropdownButtonHideUnderline( child: ButtonTheme( alignedDropdown: true, child: DropdownButton( value: currentValue, items: _unitMenuItems, onChanged: onChanged, style: Theme.of(context).textTheme.title, ), ), ), ), ); } @override Widget build(BuildContext context) { if (widget.category.units == null || (widget.category.name == apiCategory['name'] && _showErrorUI)) { return SingleChildScrollView( child: Container( margin: _padding, padding: _padding, decoration: BoxDecoration( borderRadius: BorderRadius.circular(16.0), color: widget.category.color['error'], ), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Icon( Icons.error_outline, size: 180.0, color: Colors.white, ), Text( "Oh no! We can't connect right now!", textAlign: TextAlign.center, style: Theme.of(context).textTheme.headline.copyWith( color: Colors.white, ), ), ], ), ), ); } final input = Padding( padding: _padding, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ // This is the widget that accepts text input. In this case, it // accepts numbers and calls the onChanged property on update. // You can read more about it here: https://flutter.io/text-input TextField( key: _inputKey, style: Theme.of(context).textTheme.display1, decoration: InputDecoration( labelStyle: Theme.of(context).textTheme.display1, errorText: _showValidationError ? 'Invalid number entered' : null, labelText: 'Input', border: OutlineInputBorder( borderRadius: BorderRadius.circular(0.0), ), ), // Since we only want numerical input, we use a number keyboard. There // are also other keyboards for dates, emails, phone numbers, etc. keyboardType: TextInputType.number, onChanged: _updateInputValue, ), _createDropdown(_fromValue.name, _updateFromConversion), ], ), ); final arrows = RotatedBox( quarterTurns: 1, child: Icon( Icons.compare_arrows, size: 40.0, ), ); final output = Padding( padding: _padding, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ InputDecorator( child: Text( _convertedValue, style: Theme.of(context).textTheme.display1, ), decoration: InputDecoration( labelText: 'Output', labelStyle: Theme.of(context).textTheme.display1, border: OutlineInputBorder( borderRadius: BorderRadius.circular(0.0), ), ), ), _createDropdown(_toValue.name, _updateToConversion), ], ), ); final converter = ListView( children: [ input, arrows, output, ], ); // Based on the orientation of the parent widget, figure out how to best // lay out our converter. return Padding( padding: _padding, child: OrientationBuilder( builder: (BuildContext context, Orientation orientation) { if (orientation == Orientation.portrait) { return converter; } else { return Center( child: Container( width: 450.0, child: converter, ), ); } }, ), ); } }
0
mirrored_repositories/Flutter-Udacity/ex_04_backdrop
mirrored_repositories/Flutter-Udacity/ex_04_backdrop/lib/api.dart
import 'dart:async'; import 'dart:convert' show json, utf8; import 'dart:io'; // For this app, the only [Category] endpoint we retrieve from an API is Currency. /// /// If we had more, we could keep a list of [Categories] here. const apiCategory = { 'name': 'Currency', 'route': 'currency', }; class Api { final HttpClient _httpClient = HttpClient(); final String _url = 'flutter.udacity.com'; Future<double> convert( String category, String amount, String fromUnit, String toUnit) async { final uri = Uri.https(_url, '/$category/convert', {'amount': amount, 'from': fromUnit, 'to': toUnit}); final jsonResponse = await _getJson(uri); if (jsonResponse == null || jsonResponse['status'] == null) { print('Error retrieving conversion.'); return null; } else if (jsonResponse['status'] == 'error') { print(jsonResponse['message']); return null; } return jsonResponse['conversion'].toDouble(); } Future<Map<String, dynamic>> _getJson(Uri uri) async { try { final httpRequest = await _httpClient.getUrl(uri); final httpResponse = await httpRequest.close(); if (httpResponse.statusCode != HttpStatus.OK) { return null; } final responseBody = await httpResponse.transform(utf8.decoder).join(); return json.decode(responseBody); } on Exception catch (e) { print('$e'); return null; } } Future<List> getUnits(String category) async { final uri = Uri.https(_url, '/$category'); final jsonResponse = await _getJson(uri); if (jsonResponse == null || jsonResponse['units'] == null) { print('Error retrieving units.'); return null; } return jsonResponse['units']; } }
0
mirrored_repositories/Flutter-Udacity/ex_04_backdrop
mirrored_repositories/Flutter-Udacity/ex_04_backdrop/lib/unit.dart
import 'package:meta/meta.dart'; class Unit{ final String name; final double conversion; /// A [Unit] stores its name and conversion factor. /// /// An example would be 'Meter' and '1.0'. const Unit({ @required this.name, @required this.conversion, }) : assert(name != null), assert(conversion != null); /// Creates a [Unit] from a JSON object. Unit.fromJson(Map jsonMap) : name = jsonMap['name'], conversion = jsonMap['conversion'].toDouble(), assert(name != null), assert(conversion != null); }
0
mirrored_repositories/Flutter-Udacity/ex_04_backdrop
mirrored_repositories/Flutter-Udacity/ex_04_backdrop/lib/category.dart
import 'package:ex_04_backdrop/unit.dart'; import 'package:flutter/material.dart'; import 'package:meta/meta.dart'; class Category { final String name; final ColorSwatch color; final List<Unit> units; final String iconLocation; const Category( {@required this.name, @required this.color, @required this.units, @required this.iconLocation}) : assert(name != null), assert(color != null), assert(units != null), assert(iconLocation != null); }
0
mirrored_repositories/Flutter-Udacity/ex_04_backdrop
mirrored_repositories/Flutter-Udacity/ex_04_backdrop/lib/backdrop.dart
import 'dart:math' as math; import 'package:ex_04_backdrop/category.dart'; import 'package:flutter/material.dart'; const double _kFlingVelocity = 2.0; class _BackdropPanel extends StatelessWidget { const _BackdropPanel({ Key key, this.onTap, this.onVerticalDragUpdate, this.onVerticalDragEnd, this.title, this.child, }) : super(key: key); final VoidCallback onTap; final GestureDragUpdateCallback onVerticalDragUpdate; final GestureDragEndCallback onVerticalDragEnd; final Widget title; final Widget child; @override Widget build(BuildContext context) { return Material( elevation: 2.0, borderRadius: BorderRadius.only( topLeft: Radius.circular(16.0), topRight: Radius.circular(16.0), ), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ GestureDetector( behavior: HitTestBehavior.opaque, onVerticalDragUpdate: onVerticalDragUpdate, onVerticalDragEnd: onVerticalDragEnd, onTap: onTap, child: Container( height: 48.0, padding: EdgeInsetsDirectional.only(start: 16.0), alignment: AlignmentDirectional.centerStart, child: DefaultTextStyle( style: Theme.of(context).textTheme.subhead, child: title, ), ), ), Divider( height: 1.0, ), Expanded( child: child, ), ], ), ); } } class _BackdropTitle extends AnimatedWidget { final Widget frontTitle; final Widget backTitle; const _BackdropTitle({ Key key, Listenable listenable, this.frontTitle, this.backTitle, }) : super(key: key, listenable: listenable); @override Widget build(BuildContext context) { final Animation<double> animation = this.listenable; return DefaultTextStyle( style: Theme.of(context).primaryTextTheme.title, softWrap: false, overflow: TextOverflow.ellipsis, // Here, we do a custom cross fade between backTitle and frontTitle. // This makes a smooth animation between the two texts. child: Stack( children: <Widget>[ Opacity( opacity: CurvedAnimation( parent: ReverseAnimation(animation), curve: Interval(0.5, 1.0), ).value, child: backTitle, ), Opacity( opacity: CurvedAnimation( parent: animation, curve: Interval(0.5, 1.0), ).value, child: frontTitle, ), ], ), ); } } class Backdrop extends StatefulWidget { final Category currentCategory; final Widget frontPanel; final Widget backPanel; final Widget frontTitle; final Widget backTitle; const Backdrop({ @required this.currentCategory, @required this.frontPanel, @required this.backPanel, @required this.frontTitle, @required this.backTitle, }) : assert(currentCategory != null), assert(frontPanel != null), assert(backPanel != null), assert(frontTitle != null), assert(backTitle != null); @override _BackdropState createState() => _BackdropState(); } class _BackdropState extends State<Backdrop> with SingleTickerProviderStateMixin { final GlobalKey _backdropKey = GlobalKey(debugLabel: 'Backdrop'); AnimationController _controller; @override void initState() { super.initState(); // This creates an [AnimationController] that can allows for animation for // the BackdropPanel. 0.00 means that the front panel is in "tab" (hidden) // mode, while 1.0 means that the front panel is open. _controller = AnimationController( duration: Duration(milliseconds: 300), value: 1.0, vsync: this, ); } bool get _backdropPanelVisible { final AnimationStatus status = _controller.status; return status == AnimationStatus.completed || status == AnimationStatus.forward; } double get _backdropHeight { final RenderBox renderBox = _backdropKey.currentContext.findRenderObject(); return renderBox.size.height; } void _handleDragUpdate(DragUpdateDetails details) { if (_controller.isAnimating || _controller.status == AnimationStatus.completed) return; _controller.value -= details.primaryDelta / _backdropHeight; } void _handleDragEnd(DragEndDetails details) { if (_controller.isAnimating || _controller.status == AnimationStatus.completed) return; final double flingVelocity = details.velocity.pixelsPerSecond.dy / _backdropHeight; if (flingVelocity < 0.0) _controller.fling(velocity: math.max(_kFlingVelocity, -flingVelocity)); else if (flingVelocity > 0.0) _controller.fling(velocity: math.min(-_kFlingVelocity, -flingVelocity)); else _controller.fling( velocity: _controller.value < 0.5 ? -_kFlingVelocity : _kFlingVelocity); } Widget _buildStack(BuildContext context, BoxConstraints constraints) { const double panelTitleHeight = 48.0; final Size panelSize = constraints.biggest; final double panelTop = panelSize.height - panelTitleHeight; Animation<RelativeRect> panelAnimation = RelativeRectTween( begin: RelativeRect.fromLTRB( 0.0, panelTop, 0.0, panelTop - panelSize.height), end: RelativeRect.fromLTRB(0.0, 0.0, 0.0, 0.0), ).animate(_controller.view); return Container( key: _backdropKey, color: widget.currentCategory.color, child: Stack( children: <Widget>[ widget.backPanel, PositionedTransition( rect: panelAnimation, child: _BackdropPanel( onTap: _toggleBackdropPanelVisibility, onVerticalDragUpdate: _handleDragUpdate, onVerticalDragEnd: _handleDragEnd, title: Text(widget.currentCategory.name), child: widget.frontPanel, ), ), ], ), ); } void _toggleBackdropPanelVisibility() { _controller.fling( velocity: _backdropPanelVisible ? -_kFlingVelocity : _kFlingVelocity); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: widget.currentCategory.color, elevation: 0.0, leading: IconButton( onPressed: _toggleBackdropPanelVisibility, icon: AnimatedIcon( icon: AnimatedIcons.close_menu, progress: _controller.view, ), ), title: _BackdropTitle( listenable: _controller.view, frontTitle: widget.frontTitle, backTitle: widget.backTitle, ), ), body: LayoutBuilder( builder: _buildStack, ), resizeToAvoidBottomPadding: false, ); } }
0
mirrored_repositories/Flutter-Udacity/ex_04_backdrop
mirrored_repositories/Flutter-Udacity/ex_04_backdrop/lib/category_route.dart
import 'dart:async'; import 'dart:convert'; import 'package:ex_04_backdrop/category.dart'; import 'package:ex_04_backdrop/unit.dart'; import 'package:flutter/material.dart'; import 'api.dart'; import 'backdrop.dart'; import 'category_tile.dart'; import 'unit_converter.dart'; class CategoryRoute extends StatefulWidget { const CategoryRoute(); @override _CategoryRouteState createState() => _CategoryRouteState(); } final _backgroundColor = Colors.green[100]; class _CategoryRouteState extends State<CategoryRoute> { Category _defaultCategory; Category _currentCategory; final _categories = <Category>[]; // static const _categoryNames = <String>[ // 'Length', // 'Area', // 'Volume', // 'Mass', // 'Time', // 'Digital Storage', // 'Energy', // 'Currency', // ]; static const _baseColors = <ColorSwatch>[ ColorSwatch(0xFF6AB7A8, { 'highlight': Color(0xFF6AB7A8), 'splash': Color(0xFF0ABC9B), }), ColorSwatch(0xFFFFD28E, { 'highlight': Color(0xFFFFD28E), 'splash': Color(0xFFFFA41C), }), ColorSwatch(0xFFFFB7DE, { 'highlight': Color(0xFFFFB7DE), 'splash': Color(0xFFF94CBF), }), ColorSwatch(0xFF8899A8, { 'highlight': Color(0xFF8899A8), 'splash': Color(0xFFA9CAE8), }), ColorSwatch(0xFFEAD37E, { 'highlight': Color(0xFFEAD37E), 'splash': Color(0xFFFFE070), }), ColorSwatch(0xFF81A56F, { 'highlight': Color(0xFF81A56F), 'splash': Color(0xFF7CC159), }), ColorSwatch(0xFFD7C0E2, { 'highlight': Color(0xFFD7C0E2), 'splash': Color(0xFFCA90E5), }), ColorSwatch(0xFFCE9A9A, { 'highlight': Color(0xFFCE9A9A), 'splash': Color(0xFFF94D56), 'error': Color(0xFF912D2D), }), ]; static const _icons = <String>[ 'assets/icons/length.png', 'assets/icons/area.png', 'assets/icons/volume.png', 'assets/icons/mass.png', 'assets/icons/time.png', 'assets/icons/digital_storage.png', 'assets/icons/power.png', 'assets/icons/currency.png', ]; @override Future<void> didChangeDependencies() async { super.didChangeDependencies(); // We have static unit conversions located in our // assets/data/regular_units.json if (_categories.isEmpty) { await _retrieveLocalCategories(); await _retrieveApiCategory(); } } Future<void> _retrieveLocalCategories() async { final json = DefaultAssetBundle .of(context) .loadString('assets/data/regular_units.json'); final data = JsonDecoder().convert(await json); if (data is! Map) { throw ('Data retrieved from API is not a Map'); } var categoryIndex = 0; data.keys.forEach((key) { final List<Unit> units = data[key].map<Unit>((dynamic data) => Unit.fromJson(data)).toList(); var category = Category( name: key, units: units, color: _baseColors[categoryIndex], iconLocation: _icons[categoryIndex], ); setState(() { if (categoryIndex == 0) { _defaultCategory = category; } _categories.add(category); }); categoryIndex += 1; }); } /// Retrieves a [Category] and its [Unit]s from an API on the web Future<void> _retrieveApiCategory() async { // Add a placeholder while we fetch the Currency category using the API setState(() { _categories.add(Category( name: apiCategory['name'], units: [], color: _baseColors.last, iconLocation: _icons.last, )); }); final api = Api(); final jsonUnits = await api.getUnits(apiCategory['route']); // If the API errors out or we have no internet connection, this category // remains in placeholder mode (disabled) if (jsonUnits != null) { final units = <Unit>[]; for (var unit in jsonUnits) { units.add(Unit.fromJson(unit)); } setState(() { _categories.removeLast(); _categories.add(Category( name: apiCategory['name'], units: units, color: _baseColors.last, iconLocation: _icons.last, )); }); } } // @override // void initState() { // super.initState(); // for (int i = 0; i < _categoryNames.length; i++) { // var category = Category( // name: _categoryNames[i], // color: _baseColors[i], // iconLocation: Icons.cake, // units: _retrieveUnitList(_categoryNames[i]), // ); // if (i == 0) { // _defaultCategory = category; // } // _categories.add(category); // } // } // TODO: Fill out this function /// Function to call when a [Category] is tapped. void _onCategoryTap(Category category) { setState(() { _currentCategory = category; }); } /// Makes the correct number of rows for the list view. /// /// For portrait, we use a [ListView]. Widget _buildCategoryWidgets(Orientation orientation) { if (orientation == Orientation.portrait) { return ListView.builder( itemBuilder: (BuildContext context, int index) { var _category = _categories[index]; return CategoryTile( category: _category, onTap: _category.name == apiCategory['name'] && _category.units.isEmpty ? null : _onCategoryTap, ); }, itemCount: _categories.length, ); } else { return GridView.count( crossAxisCount: 2, childAspectRatio: 3.0, children: _categories.map((Category c) { return CategoryTile( category: c, onTap: _onCategoryTap, ); }).toList(), ); } } @override Widget build(BuildContext context) { if (_categories.isEmpty) { return Center( child: Container( height: 40.0, width: 40.0, child: CircularProgressIndicator(), ), ); } assert(debugCheckHasMediaQuery(context)); final listView = Padding( padding: EdgeInsets.only( left: 8.0, right: 8.0, bottom: 48.0, ), child: _buildCategoryWidgets(MediaQuery.of(context).orientation), ); return Backdrop( currentCategory: _currentCategory == null ? _defaultCategory : _currentCategory, frontPanel: _currentCategory == null ? UnitConverter(category: _defaultCategory) : UnitConverter(category: _currentCategory), backPanel: listView, frontTitle: Text('Unit Converter'), backTitle: Text('Select a Category'), ); } /// Returns a list of mock [Unit]s. // List<Unit> _retrieveUnitList(String categoryName) { // return List.generate(10, (int i) { // i += 1; // return Unit( // name: '$categoryName Unit $i', // conversion: i.toDouble(), // ); // }); // } }
0
mirrored_repositories/Flutter-Udacity/ex_04_backdrop
mirrored_repositories/Flutter-Udacity/ex_04_backdrop/lib/main.dart
import 'package:flutter/material.dart'; import 'category_route.dart'; void main() => runApp(new MyApp()); class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return new MaterialApp( debugShowCheckedModeBanner: false, title: 'Unit Converter', theme: ThemeData( fontFamily: 'Raleway', textTheme: Theme.of(context).textTheme.apply( bodyColor: Colors.black, displayColor: Colors.grey[600], ), // This colors the [InputOutlineBorder] when it is selected primaryColor: Colors.grey[500], textSelectionHandleColor: Colors.green[500], ), home: CategoryRoute(), ); } }
0
mirrored_repositories/Flutter-Udacity/ex_04_backdrop
mirrored_repositories/Flutter-Udacity/ex_04_backdrop/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:ex_04_backdrop/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(new MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/Flutter-Udacity/ex_02_category_widget
mirrored_repositories/Flutter-Udacity/ex_02_category_widget/lib/category.dart
import 'package:flutter/material.dart'; class Category extends StatelessWidget { get _borderRadius => new BorderRadius.circular(50.0); get _heightRow => 50.0; @override Widget build(BuildContext context) { return Material( child: Container( height: _heightRow, child: InkWell( borderRadius: _borderRadius, onTap: () { print('On tap row'); }, child: Padding( padding: EdgeInsets.all(8.0), child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ Padding( padding: EdgeInsets.only(right: 16.0), child: Icon(Icons.cake), ), Center( child: Text( "Testing", textAlign: TextAlign.center, style: Theme.of(context).textTheme.display1.copyWith( color: Colors.grey, fontSize: 24.0, fontWeight: FontWeight.w700, ), ), ) ], ), ), ), ), ); } }
0
mirrored_repositories/Flutter-Udacity/ex_02_category_widget
mirrored_repositories/Flutter-Udacity/ex_02_category_widget/lib/main.dart
import 'package:ex_02_category_widget/category.dart'; import 'package:flutter/material.dart'; void main() => runApp(new MyApp()); class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return new MaterialApp( title: 'Flutter Demo', theme: new ThemeData( primarySwatch: Colors.blue, ), home: Scaffold( backgroundColor: Colors.white, body: Center( child: Category(), ), ), ); } }
0
mirrored_repositories/Flutter-Udacity/ex_02_category_widget
mirrored_repositories/Flutter-Udacity/ex_02_category_widget/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:ex_02_category_widget/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(new MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/Flutter-Udacity/ex_03_category_route
mirrored_repositories/Flutter-Udacity/ex_03_category_route/lib/unit.dart
import 'package:meta/meta.dart'; class Unit { final String name; final double conversion; /// A [Unit] stores its name and conversion factor. /// /// An example would be 'Meter' and '1.0'. const Unit({ @required this.name, @required this.conversion, }) : assert(name != null), assert(conversion != null); /// Creates a [Unit] from a JSON object. Unit.fromJson(Map jsonMap) : name = jsonMap['name'], conversion = jsonMap['conversion'].toDouble(), assert(name != null), assert(conversion != null); }
0
mirrored_repositories/Flutter-Udacity/ex_03_category_route
mirrored_repositories/Flutter-Udacity/ex_03_category_route/lib/category.dart
import 'package:ex_03_category_route/converter_route_input.dart'; import 'package:ex_03_category_route/unit.dart'; import 'package:flutter/material.dart'; final _rowHeight = 100.0; final _borderRadius = BorderRadius.circular(_rowHeight / 2); class Category extends StatelessWidget { final String name; final ColorSwatch color; final IconData iconLocation; final List<Unit> units; const Category( {Key key, @required this.name, @required this.color, @required this.iconLocation, @required this.units}) : assert(name != null), assert(color != null), assert(iconLocation != null), assert(units != null), super(key: key); @override Widget build(BuildContext context) { return Material( color: Colors.white, child: Container( height: _rowHeight, child: InkWell( borderRadius: _borderRadius, onTap: () { print('On tap row'); _navigateToConverter(context); }, child: Padding( padding: EdgeInsets.all(8.0), child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ Padding( padding: EdgeInsets.only(right: 16.0), child: Icon(Icons.cake), ), Center( child: Text( name, textAlign: TextAlign.center, style: Theme.of(context).textTheme.display1.copyWith( color: color, fontSize: 24.0, fontWeight: FontWeight.w700, ), ), ) ], ), ), ), ), ); } void _navigateToConverter(BuildContext context) { if (Navigator.of(context).canPop()) { Navigator.of(context).pop(); } Navigator .of(context) .push(MaterialPageRoute<Null>(builder: (BuildContext context) { return Scaffold( appBar: AppBar( elevation: 1.0, title: Text( name, style: Theme.of(context).textTheme.display1, ), ), body: ConverterRouteInput( color: color, name: name, units: units, ), resizeToAvoidBottomPadding: false, ); })); } }
0
mirrored_repositories/Flutter-Udacity/ex_03_category_route
mirrored_repositories/Flutter-Udacity/ex_03_category_route/lib/category_route.dart
import 'package:ex_03_category_route/category.dart'; import 'package:ex_03_category_route/unit.dart'; import 'package:flutter/material.dart'; class CategoryRoute extends StatefulWidget { @override State<StatefulWidget> createState() => _MyCategoryRoutePageState(); } class _MyCategoryRoutePageState extends State<CategoryRoute> { var _backgroundColor = Colors.white; static const _categoryNames = <String>[ 'Length', 'Area', 'Volume', 'Mass', 'Time', 'Digital Storage', 'Energy', 'Currency', ]; static const _baseColors = <Color>[ Colors.teal, Colors.orange, Colors.pinkAccent, Colors.blueAccent, Colors.yellow, Colors.greenAccent, Colors.purpleAccent, Colors.red, ]; /// Returns a list of mock [Unit]s. List<Unit> _retrieveUnitList(String categoryName) { return List.generate(10, (int i) { i += 1; return Unit( name: '$categoryName Unit $i', conversion: i.toDouble(), ); }); } @override Widget build(BuildContext context) { final appbar = AppBar( elevation: 0.0, title: Text( 'Unit Converter', style: TextStyle( color: Colors.black, fontSize: 30.0, ), ), backgroundColor: _backgroundColor, ); final categories = <Category>[]; for (var i = 0; i < _categoryNames.length; i++) { categories.add(Category( name: _categoryNames[i], color: _baseColors[i], iconLocation: Icons.cake, units: _retrieveUnitList(_categoryNames[i]), )); } final listView = Container( color: _backgroundColor, padding: EdgeInsets.symmetric(horizontal: 8.0), child: _buildCategoryWidgets(categories), ); return Scaffold( appBar: appbar, body: listView, ); } Widget _buildCategoryWidgets(List<Widget> categories) { return ListView.builder( itemBuilder: (BuildContext context, int index) => categories[index], itemCount: categories.length, ); } }
0
mirrored_repositories/Flutter-Udacity/ex_03_category_route
mirrored_repositories/Flutter-Udacity/ex_03_category_route/lib/converter_route.dart
import 'package:ex_03_category_route/unit.dart'; import 'package:flutter/material.dart'; import 'package:meta/meta.dart'; class ConverterRoute extends StatefulWidget { /// Units for this [Category]. final List<Unit> units; /// This [ConverterRoute] requires the name, color, and units to not be null. // TODO: Pass in the [Category]'s name and color const ConverterRoute({ @required this.units, }) : assert(units != null); @override State<StatefulWidget> createState() => _MyConverterRouteState(); } class _MyConverterRouteState extends State<ConverterRoute>{ @override Widget build(BuildContext context) { // Here is just a placeholder for a list of mock units final unitWidgets = widget.units.map((Unit unit) { // TODO: Set the color for this Container return Container( margin: EdgeInsets.all(8.0), padding: EdgeInsets.all(16.0), child: Column( children: <Widget>[ Text( unit.name, style: Theme.of(context).textTheme.headline, ), Text( 'Conversion: ${unit.conversion}', style: Theme.of(context).textTheme.subhead, ), ], ), ); }).toList(); return ListView( children: unitWidgets, ); } }
0
mirrored_repositories/Flutter-Udacity/ex_03_category_route
mirrored_repositories/Flutter-Udacity/ex_03_category_route/lib/main.dart
import 'package:ex_03_category_route/category_route.dart'; import 'package:flutter/material.dart'; void main() => runApp(new MyApp()); class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return new MaterialApp( title: 'Flutter Demo', debugShowCheckedModeBanner: false, home: CategoryRoute(), ); } }
0
mirrored_repositories/Flutter-Udacity/ex_03_category_route
mirrored_repositories/Flutter-Udacity/ex_03_category_route/lib/converter_route_input.dart
import 'package:ex_03_category_route/unit.dart'; import 'package:flutter/material.dart'; const _padding = EdgeInsets.all(16.0); class ConverterRouteInput extends StatefulWidget { /// Units for this [Category]. final List<Unit> units; final String name; final Color color; /// This [ConverterRoute] requires the name, color, and units to not be null. const ConverterRouteInput({ @required this.name, @required this.color, @required this.units, }) : assert(name != null), assert(color != null), assert(units != null); @override ConverterRouteInputState createState() => ConverterRouteInputState(); } class ConverterRouteInputState extends State<ConverterRouteInput> { Unit _fromValue; Unit _toValue; bool _showValidationError = false; double _inputValue; String _convertedValue = ''; List<DropdownMenuItem> _unitMenuItems; @override void initState() { super.initState(); _createDropdownMenuItems(); _setDefaults(); } /// Sets the default values for the 'from' and 'to' [Dropdown]s. void _setDefaults() { setState(() { _fromValue = widget.units[0]; _toValue = widget.units[1]; }); } /// Creates fresh list of [DropdownMenuItem] widgets, given a list of [Unit]s. void _createDropdownMenuItems() { var newItems = <DropdownMenuItem>[]; for (var unit in widget.units) { newItems.add(DropdownMenuItem( value: unit.name, child: Container( child: Text( unit.name, softWrap: true, ), ), )); } setState(() { _unitMenuItems = newItems; }); } @override Widget build(BuildContext context) { final input = Padding( padding: _padding, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ TextField( style: Theme.of(context).textTheme.body1, decoration: InputDecoration( labelStyle: Theme.of(context).textTheme.body1, errorText: _showValidationError ? 'Invalid number entered' : null, border: OutlineInputBorder(borderRadius: BorderRadius.circular(8.0)), labelText: "Input", ), keyboardType: TextInputType.number, onChanged: _updateInputValue, ), _createDropdown(_fromValue.name, _updateFromConversion), ], ), ); final arrows = RotatedBox( quarterTurns: 1, child: Icon( Icons.compare_arrows, size: 40.0, ), ); final output = Padding( padding: _padding, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ InputDecorator( child: Text( _convertedValue, style: Theme.of(context).textTheme.body1, ), decoration: InputDecoration( labelText: 'Output', labelStyle: Theme.of(context).textTheme.body1, border: OutlineInputBorder( borderRadius: BorderRadius.circular(8.0), ), ), ), _createDropdown(_toValue.name, _updateToConversion), ], ), ); final converter = Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [input, arrows, output], ); return Padding( padding: _padding, child: converter, ); } void _updateInputValue(String input) { setState(() { if (input == null || input.isEmpty) { _convertedValue = ''; } else { // Even though we are using the numerical keyboard, we still have to check // for non-numerical input such as '5..0' or '6 -3' try { final inputDouble = double.parse(input); _showValidationError = false; _inputValue = inputDouble; _updateConversion(); } on Exception catch (e) { print('Error: $e'); _showValidationError = true; } } }); } void _updateToConversion(dynamic unitName) { setState(() { _toValue = _getUnit(unitName); }); if (_inputValue != null) { _updateConversion(); } } /// Clean up conversion; trim trailing zeros, e.g. 5.500 -> 5.5, 10.0 -> 10 String _format(double conversion) { var outputNum = conversion.toStringAsPrecision(7); if (outputNum.contains('.') && outputNum.endsWith('0')) { var i = outputNum.length - 1; while (outputNum[i] == '0') { i -= 1; } outputNum = outputNum.substring(0, i + 1); } if (outputNum.endsWith('.')) { return outputNum.substring(0, outputNum.length - 1); } return outputNum; } Unit _getUnit(String unitName) { return widget.units.firstWhere( (Unit unit) { return unit.name == unitName; }, orElse: null, ); } void _updateConversion() { setState(() { _convertedValue = _format(_inputValue * (_toValue.conversion / _fromValue.conversion)); }); } void _updateFromConversion(dynamic unitName) { setState(() { _fromValue = _getUnit(unitName); }); if (_inputValue != null) { _updateConversion(); } } _createDropdown(String currentValue, ValueChanged<dynamic> onChanged) { return Container( margin: EdgeInsets.only(top: 16.0), decoration: BoxDecoration( color: Colors.grey[50], borderRadius: BorderRadius.circular(8.0), border: Border.all( color: Colors.grey[400], width: 1.0, )), padding: EdgeInsets.symmetric(vertical: 8.0), child: Theme( data: Theme.of(context).copyWith(canvasColor: Colors.grey[50]), child: DropdownButtonHideUnderline( child: ButtonTheme( alignedDropdown: true, child: DropdownButton( value: currentValue, items: _unitMenuItems, onChanged: onChanged, style: Theme.of(context).textTheme.body1, ), ), ), ), ); } }
0
mirrored_repositories/Flutter-Udacity/ex_03_category_route
mirrored_repositories/Flutter-Udacity/ex_03_category_route/test/widget_test.dart
// This is a basic Flutter widget test. // To perform an interaction with a widget in your test, use the WidgetTester utility that Flutter // provides. For example, you can send tap and scroll gestures. You can also use WidgetTester to // find child widgets in the widget tree, read text, and verify that the values of widget properties // are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:ex_03_category_route/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(new MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/mealsApp
mirrored_repositories/mealsApp/lib/mealsHomepage.dart
import 'package:flutter/material.dart'; import 'package:meals_app/categoriesScree.dart'; import 'package:meals_app/settings.dart'; import 'dummy_data.dart'; import 'meals.dart'; class mealsHomePage extends StatefulWidget { const mealsHomePage({Key? key}) : super(key: key); @override _mealsHomePageState createState() => _mealsHomePageState(); } class _mealsHomePageState extends State<mealsHomePage> { Iterable<Meal> mylist = dunny_names; var abc = true; void newList(Map<String,bool> mapp){ setState(() { mylist = dunny_names.where((element){ if(element.isGlutenFree && mapp['glutenFree'] == false){ return false; } if(element.isLactoseFree && mapp['_lactoseFree'] == false){ return false; } if(element.isVegetarian && mapp['_isVegetarian'] == false){ return false; } if(element.isVegan && mapp['_isVegan'] == false){ return false; } return true; }); }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Theme.of(context).primaryColor, title: Text('MealsApp'), ), drawer: Drawer( child: Column( children:[ Container( alignment: Alignment.center, width: double.infinity, height: 130, color: Theme.of(context).accentColor, padding: EdgeInsets.all(35), child: Text("Cooking !!!!", softWrap: true, style: TextStyle(fontSize: 30.0, fontWeight: FontWeight.bold,color: Colors.black),), ), SizedBox(height: 20.0,), ListTile(onTap: ()=>Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (_)=>mealsHomePage())), leading: Icon(Icons.no_meals, size: 30,), title: Text("Meals", style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),),), SizedBox(height: 5.0,), ListTile(onTap: ()=>Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (_)=>settings(newList))),leading: Icon(Icons.settings, size: 30,), title: Text("Settings", style: TextStyle(fontSize: 20.0,fontWeight: FontWeight.bold),),), ] ) ), body: categoriesScreen(mylist), ); } }
0
mirrored_repositories/mealsApp
mirrored_repositories/mealsApp/lib/elementContainer.dart
import 'package:flutter/material.dart'; import 'meals.dart'; import 'meals_screen.dart'; class myContainer extends StatelessWidget { final String title; final Color color; final String id; final Iterable<Meal> lists; myContainer({this.id = '1', this.title = 'mihir', this.color = Colors.blue, this.lists = const[]}); @override Widget build(BuildContext context) { return InkWell( splashColor: Theme.of(context).accentColor, onTap: () => Navigator.of(context) .push(MaterialPageRoute(builder: (_) => mealsScreen(id, title,lists))), child: Container( padding: EdgeInsets.all(12.0), child: Center( child: Text( title, style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16.0), ), ), decoration: BoxDecoration( borderRadius: BorderRadius.circular(12.0), gradient: LinearGradient( begin: Alignment.topLeft, end: Alignment.bottomRight, colors: [color.withOpacity(0.6), color], )), ), ); } }
0
mirrored_repositories/mealsApp
mirrored_repositories/mealsApp/lib/categoriesScree.dart
import 'package:flutter/material.dart'; import 'package:meals_app/dummy_data.dart'; import 'elementContainer.dart'; import 'meals.dart'; class categoriesScreen extends StatelessWidget { Iterable<Meal> mylist; categoriesScreen(this.mylist); @override Widget build(BuildContext context) { print(mylist); return GridView( padding: EdgeInsets.all(20.0), children: DUMMY_CATEGORIES.map((tx) { return myContainer( id: tx.id, title: tx.title, color: tx.color, lists: mylist, ); }).toList(), gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent( maxCrossAxisExtent: 200, crossAxisSpacing: 20, mainAxisSpacing: 20, childAspectRatio: 3 / 2), ); } }
0
mirrored_repositories/mealsApp
mirrored_repositories/mealsApp/lib/category.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class Category { final String id; final String title; final Color color; const Category({ this.id = '1', this.title = "ok", this.color = Colors.orange, }); }
0
mirrored_repositories/mealsApp
mirrored_repositories/mealsApp/lib/tabs_screen.dart
import 'package:flutter/material.dart'; import 'package:meals_app/settings.dart'; import 'categoriesScree.dart'; import 'favouritesScreen.dart'; import 'mealsHomepage.dart'; class tabsScreen extends StatefulWidget { @override _tabsScreenState createState() => _tabsScreenState(); } class _tabsScreenState extends State<tabsScreen> { final List abc = [mealsHomePage(), favouritesScreen()]; var _selectedindex = 0 ; void _selectindex(int index){ setState(() { _selectedindex = index; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: _selectedindex == 0 ? Text('Meals App'): Text('Favourites Screen'), ), body: abc[_selectedindex], drawer: Drawer( child: Column( children:[ Container( alignment: Alignment.center, width: double.infinity, height: 130, color: Theme.of(context).accentColor, padding: EdgeInsets.all(35), child: Text("Cooking !!!!", softWrap: true, style: TextStyle(fontSize: 30.0, fontWeight: FontWeight.bold,color: Colors.black),), ), SizedBox(height: 20.0,), ListTile(onTap: ()=>Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (_)=>mealsHomePage())), leading: Icon(Icons.no_meals, size: 30,), title: Text("Meals", style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),),), SizedBox(height: 5.0,), // ListTile(onTap: ()=>Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (_)=>settings(newList))),leading: Icon(Icons.settings, size: 30,), title: Text("Settings", style: TextStyle(fontSize: 20.0,fontWeight: FontWeight.bold),),), ] ) ), bottomNavigationBar: BottomNavigationBar( selectedItemColor: Colors.amberAccent, unselectedItemColor: Colors.white, // type: BottomNavigationBarType.shifting, currentIndex: _selectedindex, onTap: _selectindex, backgroundColor: Theme.of(context).primaryColor, items: [ BottomNavigationBarItem( backgroundColor: Colors.pink, icon: Icon(Icons.access_alarm), label: 'Categories', ), BottomNavigationBarItem( backgroundColor: Colors.pink, icon: Icon(Icons.favorite), label: 'Favourites', ) ])); } }
0
mirrored_repositories/mealsApp
mirrored_repositories/mealsApp/lib/dummy_data.dart
import 'package:flutter/material.dart'; import 'category.dart'; import 'meals.dart'; const DUMMY_CATEGORIES = const [ Category( id: 'c1', title: 'Italian', color: Colors.purple, ), Category( id: 'c2', title: 'Quick & Easy', color: Colors.red, ), Category( id: 'c3', title: 'Hamburgers', color: Colors.orange, ), Category( id: 'c4', title: 'German', color: Colors.amber, ), Category( id: 'c5', title: 'Light & Lovely', color: Colors.blue, ), Category( id: 'c6', title: 'Exotic', color: Colors.green, ), Category( id: 'c7', title: 'Breakfast', color: Colors.lightBlue, ), Category( id: 'c8', title: 'Asian', color: Colors.lightGreen, ), Category( id: 'c9', title: 'French', color: Colors.pink, ), Category( id: 'c10', title: 'Summer', color: Colors.teal, ), ]; List<Meal>dunny_names = [ Meal( id: 'm1', categories: [ 'c1', 'c2', ], title: 'Spaghetti with Tomato Sauce', affordability: Affordability.Affordable, complexity: Complexity.Simple, imageUrl: 'https://upload.wikimedia.org/wikipedia/commons/thumb/2/20/Spaghetti_Bolognese_mit_Parmesan_oder_Grana_Padano.jpg/800px-Spaghetti_Bolognese_mit_Parmesan_oder_Grana_Padano.jpg', duration: 20, ingredients: [ '4 Tomatoes', '1 Tablespoon of Olive Oil', '1 Onion', '250g Spaghetti', 'Spices', 'Cheese (optional)' ], steps: [ 'Cut the tomatoes and the onion into small pieces.', 'Boil some water - add salt to it once it boils.', 'Put the spaghetti into the boiling water - they should be done in about 10 to 12 minutes.', 'In the meantime, heaten up some olive oil and add the cut onion.', 'After 2 minutes, add the tomato pieces, salt, pepper and your other spices.', 'The sauce will be done once the spaghetti are.', 'Feel free to add some cheese on top of the finished dish.' ], isGlutenFree: false, isVegan: true, isVegetarian: true, isLactoseFree: true, ), Meal( id: 'm2', categories: [ 'c2', ], title: 'Toast Hawaii', affordability: Affordability.Affordable, complexity: Complexity.Simple, imageUrl: 'https://cdn.pixabay.com/photo/2018/07/11/21/51/toast-3532016_1280.jpg', duration: 10, ingredients: [ '1 Slice White Bread', '1 Slice Ham', '1 Slice Pineapple', '1-2 Slices of Cheese', 'Butter' ], steps: [ 'Butter one side of the white bread', 'Layer ham, the pineapple and cheese on the white bread', 'Bake the toast for round about 10 minutes in the oven at 200°C' ], isGlutenFree: false, isVegan: false, isVegetarian: false, isLactoseFree: false, ), Meal( id: 'm3', categories: [ 'c2', 'c3', ], title: 'Classic Hamburger', affordability: Affordability.Pricey, complexity: Complexity.Simple, imageUrl: 'https://cdn.pixabay.com/photo/2014/10/23/18/05/burger-500054_1280.jpg', duration: 45, ingredients: [ '300g Cattle Hack', '1 Tomato', '1 Cucumber', '1 Onion', 'Ketchup', '2 Burger Buns' ], steps: [ 'Form 2 patties', 'Fry the patties for c. 4 minutes on each side', 'Quickly fry the buns for c. 1 minute on each side', 'Bruch buns with ketchup', 'Serve burger with tomato, cucumber and onion' ], isGlutenFree: false, isVegan: false, isVegetarian: false, isLactoseFree: true, ), Meal( id: 'm4', categories: [ 'c4', ], title: 'Wiener Schnitzel', affordability: Affordability.Luxurious, complexity: Complexity.Challenging, imageUrl: 'https://cdn.pixabay.com/photo/2018/03/31/19/29/schnitzel-3279045_1280.jpg', duration: 60, ingredients: [ '8 Veal Cutlets', '4 Eggs', '200g Bread Crumbs', '100g Flour', '300ml Butter', '100g Vegetable Oil', 'Salt', 'Lemon Slices' ], steps: [ 'Tenderize the veal to about 2–4mm, and salt on both sides.', 'On a flat plate, stir the eggs briefly with a fork.', 'Lightly coat the cutlets in flour then dip into the egg, and finally, coat in breadcrumbs.', 'Heat the butter and oil in a large pan (allow the fat to get very hot) and fry the schnitzels until golden brown on both sides.', 'Make sure to toss the pan regularly so that the schnitzels are surrounded by oil and the crumbing becomes ‘fluffy’.', 'Remove, and drain on kitchen paper. Fry the parsley in the remaining oil and drain.', 'Place the schnitzels on awarmed plate and serve garnishedwith parsley and slices of lemon.' ], isGlutenFree: false, isVegan: false, isVegetarian: false, isLactoseFree: false, ), Meal( id: 'm5', categories: [ 'c2' 'c5', 'c10', ], title: 'Salad with Smoked Salmon', affordability: Affordability.Luxurious, complexity: Complexity.Simple, imageUrl: 'https://cdn.pixabay.com/photo/2016/10/25/13/29/smoked-salmon-salad-1768890_1280.jpg', duration: 15, ingredients: [ 'Arugula', 'Lamb\'s Lettuce', 'Parsley', 'Fennel', '200g Smoked Salmon', 'Mustard', 'Balsamic Vinegar', 'Olive Oil', 'Salt and Pepper' ], steps: [ 'Wash and cut salad and herbs', 'Dice the salmon', 'Process mustard, vinegar and olive oil into a dessing', 'Prepare the salad', 'Add salmon cubes and dressing' ], isGlutenFree: true, isVegan: false, isVegetarian: true, isLactoseFree: true, ), Meal( id: 'm6', categories: [ 'c6', 'c10', ], title: 'Delicious Orange Mousse', affordability: Affordability.Affordable, complexity: Complexity.Hard, imageUrl: 'https://cdn.pixabay.com/photo/2017/05/01/05/18/pastry-2274750_1280.jpg', duration: 240, ingredients: [ '4 Sheets of Gelatine', '150ml Orange Juice', '80g Sugar', '300g Yoghurt', '200g Cream', 'Orange Peel', ], steps: [ 'Dissolve gelatine in pot', 'Add orange juice and sugar', 'Take pot off the stove', 'Add 2 tablespoons of yoghurt', 'Stir gelatin under remaining yoghurt', 'Cool everything down in the refrigerator', 'Whip the cream and lift it under die orange mass', 'Cool down again for at least 4 hours', 'Serve with orange peel', ], isGlutenFree: true, isVegan: false, isVegetarian: true, isLactoseFree: false, ), Meal( id: 'm7', categories: [ 'c7', ], title: 'Pancakes', affordability: Affordability.Affordable, complexity: Complexity.Simple, imageUrl: 'https://cdn.pixabay.com/photo/2018/07/10/21/23/pancake-3529653_1280.jpg', duration: 20, ingredients: [ '1 1/2 Cups all-purpose Flour', '3 1/2 Teaspoons Baking Powder', '1 Teaspoon Salt', '1 Tablespoon White Sugar', '1 1/4 cups Milk', '1 Egg', '3 Tablespoons Butter, melted', ], steps: [ 'In a large bowl, sift together the flour, baking powder, salt and sugar.', 'Make a well in the center and pour in the milk, egg and melted butter; mix until smooth.', 'Heat a lightly oiled griddle or frying pan over medium high heat.', 'Pour or scoop the batter onto the griddle, using approximately 1/4 cup for each pancake. Brown on both sides and serve hot.' ], isGlutenFree: true, isVegan: false, isVegetarian: true, isLactoseFree: false, ), Meal( id: 'm8', categories: [ 'c8', ], title: 'Creamy Indian Chicken Curry', affordability: Affordability.Pricey, complexity: Complexity.Challenging, imageUrl: 'https://cdn.pixabay.com/photo/2018/06/18/16/05/indian-food-3482749_1280.jpg', duration: 35, ingredients: [ '4 Chicken Breasts', '1 Onion', '2 Cloves of Garlic', '1 Piece of Ginger', '4 Tablespoons Almonds', '1 Teaspoon Cayenne Pepper', '500ml Coconut Milk', ], steps: [ 'Slice and fry the chicken breast', 'Process onion, garlic and ginger into paste and sauté everything', 'Add spices and stir fry', 'Add chicken breast + 250ml of water and cook everything for 10 minutes', 'Add coconut milk', 'Serve with rice' ], isGlutenFree: true, isVegan: false, isVegetarian: false, isLactoseFree: true, ), Meal( id: 'm9', categories: [ 'c9', ], title: 'Chocolate Souffle', affordability: Affordability.Affordable, complexity: Complexity.Hard, imageUrl: 'https://cdn.pixabay.com/photo/2014/08/07/21/07/souffle-412785_1280.jpg', duration: 45, ingredients: [ '1 Teaspoon melted Butter', '2 Tablespoons white Sugar', '2 Ounces 70% dark Chocolate, broken into pieces', '1 Tablespoon Butter', '1 Tablespoon all-purpose Flour', '4 1/3 tablespoons cold Milk', '1 Pinch Salt', '1 Pinch Cayenne Pepper', '1 Large Egg Yolk', '2 Large Egg Whites', '1 Pinch Cream of Tartar', '1 Tablespoon white Sugar', ], steps: [ 'Preheat oven to 190°C. Line a rimmed baking sheet with parchment paper.', 'Brush bottom and sides of 2 ramekins lightly with 1 teaspoon melted butter; cover bottom and sides right up to the rim.', 'Add 1 tablespoon white sugar to ramekins. Rotate ramekins until sugar coats all surfaces.', 'Place chocolate pieces in a metal mixing bowl.', 'Place bowl over a pan of about 3 cups hot water over low heat.', 'Melt 1 tablespoon butter in a skillet over medium heat. Sprinkle in flour. Whisk until flour is incorporated into butter and mixture thickens.', 'Whisk in cold milk until mixture becomes smooth and thickens. Transfer mixture to bowl with melted chocolate.', 'Add salt and cayenne pepper. Mix together thoroughly. Add egg yolk and mix to combine.', 'Leave bowl above the hot (not simmering) water to keep chocolate warm while you whip the egg whites.', 'Place 2 egg whites in a mixing bowl; add cream of tartar. Whisk until mixture begins to thicken and a drizzle from the whisk stays on the surface about 1 second before disappearing into the mix.', 'Add 1/3 of sugar and whisk in. Whisk in a bit more sugar about 15 seconds.', 'whisk in the rest of the sugar. Continue whisking until mixture is about as thick as shaving cream and holds soft peaks, 3 to 5 minutes.', 'Transfer a little less than half of egg whites to chocolate.', 'Mix until egg whites are thoroughly incorporated into the chocolate.', 'Add the rest of the egg whites; gently fold into the chocolate with a spatula, lifting from the bottom and folding over.', 'Stop mixing after the egg white disappears. Divide mixture between 2 prepared ramekins. Place ramekins on prepared baking sheet.', 'Bake in preheated oven until scuffles are puffed and have risen above the top of the rims, 12 to 15 minutes.', ], isGlutenFree: true, isVegan: false, isVegetarian: true, isLactoseFree: false, ), Meal( id: 'm10', categories: [ 'c2', 'c5', 'c10', ], title: 'Asparagus Salad with Cherry Tomatoes', affordability: Affordability.Luxurious, complexity: Complexity.Simple, imageUrl: 'https://cdn.pixabay.com/photo/2018/04/09/18/26/asparagus-3304997_1280.jpg', duration: 30, ingredients: [ 'White and Green Asparagus', '30g Pine Nuts', '300g Cherry Tomatoes', 'Salad', 'Salt, Pepper and Olive Oil' ], steps: [ 'Wash, peel and cut the asparagus', 'Cook in salted water', 'Salt and pepper the asparagus', 'Roast the pine nuts', 'Halve the tomatoes', 'Mix with asparagus, salad and dressing', 'Serve with Baguette' ], isGlutenFree: true, isVegan: true, isVegetarian: true, isLactoseFree: true, ), ];
0
mirrored_repositories/mealsApp
mirrored_repositories/mealsApp/lib/meals_screen.dart
import 'package:flutter/material.dart'; import 'package:meals_app/mealItem.dart'; import 'dummy_data.dart'; import 'meals.dart'; class mealsScreen extends StatefulWidget { final String id; final String title; final Iterable<Meal>lsitss; mealsScreen(this.id, this.title, this.lsitss); @override _mealsScreenState createState() => _mealsScreenState(); } class _mealsScreenState extends State<mealsScreen> { @override Widget build(BuildContext context) { final myList = widget.lsitss.where((meal) { return meal.categories.contains(widget.id); }).toList(); return Scaffold( body: Center( child: ListView.builder( itemBuilder: (context, index) { return mealItem( id: myList[index].id, myImage: myList[index].imageUrl, title: myList[index].title, duration: myList[index].duration, affordability: myList[index].affordability, complexity: myList[index].complexity, ); }, itemCount: myList.length, )), ); } }
0
mirrored_repositories/mealsApp
mirrored_repositories/mealsApp/lib/mealdetails.dart
import 'package:flutter/cupertino.dart'; import 'package:meals_app/dummy_data.dart'; import 'package:flutter/material.dart'; import 'meals.dart'; class mealDetails extends StatelessWidget { final String id; mealDetails(this.id); @override Widget build(BuildContext context) { final aBc = dunny_names.firstWhere((element) => element.id == id); // print(aBc); return Scaffold( appBar: AppBar( backgroundColor: Theme.of(context).primaryColor, title: Text(aBc.title), ), body: SingleChildScrollView( child: Column( children: [ Image.network( aBc.imageUrl, height: 300.0, width: double.infinity, fit: BoxFit.cover, ), Container( margin: EdgeInsets.only(top: 20.0), child: Text( "Ingredients", style: TextStyle(fontSize: 25.0, fontWeight: FontWeight.bold), ), ), Container( width: 200, height: 100, margin: EdgeInsets.symmetric(vertical: 10.0), padding: EdgeInsets.all(10.0), decoration: BoxDecoration( border: Border.all(width: 1.5, color: Colors.black), borderRadius: BorderRadius.circular(5.0)), child: ListView.builder( itemBuilder: (context, index) { return Container( margin: EdgeInsets.symmetric(vertical: 2.0), child: Text(aBc.ingredients[index]), color: Theme.of(context).accentColor.withOpacity(0.7)); }, itemCount: aBc.ingredients.length, ), ), Container( margin: EdgeInsets.only(top: 20.0), child: Text( "Steps", style: TextStyle(fontSize: 25.0, fontWeight: FontWeight.bold), ), ), Container( width: 300, height: 400, margin: EdgeInsets.symmetric(vertical: 10.0), padding: EdgeInsets.all(10.0), decoration: BoxDecoration( border: Border.all(width: 1.5, color: Colors.black), borderRadius: BorderRadius.circular(5.0)), child: ListView.builder( itemBuilder: (context, index) { return ListTile( leading: CircleAvatar( backgroundColor: Colors.amberAccent[300], child: Text("# ${index + 1}"), ), title: Column(children: [ Container( margin: EdgeInsets.symmetric(vertical: 2.0), child: Text(aBc.steps[index]), ), Divider( thickness: 2.0, color: Colors.black.withOpacity(0.2), ) ])); }, itemCount: aBc.steps.length, ), ) ], ), ), floatingActionButton: FloatingActionButton( onPressed: () { Navigator.of(context).pop(id); }, child: Icon(Icons.delete), ), ); } }
0
mirrored_repositories/mealsApp
mirrored_repositories/mealsApp/lib/settings.dart
import 'package:flutter/material.dart'; import 'package:meals_app/tabs_screen.dart'; class settings extends StatefulWidget { Function newlist; settings(this.newlist); @override _settingsState createState() => _settingsState(); } class _settingsState extends State<settings> { Map<String,bool> mapp = { '_isVegan' : false , '_lactoseFree' : false, '_glutenFree' : false, '_isVegetarian' : false }; bool _isVegan = false; bool _lactosefree = false; bool _glutenFree = false; bool _isVegetarian = false; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Meals App'), backgroundColor: Theme.of(context).primaryColor, actions: [ IconButton(onPressed: (){ mapp['_isVegan'] = _isVegan; mapp['_lactoseFree'] = _lactosefree; mapp['_glutenFree'] = _glutenFree; mapp['_isVegetarian'] = _isVegetarian; print(mapp); widget.newlist(mapp); }, icon: Icon(Icons.save)) ], ), drawer: Drawer( child: Column( children:[ Container( alignment: Alignment.center, width: double.infinity, height: 130, color: Theme.of(context).accentColor, padding: EdgeInsets.all(35), child: Text("Cooking !!!!", softWrap: true, style: TextStyle(fontSize: 30.0, fontWeight: FontWeight.bold,color: Colors.black),), ), SizedBox(height: 20.0,), ListTile(onTap: ()=>Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (_)=>tabsScreen())), leading: Icon(Icons.no_meals, size: 30,), title: Text("Meals", style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold),),), SizedBox(height: 5.0,), // ListTile(onTap: ()=>Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (_)=>settings())),leading: Icon(Icons.settings, size: 30,), title: Text("Settings", style: TextStyle(fontSize: 20.0,fontWeight: FontWeight.bold),),), ] ) ), body: Column( children: [ Center(child: Container( margin: EdgeInsets.all(15.0), child: Text("Adjust Your Settings", style: TextStyle(fontWeight: FontWeight.bold,fontSize: 25.0),))) , Expanded(child: Column( children: [ SwitchListTile(subtitle:Text("Only include Gluten-Free meals") , title: Text("Gluten-free",style: TextStyle(fontSize: 20.0),), value: _glutenFree, onChanged: (value){ setState(() { _glutenFree = value; }); }), SizedBox(height: 10.0,), SwitchListTile(subtitle:Text("Only include Lactose-Free meals") , title: Text("Lactose-Free",style: TextStyle(fontSize: 20.0),), value: _lactosefree, onChanged: (value){ setState(() { _lactosefree = value; }); }), SizedBox(height: 10.0,), SwitchListTile(subtitle:Text("Only include Vegetarian meals") , title: Text("Vegetarian",style: TextStyle(fontSize: 20.0),), value: _isVegetarian, onChanged: (value){ setState(() { _isVegetarian = value; }); }), SizedBox(height: 10.0,), SwitchListTile(subtitle:Text("Only include Vegan meals") , title: Text("Vegan",style: TextStyle(fontSize: 20.0),), value: _isVegan, onChanged: (value){ setState(() { _isVegan = value; }); }), SizedBox(height: 10.0,), ], )) ], ), ); } }
0
mirrored_repositories/mealsApp
mirrored_repositories/mealsApp/lib/main.dart
import 'package:flutter/material.dart'; import 'mealsHomepage.dart'; import 'tabs_screen.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( // This is the theme of your application. // // Try running your application with "flutter run". You'll see the // application has a blue toolbar. Then, without quitting the app, try // changing the primarySwatch below to Colors.green and then invoke // "hot reload" (press "r" in the console where you ran "flutter run", // or simply save your changes to "hot reload" in a Flutter IDE). // Notice that the counter didn't reset back to zero; the application // is not restarted. primarySwatch: Colors.pink, accentColor: Colors.amber), home: tabsScreen()); } }
0
mirrored_repositories/mealsApp
mirrored_repositories/mealsApp/lib/meals.dart
import 'package:flutter/material.dart'; import 'package:flutter/cupertino.dart'; enum Complexity { Simple, Challenging, Hard } enum Affordability { Affordable, Pricey, Luxurious } class Meal { final String id; List<String> categories; final String title; final String imageUrl; final List<String> ingredients; final List<String> steps; final int duration; final Complexity complexity; final Affordability affordability; final bool isGlutenFree; final bool isLactoseFree; final bool isVegan; final bool isVegetarian; Meal( {this.id = '1', this.categories = const ['12w'], this.title = '1', this.imageUrl = 'w', this.ingredients = const ['12w'], this.steps = const ['12w'], this.duration = 1, this.complexity = Complexity.Challenging, this.affordability = Affordability.Affordable, this.isGlutenFree = false, this.isLactoseFree = false, this.isVegan = false, this.isVegetarian = false}); }
0
mirrored_repositories/mealsApp
mirrored_repositories/mealsApp/lib/favouritesScreen.dart
import 'package:flutter/material.dart'; class favouritesScreen extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( body: Center(child: Text('Mihir'),), ); } }
0
mirrored_repositories/mealsApp
mirrored_repositories/mealsApp/lib/mealItem.dart
import 'package:flutter/material.dart'; import 'package:meals_app/mealdetails.dart'; import 'package:meals_app/meals.dart'; class mealItem extends StatelessWidget { final String id; final String myImage; final String title; final int duration; final affordability; final complexity; mealItem( {this.id = '1', this.myImage = '1', this.title = '3', this.duration = 1, this.affordability = Affordability.Affordable, this.complexity = Complexity.Hard}); void onClick() {} String get affor { switch (affordability) { case Affordability.Affordable: return 'Affordable'; case Affordability.Luxurious: return 'Luxurious'; case Affordability.Pricey: return 'Pricey'; default: return 'Unknown'; } } String get comp { switch (complexity) { case Complexity.Challenging: return 'Challenging'; case Complexity.Hard: return 'Hard'; case Complexity.Simple: return 'Simple'; default: return 'Unknown'; } } void goonit(BuildContext context) {} @override Widget build(BuildContext context) { return InkWell( onTap: onClick, child: InkWell( onTap: () => Navigator.of(context) .push(MaterialPageRoute(builder: (_) => mealDetails(id))).then((value){ print("$value"); }), child: Card( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(15), ), margin: EdgeInsets.all(15.0), elevation: 4.0, child: Column( children: [ Stack( children: [ ClipRRect( child: Image.network(myImage, height: 250.0, width: double.infinity, fit: BoxFit.fill), borderRadius: BorderRadius.only( topLeft: Radius.circular(15.0), topRight: Radius.circular(15.0))), Positioned( bottom: 20.0, right: 10.0, child: Container( padding: EdgeInsets.all(20.0), width: 250.0, color: Colors.black54, child: Text( title, style: TextStyle(color: Colors.white, fontSize: 26), softWrap: true, overflow: TextOverflow.fade, ), ), ) ], ), Padding( padding: EdgeInsets.all(15.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Row( children: [ Icon(Icons.schedule), SizedBox( width: 5.0, ), Text('${duration.toString()}' + 'min'), ], ), Row( children: [ Icon(Icons.directions_boat_filled_sharp), SizedBox( width: 5.0, ), Text('${comp}'), ], ), Row( children: [ Icon(Icons.monetization_on), SizedBox( width: 5.0, ), Text( '${affor}', ), ], ), ], ), ) ], ), ), ), ); } }
0
mirrored_repositories/mealsApp
mirrored_repositories/mealsApp/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:meals_app/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/famxon
mirrored_repositories/famxon/lib/main.dart
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'src/app.dart'; import 'src/features/products/services/products_controller.dart'; import 'src/settings/settings_controller.dart'; import 'src/settings/settings_service.dart'; void main() async { final settingsController = SettingsController(SettingsService()); await settingsController.loadSettings(); runApp( MultiProvider( providers: [ ChangeNotifierProvider(create: (_) => ProductsController(),), ], child: MyApp( settingsController: settingsController ), )); }
0
mirrored_repositories/famxon/lib
mirrored_repositories/famxon/lib/src/app.dart
import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'features/products/views/products_list.dart'; import 'settings/settings_controller.dart'; import 'settings/settings_view.dart'; class MyApp extends StatelessWidget { const MyApp({ super.key, required this.settingsController, }); final SettingsController settingsController; @override Widget build(BuildContext context) { return ListenableBuilder( listenable: settingsController, builder: (BuildContext context, Widget? child) { return MaterialApp( restorationScopeId: 'app', localizationsDelegates: const [ AppLocalizations.delegate, GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, GlobalCupertinoLocalizations.delegate, ], supportedLocales: const [ Locale('en', ''), ], onGenerateTitle: (BuildContext context) => AppLocalizations.of(context)!.appTitle, theme: ThemeData( useMaterial3: true, colorScheme: ColorScheme.fromSeed( seedColor: Colors.indigo, ), ), darkTheme: ThemeData.dark( useMaterial3: true, ), themeMode: settingsController.themeMode, onGenerateRoute: (RouteSettings routeSettings) { return MaterialPageRoute<void>( settings: routeSettings, builder: (BuildContext context) { switch (routeSettings.name) { case SettingsView.routeName: return SettingsView(controller: settingsController); // case ProductDetails.routeName: // return ProductDetails( // model: routeSettings.arguments as ProductModel, // ); case ProductList.routeName: default: return const ProductList(); } }, ); }, ); }, ); } }
0
mirrored_repositories/famxon/lib/src/features/products
mirrored_repositories/famxon/lib/src/features/products/views/products_list.dart
import 'package:e_commerce/src/features/products/services/products_controller.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import '../../../settings/settings_view.dart'; import '../models/product_model.dart'; import '../services/products.dart'; import '../widgets/product_grid.dart'; import '../widgets/product_tile.dart'; class ProductList extends StatefulWidget { const ProductList({ super.key, }); static const routeName = '/'; @override State<ProductList> createState() => _ProductListState(); } class _ProductListState extends State<ProductList> { @override void initState() { super.initState(); WidgetsBinding.instance.addPostFrameCallback((timeStamp) { Provider.of<ProductsController>(context, listen: false).load(); }); } @override Widget build(BuildContext context) { ProductsController productsController = context.watch<ProductsController>(); return Scaffold( appBar: AppBar( backgroundColor: Theme.of(context).colorScheme.inversePrimary, title: const Text('FamXon Shopping'), actions: [ IconButton( icon: const Icon(Icons.settings), onPressed: () { Navigator.restorablePushNamed(context, SettingsView.routeName); }, ), ], ), body: Padding( padding: const EdgeInsets.symmetric(horizontal: 12), child: Builder(builder: (context) { if (productsController.isMainLoading) { return Center( child: CircularProgressIndicator( color: Theme.of(context).colorScheme.surface)); } if (productsController.hasError) { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( productsController.errorMessage, style: TextStyle( color: Theme.of(context).colorScheme.error, fontSize: 22, fontWeight: FontWeight.bold, ), ), const SizedBox(height: 50), ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: Theme.of(context).colorScheme.primary, foregroundColor: Theme.of(context).colorScheme.surface, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8), ), ), onPressed: () { setState(() {}); }, child: const Text("retry"), ), ], )); } List<ProductModel>? items = productsController.products; if ((items?.length ?? 0) == 0) { return const Center( child: Text( "No Products found", style: TextStyle(fontWeight: FontWeight.bold, fontSize: 42), )); } return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const SizedBox(height: 20), const Text( "Trending Products", style: TextStyle( fontWeight: FontWeight.w500, fontSize: 24, ), ), SizedBox( height: 150, child: ListView.builder( scrollDirection: Axis.horizontal, restorationId: 'sampleItemListView', itemCount: items?.length ?? 0, itemBuilder: (BuildContext context, int index) { final item = items![index]; return ProductGrid(item: item); }, ), ), SizedBox( height: 50, child: ListView.builder( itemCount: productsController.categories?.length ?? 0, scrollDirection: Axis.horizontal, itemBuilder: (context, index) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 4), child: ChoiceChip( onSelected: (val) { productsController.selectedCategory = productsController.categories!.elementAt(index); }, label: Text( productsController.categories!.elementAt(index)), selected: productsController.selectedCategory == productsController.categories!.elementAt(index), ), ); }, ), ), Expanded( child: FutureBuilder( future: productsByCategory(productsController.selectedCategory!), builder: (context, snapshot) { switch (snapshot.connectionState) { case ConnectionState.waiting: return Center( child: CircularProgressIndicator( color: Theme.of(context).colorScheme.inverseSurface, )); case ConnectionState.none: return const Center( child: Text("Error"), ); default: } if (snapshot.data?.hasError ?? true) { return Center( child: Column( children: [ Text( snapshot.data?.message ?? "Something went wrong", style: TextStyle( color: Theme.of(context).colorScheme.error, fontSize: 22, fontWeight: FontWeight.bold, ), ), const SizedBox(height: 50), ElevatedButton( style: ElevatedButton.styleFrom( backgroundColor: Theme.of(context).colorScheme.primary, foregroundColor: Theme.of(context).colorScheme.surface, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(8), ), ), onPressed: () { productsController.load(); }, child: const Text("retry"), ), ], ), ); } List<ProductModel>? items = snapshot.data?.data as List<ProductModel>?; return ListView.builder( itemCount: items?.length ?? 0, itemBuilder: (context, index) { ProductModel item = items!.elementAt(index); return ProductTile(item: item); }, ); }, ), ) ], ); }), ), ); } }
0
mirrored_repositories/famxon/lib/src/features/products
mirrored_repositories/famxon/lib/src/features/products/widgets/product_grid.dart
import 'package:flutter/material.dart'; import '../models/product_model.dart'; import 'buy_column.dart'; class ProductGrid extends StatelessWidget { const ProductGrid({ super.key, required this.item, }); final ProductModel item; @override Widget build(BuildContext context) { return GestureDetector( onTap: () { // Navigator.pushNamed(context, ProductDetails.routeName, arguments: item); buyDialog(context, item); }, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 0, vertical: 5), child: SizedBox( width: 250, child: Padding( padding: const EdgeInsets.all(8.0), child: GridTile( header: Align( alignment: Alignment.topRight, child: Container( decoration: const BoxDecoration( color: Colors.black, borderRadius: BorderRadius.only(topRight: Radius.circular(12)), ), child: Text( " \$${item.price.toStringAsFixed(2)} ", style: const TextStyle( fontWeight: FontWeight.w900, fontSize: 18, color: Colors.white, ), ), ), ), footer: Container( padding: const EdgeInsets.all(10), decoration: BoxDecoration( color: Colors.grey.shade800.withOpacity(.8), borderRadius: const BorderRadius.vertical(bottom: Radius.circular(12)), ), child: Text( item.title, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle( color: Colors.white, fontWeight: FontWeight.w600, fontSize: 20, ), ), ), child: SizedBox( width: 120, child: ClipRRect( borderRadius: BorderRadius.circular(12), child: Image.network( item.thumbnail, fit: BoxFit.cover, ), ), ), // onTap: () { // Navigator.restorablePushNamed( // context, // ProductDetails.routeName, // ); // }, ), ), ), ), ); } } Future<dynamic> buyDialog(BuildContext context, ProductModel item) { return showModalBottomSheet( context: context, builder: (_) => BuyColumn(model: item)); }
0
mirrored_repositories/famxon/lib/src/features/products
mirrored_repositories/famxon/lib/src/features/products/widgets/product_tile.dart
import 'package:e_commerce/src/features/products/widgets/product_grid.dart'; import 'package:flutter/material.dart'; import '../models/product_model.dart'; class ProductTile extends StatelessWidget { const ProductTile({ super.key, required this.item, }); final ProductModel item; @override Widget build(BuildContext context) { return ListTile( onTap: () { // Navigator.pushNamed(context, ProductDetails.routeName, arguments: item); buyDialog(context, item); }, leading: AspectRatio( // width: 80, aspectRatio: 16 / 9, child: ClipRRect( borderRadius: BorderRadius.circular(8), child: Image.network( item.thumbnail, fit: BoxFit.cover, ), ), ), title: Text(item.title), subtitle: Text("\$${item.price} || ${item.brand}"), trailing: Text("⭐ ${item.rating}"), ); } }
0
mirrored_repositories/famxon/lib/src/features/products
mirrored_repositories/famxon/lib/src/features/products/widgets/buy_column.dart
import 'package:flutter/material.dart'; import '../models/product_model.dart'; class BuyColumn extends StatelessWidget { const BuyColumn({ super.key, required this.model, }); final ProductModel model; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 20), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const SizedBox(height: 20), Align( alignment: Alignment.center, child: Container( width: 50, height: 5, decoration: BoxDecoration( color: Colors.grey, borderRadius: BorderRadius.circular(12)), ), ), const SizedBox(height: 20), SizedBox( height: 200, child: ListView.builder( // controller: _controller, scrollDirection: Axis.horizontal, itemCount: model.images.length, itemBuilder: (context, index) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 10), child: Image.network( model.images.elementAt(index), fit: BoxFit.cover, ), ); }, ), ), // Text(model.category), const SizedBox(height: 25), SizedBox( height: 80, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.start, children: [ Flexible( child: Text( model.title, style: Theme.of(context).textTheme.headlineSmall, ), ), Column( crossAxisAlignment: CrossAxisAlignment.end, children: [ const Text("Rating"), Text( "🌟 ${model.rating}", style: const TextStyle( fontSize: 20, fontWeight: FontWeight.bold, ), ), ], ), ], ), ), const Spacer(), FractionallySizedBox( widthFactor: 1, child: Container( height: 85, decoration: const BoxDecoration( // color: Theme.of(context).primaryColor, ), child: SafeArea( child: ElevatedButton( style: ElevatedButton.styleFrom( foregroundColor: Colors.white, backgroundColor: Colors.deepPurple, ), child: Text.rich( TextSpan( text: "Buy now for ", children: [ TextSpan( text: "\$${(model.price).toStringAsFixed(2)}", style: const TextStyle( fontWeight: FontWeight.w900, )) ], ), ), onPressed: () { // }, ), ), ), ), const SizedBox(height: 10), ], ), ); } }
0
mirrored_repositories/famxon/lib/src/features/products
mirrored_repositories/famxon/lib/src/features/products/models/product_model.dart
import 'dart:convert'; class ProductModel { final int id; String title; double price; double discountPercentage; double rating; int stock; String brand; String category; String thumbnail; List<String> images; ProductModel({ required this.id, required this.title, required this.price, required this.discountPercentage, required this.rating, required this.stock, required this.brand, required this.category, required this.thumbnail, required this.images, }); Map<String, dynamic> toMap() { return <String, dynamic>{ 'id': id, 'title': title, 'price': price, 'discountPercentage': discountPercentage, 'rating': rating, 'stock': stock, 'brand': brand, 'category': category, 'thumbnail': thumbnail, 'images': images, }; } factory ProductModel.fromMap(Map<String, dynamic> map) { return ProductModel( id: map['id'] as int, title: map['title'] as String, price: double.parse("${map['price']}"), discountPercentage: double.parse("${map['discountPercentage']}"), rating: double.parse("${map['rating']}"), stock: map['stock'] as int, brand: map['brand'] as String, category: map['category'] as String, thumbnail: map['thumbnail'] as String, images: List<String>.from((map['images'] as List<dynamic>)), ); } String toJson() => json.encode(toMap()); factory ProductModel.fromJson(String source) => ProductModel.fromMap(json.decode(source) as Map<String, dynamic>); }
0
mirrored_repositories/famxon/lib/src/features/products
mirrored_repositories/famxon/lib/src/features/products/services/products_controller.dart
import 'package:flutter/material.dart'; import '../models/product_model.dart'; import 'products.dart'; class ProductsController extends ChangeNotifier { List<ProductModel>? _products; List<String>? _categories; bool hasError = false; bool isMainLoading = true; String errorMessage = ''; int totalProducts = 0; String? _selectedCategory; load() async { totalProducts = 0; isMainLoading = true; hasError = false; notifyListeners(); fetchProducts().then((r) { if (r.hasError) { hasError = true; errorMessage = r.message; } else { _products = r.data as List<ProductModel>; totalProducts += _products?.length ?? 0; } isMainLoading = false; notifyListeners(); }); fetchCategories().then((r) { if (!r.hasError) { _categories = r.data as List<String>; _selectedCategory = _categories?.first; } notifyListeners(); }); } List<ProductModel>? get products => _products; List<String>? get categories => _categories; String? get selectedCategory => _selectedCategory; set selectedCategory(val) { _selectedCategory = val; notifyListeners(); } }
0
mirrored_repositories/famxon/lib/src/features/products
mirrored_repositories/famxon/lib/src/features/products/services/products.dart
import 'dart:convert'; import 'dart:developer'; import 'dart:io'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import '../../../common/models/app_response.dart'; import '../../../meta/meta_data.dart'; import '../models/product_model.dart'; Future<AppResponse> fetchProducts() async { try { log('message'); http.Response r = await http.get(Uri.parse('$baseUrl/products')); log('fetched'); switch (r.statusCode) { case 404: return const AppResponse( hasError: true, message: 'Invalid url : Not found!'); case 200: break; default: return const AppResponse(hasError: true, message: 'Unexpected error'); } return AppResponse( hasError: false, message: 'ok', data: ((jsonDecode(r.body) as Map<String, dynamic>)['products'] as List<dynamic>) .map((e) => ProductModel.fromMap(e)) .toList(), ); } on SocketException catch (e) { debugPrint(e.toString()); return const AppResponse(hasError: true, message: 'Request Timeout'); } catch (e) { return AppResponse(hasError: true, message: e.toString()); } } Future<AppResponse> fetchCategories() async { try { log('message'); http.Response r = await http.get(Uri.parse('$baseUrl/products/categories')); log('fetched'); switch (r.statusCode) { case 404: return const AppResponse( hasError: true, message: 'Invalid url : Not found!'); case 200: break; default: return const AppResponse(hasError: true, message: 'Unexpected error'); } return AppResponse( hasError: false, message: 'ok', data: List<String>.from(jsonDecode(r.body) as List<dynamic>), ); } on SocketException catch (e) { debugPrint(e.toString()); return const AppResponse(hasError: true, message: 'Request Timeout'); } catch (e) { return AppResponse(hasError: true, message: e.toString()); } } Future<AppResponse> productsByCategory(String category) async { try { log('message'); http.Response r = await http .get(Uri.parse('$baseUrl/products/category/$category?limit=40')); log('fetched'); switch (r.statusCode) { case 404: return const AppResponse( hasError: true, message: 'Invalid url : Not found!'); case 200: break; default: return const AppResponse(hasError: true, message: 'Unexpected error'); } return AppResponse( hasError: false, message: 'ok', data: ((jsonDecode(r.body) as Map<String, dynamic>)['products'] as List<dynamic>) .map((e) => ProductModel.fromMap(e)) .toList(), ); } on SocketException catch (e) { debugPrint(e.toString()); return const AppResponse(hasError: true, message: 'Request Timeout'); } catch (e) { return AppResponse(hasError: true, message: e.toString()); } }
0
mirrored_repositories/famxon/lib/src
mirrored_repositories/famxon/lib/src/meta/meta_data.dart
String baseUrl = 'https://dummyjson.com';
0
mirrored_repositories/famxon/lib/src/common
mirrored_repositories/famxon/lib/src/common/models/app_response.dart
// ignore_for_file: public_member_api_docs, sort_constructors_first class AppResponse { final bool hasError; final String message; final Object? data; const AppResponse({ required this.hasError, required this.message, this.data, }); }
0
mirrored_repositories/famxon/lib/src
mirrored_repositories/famxon/lib/src/settings/settings_controller.dart
import 'package:flutter/material.dart'; import 'settings_service.dart'; class SettingsController with ChangeNotifier { SettingsController(this._settingsService); final SettingsService _settingsService; late ThemeMode _themeMode; ThemeMode get themeMode => _themeMode; Future<void> loadSettings() async { _themeMode = await _settingsService.themeMode(); notifyListeners(); } Future<void> updateThemeMode(ThemeMode? newThemeMode) async { if (newThemeMode == null) return; if (newThemeMode == _themeMode) return; _themeMode = newThemeMode; notifyListeners(); await _settingsService.updateThemeMode(newThemeMode); } }
0
mirrored_repositories/famxon/lib/src
mirrored_repositories/famxon/lib/src/settings/settings_view.dart
import 'package:flutter/material.dart'; import 'settings_controller.dart'; class SettingsView extends StatelessWidget { const SettingsView({super.key, required this.controller}); static const routeName = '/settings'; final SettingsController controller; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Theme.of(context).colorScheme.inversePrimary, title: const Text('Settings'), ), body: Padding( padding: const EdgeInsets.all(16), child: DropdownButton<ThemeMode>( value: controller.themeMode, borderRadius: BorderRadius.circular(20), elevation: 1, dropdownColor: Theme.of(context).colorScheme.inversePrimary.withOpacity(.9), onChanged: controller.updateThemeMode, items: const [ DropdownMenuItem( value: ThemeMode.system, child: Text('System Theme'), ), DropdownMenuItem( value: ThemeMode.light, child: Text('Light Theme'), ), DropdownMenuItem( value: ThemeMode.dark, child: Text('Dark Theme'), ) ], ), ), ); } }
0
mirrored_repositories/famxon/lib/src
mirrored_repositories/famxon/lib/src/settings/settings_service.dart
import 'package:flutter/material.dart'; class SettingsService { Future<ThemeMode> themeMode() async => ThemeMode.system; Future<void> updateThemeMode(ThemeMode theme) async {} }
0
mirrored_repositories/famxon
mirrored_repositories/famxon/test/unit_test.dart
// This is an example unit test. // // A unit test tests a single function, method, or class. To learn more about // writing unit tests, visit // https://flutter.dev/docs/cookbook/testing/unit/introduction import 'package:flutter_test/flutter_test.dart'; void main() { group('Plus Operator', () { test('should add two numbers together', () { expect(1 + 1, 2); }); }); }
0
mirrored_repositories/famxon
mirrored_repositories/famxon/test/widget_test.dart
// This is an example 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. // // Visit https://flutter.dev/docs/cookbook/testing/widget/introduction for // more information about Widget testing. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; void main() { group('MyWidget', () { testWidgets('should display a string of text', (WidgetTester tester) async { // Define a Widget const myWidget = MaterialApp( home: Scaffold( body: Text('Hello'), ), ); // Build myWidget and trigger a frame. await tester.pumpWidget(myWidget); // Verify myWidget shows some text expect(find.byType(Text), findsOneWidget); }); }); }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web_start_template
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web_start_template/lib/constants.dart
import 'package:flutter/material.dart'; const Color primary = Colors.lightBlue; const Color primaryDark = Colors.blue; const Color textPrimaryLight = Colors.black; const Color textPrimaryDark = Colors.white; const Color background = Colors.white; const String fontFamily = "Google Sans";
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web_start_template
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web_start_template/lib/main.dart
import 'package:flutter/material.dart'; import 'package:flutterweb/presentation/dev_page/dev_page.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return const MaterialApp( debugShowCheckedModeBanner: false, title: 'Flutter Web', home: DevPage(), ); } }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web_start_template/lib/presentation
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web_start_template/lib/presentation/home_page/homepage.dart
import 'package:flutter/material.dart'; import 'package:flutterweb/presentation/core/page_wrapper/page_template.dart'; class HomePage extends StatelessWidget { const HomePage({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return PageTemplate( child: Container( color: Colors.green, ), ); } }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web_start_template/lib/presentation/core
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web_start_template/lib/presentation/core/page_wrapper/page_template.dart
import 'package:flutter/material.dart'; import 'package:flutterweb/constants.dart'; class PageTemplate extends StatelessWidget { final Widget child; const PageTemplate({Key? key, required this.child}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( backgroundColor: background, appBar: AppBar( title: const Text( "flutter web", style: TextStyle(fontFamily: fontFamily), ), ), body: child, ); } }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web_start_template/lib/presentation
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web_start_template/lib/presentation/dev_page/dev_page.dart
import 'package:flutter/material.dart'; import 'package:flutterweb/presentation/core/page_wrapper/page_template.dart'; class DevPage extends StatelessWidget { const DevPage({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return PageTemplate( child: Container( color: Colors.red, ), ); } }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web_start_template
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web_start_template/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:flutterweb/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/FlutterLeichtGemacht_ZeroToMasery/flutter_web
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/lib/constants.dart
import 'package:flutter/material.dart'; const Color primary = Colors.lightBlue; const Color primaryDark = Colors.blue; const Color textPrimaryLight = Colors.black; const Color textPrimaryDark = Colors.white; const Color background = Colors.white; const String fontFamily = "Google Sans";
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/lib/main.dart
import 'package:flutter/material.dart'; import 'package:flutterweb/presentation/dev_page/dev_page.dart'; import 'package:flutterweb/presentation/eco_page/eco_page.dart'; import 'package:flutterweb/presentation/home_page/homepage.dart'; import 'package:flutterweb/presentation/not_found_page/not_found_page.dart'; import 'package:responsive_framework/responsive_framework.dart'; import 'package:routemaster/routemaster.dart'; import 'package:url_strategy/url_strategy.dart'; void main() { setPathUrlStrategy(); runApp(const MyApp()); } final routes = RouteMap( onUnknownRoute: (route) { return const MaterialPage(child: NotFondPage()); }, routes: { '/': (_) => const Redirect(HomePage.homePagePath), HomePage.homePagePath: (_) => const MaterialPage(child: HomePage()), DevPage.devPagePath: (_) => const MaterialPage(child: DevPage()), EcoPage.ecoPagePath: (_) => const MaterialPage(child: EcoPage()), }); class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp.router( routeInformationParser: const RoutemasterParser(), routerDelegate: RoutemasterDelegate(routesBuilder: (context) => routes), debugShowCheckedModeBanner: false, title: 'Flutter Web Test', builder: (context, widget) => ResponsiveWrapper.builder(widget, defaultScale: true, minWidth: 400, defaultName: MOBILE, breakpoints: const [ ResponsiveBreakpoint.autoScale(450, name: MOBILE), ResponsiveBreakpoint.resize(600, name: TABLET), ResponsiveBreakpoint.resize(1000, name: DESKTOP) ], backgroundColor: Colors.white), ); } }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/lib/presentation
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/lib/presentation/home_page/homepage.dart
import 'package:flutter/material.dart'; import 'package:flutterweb/presentation/core/page_wrapper/centered_constrained_wrapper.dart'; import 'package:flutterweb/presentation/core/page_wrapper/page_template.dart'; import 'package:flutterweb/presentation/home_page/widgets/developer_experience.dart'; import 'package:flutterweb/presentation/home_page/widgets/multi_plattform.dart'; class HomePage extends StatelessWidget { static const String homePagePath = "/home"; const HomePage({Key? key}) : super(key: key); @override Widget build(BuildContext context) { List<Widget> partblocks = [ const CenteredConstrainedWrapper(child: MultiPlattform()), const CenteredConstrainedWrapper(child: DeveloperExperience()) ]; return PageTemplate( child: ListView.builder( itemCount: partblocks.length, itemBuilder: (context, index) { return partblocks[index]; })); } }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/lib/presentation/home_page
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/lib/presentation/home_page/widgets/developer_experience.dart
import 'package:flutter/material.dart'; import 'package:flutterweb/constants.dart'; import 'package:flutterweb/presentation/core/buttons/call_to_action.dart'; import 'package:responsive_framework/responsive_framework.dart'; class DeveloperExperience extends StatelessWidget { const DeveloperExperience({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final responsive = ResponsiveWrapper.of(context); return Container( width: double.infinity, decoration: const BoxDecoration( color: Colors.white, ), child: ResponsiveRowColumn( layout: ResponsiveWrapper.of(context).isSmallerThan(DESKTOP) ? ResponsiveRowColumnType.COLUMN : ResponsiveRowColumnType.ROW, rowCrossAxisAlignment: CrossAxisAlignment.center, children: [ ResponsiveRowColumnItem( rowFlex: 1, child: Padding( padding: EdgeInsets.symmetric( horizontal: responsive.equals(TABLET) ? 120 : 50, vertical: 20, ), child: Image.asset( "assets/images/dev_exp.png", ), )), ResponsiveRowColumnItem( rowFlex: 1, child: Padding( padding: const EdgeInsets.symmetric( horizontal: 50, vertical: 20, ), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( "Developer-Experience", style: TextStyle( color: Colors.teal[400], fontFamily: fontFamily, fontSize: responsive.equals(DESKTOP) ? 20 : 18, fontWeight: FontWeight.bold), ), const SizedBox( height: 20, ), Text( "Transform your workflow", style: TextStyle( color: Colors.black, fontFamily: fontFamily, fontSize: responsive.equals(DESKTOP) ? 60 : 40, fontWeight: FontWeight.bold, height: 0.9), ), const SizedBox( height: 20, ), Text( "Take control of your codebase with automated testing, developer tooling, and everything else you need to build production-quality apps.", style: TextStyle( color: Colors.black, fontFamily: fontFamily, fontSize: responsive.equals(DESKTOP) ? 20 : 18, ), ), const SizedBox( height: 25, ), CallToAction( text: "Flutter for developers", callback: (){}, ) ], ), ), ), ], ), ); } }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/lib/presentation/home_page
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/lib/presentation/home_page/widgets/multi_plattform.dart
import 'package:flutter/material.dart'; import 'package:flutterweb/constants.dart'; import 'package:flutterweb/presentation/core/buttons/call_to_action.dart'; import 'package:responsive_framework/responsive_framework.dart'; class MultiPlattform extends StatelessWidget { const MultiPlattform({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final responsiveValue = ResponsiveWrapper.of(context); return Container( width: double.infinity, decoration: const BoxDecoration(color: background), child: ResponsiveRowColumn( columnVerticalDirection: VerticalDirection.up, rowCrossAxisAlignment: CrossAxisAlignment.center, layout: responsiveValue.isSmallerThan(DESKTOP) ? ResponsiveRowColumnType.COLUMN : ResponsiveRowColumnType.ROW, children: [ ResponsiveRowColumnItem( rowFlex: 1, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 50, vertical: 20), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ Text( "Multi-Platform", style: TextStyle( color: Colors.lightBlue, fontFamily: fontFamily, fontSize: responsiveValue.isLargerThan(TABLET) ? 20 : 18, fontWeight: FontWeight.bold), ), const SizedBox( height: 20, ), Text( "Reach users on every screen", style: TextStyle( color: textPrimaryLight, fontFamily: fontFamily, fontSize: responsiveValue.isLargerThan(TABLET) ? 60 : 40, height: 0.9, fontWeight: FontWeight.bold), ), const SizedBox( height: 20, ), Text( "Deploy to multiple devices from a single codebase: mobile, web, desktop, and embedded devices.", style: TextStyle( color: textPrimaryLight, fontFamily: fontFamily, fontSize: responsiveValue.isLargerThan(TABLET) ? 20 : 18, ), ), const SizedBox( height: 25, ), CallToAction( text: "See the target platforms", callback: () {}, ) ], ), )), ResponsiveRowColumnItem( rowFlex: 1, child: Padding( padding: EdgeInsets.symmetric( horizontal: responsiveValue.equals(TABLET) ? 120 : 50, vertical: 20), child: Image.asset("assets/images/multi_plattform.png"))), ], ), ); } }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/lib/presentation
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/lib/presentation/eco_page/eco_page.dart
import 'package:flutter/material.dart'; import 'package:flutterweb/presentation/core/page_wrapper/page_template.dart'; import 'package:flutterweb/presentation/eco_page/widgets/ecosystem.dart'; class EcoPage extends StatelessWidget { static const String ecoPagePath = "/ecosystem"; const EcoPage({Key? key}) : super(key: key); @override Widget build(BuildContext context) { List<Widget> partblocks = [ const Ecosystem(), ]; return PageTemplate( child: ListView.builder( itemCount: partblocks.length, itemBuilder: (context, index) { return partblocks[index]; }), ); } }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/lib/presentation/eco_page
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/lib/presentation/eco_page/widgets/ecosystem.dart
import 'package:flutter/material.dart'; import 'package:flutterweb/constants.dart'; import 'package:flutterweb/presentation/core/page_wrapper/centered_constrained_wrapper.dart'; import 'package:responsive_framework/responsive_framework.dart'; class Ecosystem extends StatelessWidget { const Ecosystem({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final responsive = ResponsiveWrapper.of(context); return Container( width: double.infinity, decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.bottomLeft, end: Alignment.topRight, colors: [Colors.pink[50]!, Colors.white], ), ), child: CenteredConstrainedWrapper( child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: [ ResponsiveRowColumn( columnVerticalDirection: VerticalDirection.up, columnMainAxisSize: MainAxisSize.min, layout: ResponsiveWrapper.of(context).isSmallerThan(DESKTOP) ? ResponsiveRowColumnType.COLUMN : ResponsiveRowColumnType.ROW, rowCrossAxisAlignment: CrossAxisAlignment.center, children: [ ResponsiveRowColumnItem( rowFlex: 1, child: Padding( padding: const EdgeInsets.symmetric( horizontal: 50, vertical: 20, ), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( "A strong ecosystem, powered by open source", style: TextStyle( color: Colors.black, fontFamily: fontFamily, fontSize: responsive.equals(DESKTOP) ? 75 : 40, fontWeight: FontWeight.bold, height: 0.9), textAlign: responsive.isSmallerThan(DESKTOP) ? TextAlign.center : TextAlign.start, ), ], ), ), ), ResponsiveRowColumnItem( rowFlex: 1, child: Padding( padding: EdgeInsets.symmetric( horizontal: responsive.equals(TABLET) ? 120 : 50, vertical: 20, ), child: Image.asset( "assets/images/ecosystem.png", ), )), ], ), Padding( padding: const EdgeInsets.symmetric( horizontal: 50, vertical: 20, ), child: Text( "From packages and plugins to friendly developers, find all of the resources you need to be successful with Flutter.", style: TextStyle( color: Colors.black, fontFamily: fontFamily, fontSize: responsive.equals(DESKTOP) ? 38 : 22, ), textAlign: TextAlign.center, ), ), ], ), ), ); } }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/lib/presentation/core
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/lib/presentation/core/menu/appbar.dart
import 'package:flutter/material.dart'; import 'package:flutterweb/constants.dart'; import 'package:flutterweb/presentation/core/menu/flutter_home_logo.dart'; class CustomAppBar extends StatelessWidget { const CustomAppBar({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return AppBar( iconTheme: const IconThemeData(color: textPrimaryLight), backgroundColor: background, title: Row( children: const [FlutterHomeLogo()], ), ); } }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/lib/presentation/core
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/lib/presentation/core/menu/menu_bar.dart
import 'package:flutter/material.dart'; import 'package:flutterweb/presentation/core/buttons/get_started.dart'; import 'package:flutterweb/presentation/core/menu/flutter_home_logo.dart'; import 'package:flutterweb/presentation/core/menu/menu_item.dart'; import 'package:flutterweb/presentation/dev_page/dev_page.dart'; import 'package:flutterweb/presentation/eco_page/eco_page.dart'; class CustomMenuBar extends StatelessWidget { const CustomMenuBar({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Container( height: 66, width: double.infinity, decoration: const BoxDecoration(color: Colors.white, boxShadow: [ BoxShadow(color: Colors.black, offset: Offset(0, 2), blurRadius: 4) ]), padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), child: Row( children: const [ FlutterHomeLogo(), Spacer(), MenuItem(text: "Docs", inDrawer: false, path: "",), MenuItem(text: "Showcase", inDrawer: false,path: "",), MenuItem(text: "Development", inDrawer: false,path: DevPage.devPagePath,), MenuItem(text: "Ecosystem", inDrawer: false,path: EcoPage.ecoPagePath,), GetStartedButton(inDrawer: false,) ], ), ); } }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/lib/presentation/core
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/lib/presentation/core/menu/drawer.dart
import 'package:flutter/material.dart'; import 'package:flutterweb/constants.dart'; import 'package:flutterweb/presentation/core/buttons/get_started.dart'; import 'package:flutterweb/presentation/core/menu/flutter_home_logo.dart'; import 'package:flutterweb/presentation/core/menu/menu_item.dart'; import 'package:flutterweb/presentation/dev_page/dev_page.dart'; import 'package:flutterweb/presentation/eco_page/eco_page.dart'; class CustomDrawer extends StatelessWidget { const CustomDrawer({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Container( color: primaryDark, child: Padding( padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 20), child: Stack( children: [ Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ const FlutterHomeLogo(), const Spacer(), IconButton( onPressed: () => Navigator.of(context).pop(), icon: const Icon( Icons.close, color: textPrimaryDark, size: 18, )) ], ), const SizedBox( height: 40, ), const MenuItem( path: "", text: "Docs", inDrawer: true, ), const SizedBox( height: 20, ), const MenuItem( path: "", text: "Showcase", inDrawer: true, ), const SizedBox( height: 20, ), const MenuItem( path: DevPage.devPagePath, text: "Development", inDrawer: true, ), const SizedBox( height: 20, ), const MenuItem( path: EcoPage.ecoPagePath, text: "Ecosystem", inDrawer: true, ), ], ), Column( children: const [ Spacer(), GetStartedButton(inDrawer: true,), SizedBox( height: 20, ) ], ) ], ), ), ); } }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/lib/presentation/core
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/lib/presentation/core/menu/flutter_home_logo.dart
import 'package:flutter/material.dart'; import 'package:flutterweb/presentation/home_page/homepage.dart'; import 'package:routemaster/routemaster.dart'; class FlutterHomeLogo extends StatelessWidget { const FlutterHomeLogo({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MouseRegion( cursor: SystemMouseCursors.click, child: GestureDetector( onTap: () { Routemaster.of(context).push(HomePage.homePagePath); }, child: Image.asset( "assets/images/flutter_logo_text.png", height: 37, fit: BoxFit.contain, ), ), ); } }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/lib/presentation/core
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/lib/presentation/core/menu/menu_item.dart
import 'package:flutter/material.dart'; import 'package:flutterweb/constants.dart'; import 'package:routemaster/routemaster.dart'; class MenuItem extends StatelessWidget { final String text; final String path; final bool inDrawer; const MenuItem({Key? key, required this.inDrawer, required this.text, required this.path}) : super(key: key); @override Widget build(BuildContext context) { return MouseRegion( cursor: SystemMouseCursors.click, child: GestureDetector( onTap: () { Routemaster.of(context).push(path); }, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 16), child: Text( text, style: TextStyle( fontSize: 15, fontFamily: fontFamily, color: inDrawer ? textPrimaryDark : textPrimaryLight), ), ), ), ); } }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/lib/presentation/core
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/lib/presentation/core/buttons/get_started.dart
import 'package:flutter/material.dart'; import 'package:flutterweb/constants.dart'; class GetStartedButton extends StatelessWidget { final bool inDrawer; const GetStartedButton({Key? key, required this.inDrawer}) : super(key: key); @override Widget build(BuildContext context) { return MouseRegion( cursor: SystemMouseCursors.click, child: GestureDetector( onTap: () { print("get started pressed"); }, child: Material( elevation: 6, borderRadius: BorderRadius.circular(20), child: Container( height: 40, alignment: Alignment.center, decoration: BoxDecoration( color: inDrawer ? Colors.white : primaryDark, borderRadius: BorderRadius.circular(20)), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 30), child: Text( "Get Started", style: TextStyle( fontFamily: fontFamily, fontSize: 15, color: inDrawer ? primaryDark : textPrimaryDark), ), ), ), ), ), ); } }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/lib/presentation/core
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/lib/presentation/core/buttons/call_to_action.dart
import 'package:flutter/material.dart'; import 'package:flutterweb/constants.dart'; class CallToAction extends StatelessWidget { final String text; final Function callback; const CallToAction({Key? key, required this.text, required this.callback}) : super(key: key); @override Widget build(BuildContext context) { return MouseRegion( cursor: SystemMouseCursors.click, child: GestureDetector( onTap: (){ callback(); }, child: IntrinsicWidth( child: Container( height: 40, alignment: Alignment.center, decoration: BoxDecoration( color: Colors.white, border: Border.all(color: primaryDark), borderRadius: BorderRadius.circular(20)), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 30), child: Text( text, style: const TextStyle( fontFamily: fontFamily, fontSize: 15, color: primaryDark), ), ), ), ), ), ); } }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/lib/presentation/core
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/lib/presentation/core/page_wrapper/centered_constrained_wrapper.dart
import 'package:flutter/material.dart'; import 'package:responsive_framework/responsive_framework.dart'; class CenteredConstrainedWrapper extends StatelessWidget { final Widget child; const CenteredConstrainedWrapper({Key? key, required this.child}) : super(key: key); @override Widget build(BuildContext context) { return Center( child: ResponsiveConstraints(constraintsWhen: const [ Condition.equals(name: MOBILE, value: BoxConstraints(maxWidth: 600)), Condition.equals(name: TABLET, value: BoxConstraints(maxWidth: 800)), Condition.largerThan( name: TABLET, value: BoxConstraints(maxWidth: 1280)), ], child: child), ); } }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/lib/presentation/core
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/lib/presentation/core/page_wrapper/page_template.dart
import 'package:flutter/material.dart'; import 'package:flutterweb/constants.dart'; import 'package:flutterweb/presentation/core/menu/appbar.dart'; import 'package:flutterweb/presentation/core/menu/drawer.dart'; import 'package:flutterweb/presentation/core/menu/menu_bar.dart'; import 'package:responsive_framework/responsive_framework.dart'; class PageTemplate extends StatelessWidget { final Widget child; const PageTemplate({Key? key, required this.child}) : super(key: key); @override Widget build(BuildContext context) { final responsiveValue = ResponsiveWrapper.of(context); return Scaffold( endDrawer: const CustomDrawer(), backgroundColor: background, appBar: responsiveValue.isSmallerThan(DESKTOP) ? const PreferredSize( preferredSize: Size(double.infinity, 60), child: CustomAppBar()) : const PreferredSize( preferredSize: Size(double.infinity, 66), child: CustomMenuBar(), ), body: child); } }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/lib/presentation
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/lib/presentation/not_found_page/not_found_page.dart
import 'package:flutter/material.dart'; import 'package:flutterweb/constants.dart'; import 'package:flutterweb/presentation/core/buttons/call_to_action.dart'; import 'package:flutterweb/presentation/core/page_wrapper/centered_constrained_wrapper.dart'; import 'package:flutterweb/presentation/core/page_wrapper/page_template.dart'; import 'package:flutterweb/presentation/home_page/homepage.dart'; import 'package:routemaster/routemaster.dart'; class NotFondPage extends StatelessWidget { const NotFondPage({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return PageTemplate( child: ListView( children: [ CenteredConstrainedWrapper( child: Padding( padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 50), child: Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ const Text( "Sorry, we couldn't find that page", style: TextStyle( fontFamily: fontFamily, color: Colors.blue, fontWeight: FontWeight.bold, fontSize: 20), ), const SizedBox( height: 20, ), const Text( "404", style: TextStyle( fontFamily: fontFamily, color: textPrimaryLight, fontWeight: FontWeight.bold, height: 0.9, fontSize: 60), ), ConstrainedBox( constraints: const BoxConstraints(maxHeight: 300), child: Image.asset("assets/images/mixer.png")), const SizedBox( height: 20, ), const Text( "But maybe you find help starting back from the homepage.", style: TextStyle( fontFamily: fontFamily, color: textPrimaryLight, fontWeight: FontWeight.bold, fontSize: 20), ), const SizedBox( height: 20, ), CallToAction( text: "Back to homepage", callback: () { Routemaster.of(context).push(HomePage.homePagePath); }, ) ], ), )) ], ), ); } }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/lib/presentation
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/lib/presentation/dev_page/dev_page.dart
import 'package:flutter/material.dart'; import 'package:flutterweb/presentation/core/page_wrapper/page_template.dart'; import 'package:flutterweb/presentation/dev_page/widgets/dev_start.dart'; class DevPage extends StatelessWidget { static const String devPagePath = "/development"; const DevPage({Key? key}) : super(key: key); @override Widget build(BuildContext context) { List<Widget> partblocks = [ const DevelopmentStart(), ]; return PageTemplate( child: ListView.builder( itemCount: partblocks.length, itemBuilder: (context, index) { return partblocks[index]; })); } }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/lib/presentation/dev_page
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/lib/presentation/dev_page/widgets/dev_start.dart
import 'package:flutter/material.dart'; import 'package:flutterweb/constants.dart'; import 'package:flutterweb/presentation/core/page_wrapper/centered_constrained_wrapper.dart'; import 'package:responsive_framework/responsive_framework.dart'; class DevelopmentStart extends StatelessWidget { const DevelopmentStart({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final responsiveValue = ResponsiveWrapper.of(context); return Container( width: double.infinity, decoration: BoxDecoration( gradient: LinearGradient(colors: [Colors.white, Colors.teal[100]!]), ), child: CenteredConstrainedWrapper( child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: [ ResponsiveRowColumn( columnVerticalDirection: VerticalDirection.up, columnMainAxisSize: MainAxisSize.min, layout: responsiveValue.isSmallerThan(DESKTOP) ? ResponsiveRowColumnType.COLUMN : ResponsiveRowColumnType.ROW, children: [ ResponsiveRowColumnItem( rowFlex: 1, child: Padding( padding: const EdgeInsets.symmetric( horizontal: 50, vertical: 20), child: Text( "Build more with Flutter", style: TextStyle( fontFamily: fontFamily, color: textPrimaryLight, fontWeight: FontWeight.bold, height: 0.9, fontSize: responsiveValue.isSmallerThan(DESKTOP) ? 40 : 75, ), textAlign: TextAlign.center, ), )), ResponsiveRowColumnItem( rowFlex: 1, child: Padding( padding: EdgeInsets.symmetric( vertical: 20, horizontal: responsiveValue.equals(TABLET) ? 120 : 50), child: Image.asset("assets/images/development.png"), )) ], ), Padding( padding: const EdgeInsets.symmetric( vertical: 20, horizontal: 50 ), child: Text( "Flutter transforms the app development process so you can ship more, faster. Deploy to six targets from a single codebase.", style: TextStyle( color: textPrimaryLight, fontFamily: fontFamily, fontSize: responsiveValue.isLargerThan(TABLET) ? 38 : 22), textAlign: TextAlign.center, ), ) ], )), ); } }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/flutter_web/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:flutterweb/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/FlutterLeichtGemacht_ZeroToMasery/advicer
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/injection.dart
import 'package:advicer/application/theme/theme_service.dart'; import 'package:advicer/domain/reposetories/advicer_repository.dart'; import 'package:advicer/domain/reposetories/theme_repositroy.dart'; import 'package:advicer/domain/usecases/advicer_usecases.dart'; import 'package:advicer/infrastructure/datasources/advicer_remote_datasource.dart'; import 'package:advicer/infrastructure/datasources/theme_local_datasource.dart'; import 'package:advicer/infrastructure/repositories/advicer_repository_impl.dart'; import 'package:advicer/infrastructure/repositories/theme_repository_impl.dart'; import 'package:get_it/get_it.dart'; import 'package:http/http.dart' as http; import 'package:shared_preferences/shared_preferences.dart'; import 'application/bloc/advicer_new_bloc.dart'; final sl = GetIt.I; // sl == service Locator Future<void> init() async { //! application layer sl.registerFactory(() => AdvicerNewBloc(usecases: sl())); sl.registerLazySingleton<ThemeService>(() => ThemeServiceImpl(themeRepository: sl())); //! Usecases sl.registerLazySingleton(() => AdvicerUsecases(advicerRepository: sl())); //! repos sl.registerLazySingleton<AdvicerRepository>(() => AdvicerRepositoryImpl(advicerRemoteDatasource: sl())); sl.registerLazySingleton<ThemeRepository>(() => ThemeRespositoryImpl(themeLocalDatasource: sl())); //! datasources sl.registerLazySingleton<AdvicerRemoteDatasource>(() => AdvicerRemoteDatasourceImpl(client: sl())); sl.registerLazySingleton<ThemeLocalDatasource>(() => ThemeLocalDatasourceImpl(sharedPreferences: sl())); //! extern sl.registerLazySingleton(() => http.Client()); final sharedPrefernces = await SharedPreferences.getInstance(); sl.registerLazySingleton(() => sharedPrefernces); }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/theme.dart
import 'package:flutter/material.dart'; class AppTheme { AppTheme._(); static final Color _lightPrimaryColor = Colors.blueGrey.shade50; static final Color _lightPrimaryVariantColor = Colors.blueGrey.shade800; static final Color _lightOnPrimaryColor = Colors.blueGrey.shade200; static const Color _lightTextColorPrimary = Colors.black; static const Color _appbarColorLight = Colors.blue; static final Color _darkPrimaryColor = Colors.blueGrey.shade900; static const Color _darkPrimaryVariantColor = Colors.black; static final Color _darkOnPrimaryColor = Colors.blueGrey.shade300; static const Color _darkTextColorPrimary = Colors.white; static final Color _appbarColorDark = Colors.blueGrey.shade800; static const Color _iconColor = Colors.white; static const Color _accentColorDark = Color.fromRGBO(74, 217, 217, 1); static const TextStyle _lightHeadingText = TextStyle( color: _lightTextColorPrimary, fontFamily: "Rubik", fontSize: 20, fontWeight: FontWeight.bold); static const TextStyle _lightBodyText = TextStyle( color: _lightTextColorPrimary, fontFamily: "Rubik", fontStyle: FontStyle.italic, fontWeight: FontWeight.bold, fontSize: 16); static const TextTheme _lightTextTheme = TextTheme( displayLarge: _lightHeadingText, bodyLarge: _lightBodyText, ); static final TextStyle _darkThemeHeadingTextStyle = _lightHeadingText.copyWith(color: _darkTextColorPrimary); static final TextStyle _darkThemeBodyeTextStyle = _lightBodyText.copyWith(color: _darkTextColorPrimary); static final TextTheme _darkTextTheme = TextTheme( displayLarge: _darkThemeHeadingTextStyle, bodyLarge: _darkThemeBodyeTextStyle, ); static final ThemeData lightTheme = ThemeData( scaffoldBackgroundColor: _lightPrimaryColor, appBarTheme: const AppBarTheme( color: _appbarColorLight, iconTheme: IconThemeData(color: _iconColor)), bottomAppBarTheme: const BottomAppBarTheme(color: _appbarColorLight), colorScheme: ColorScheme.light( primary: _lightPrimaryColor, onPrimary: _lightOnPrimaryColor, secondary: _accentColorDark, primaryContainer: _lightPrimaryVariantColor), textTheme: _lightTextTheme); static final ThemeData darkTheme = ThemeData( scaffoldBackgroundColor: _darkPrimaryColor, appBarTheme: AppBarTheme( color: _appbarColorDark, iconTheme: const IconThemeData(color: _iconColor)), bottomAppBarTheme: BottomAppBarTheme(color: _appbarColorDark), colorScheme: ColorScheme.dark( primary: _darkPrimaryColor, secondary: _accentColorDark, onPrimary: _darkOnPrimaryColor, primaryContainer: _darkPrimaryVariantColor, ), textTheme: _darkTextTheme); }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/main.dart
import 'package:advicer/application/bloc/advicer_new_bloc.dart'; import 'package:advicer/application/theme/theme_service.dart'; import 'package:advicer/presentation/advicer/advicer_page.dart'; import 'package:advicer/theme.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:provider/provider.dart'; import 'injection.dart' as di; import 'injection.dart'; // di == dependency injection void main() async { WidgetsFlutterBinding.ensureInitialized(); await di.init(); await di.sl<ThemeService>().init(); runApp( ChangeNotifierProvider( create: (context) => di.sl<ThemeService>(), child: const MyApp(), ), ); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Consumer<ThemeService>( builder: (context, themeService, child) { return MaterialApp( title: 'Advicer', theme: AppTheme.lightTheme, darkTheme: AppTheme.darkTheme, themeMode: themeService.useSystemTheme ? ThemeMode.system : themeService.isDarkModeOn ? ThemeMode.dark : ThemeMode.light, home: BlocProvider( create: (context) => sl<AdvicerNewBloc>(), child: const AdvicerPage()), ); }, ); } }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/widget_test_examples/simple_text.dart
import 'package:flutter/material.dart'; class MyWidget extends StatelessWidget { const MyWidget({ Key? key, required this.title, required this.message, }) : super(key: key); final String title; final String message; @override Widget build(BuildContext context) { return MaterialApp( title: 'simple text', home: Scaffold( appBar: AppBar( title: Text(title), ), body: Center( child: Text(message), ), ), ); } }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/application
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/application/advicer/advicer_event.dart
part of 'advicer_bloc.dart'; @immutable abstract class AdvicerEvent {} /// event when button is pressed class AdviceRequestedEvent extends AdvicerEvent {}
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/application
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/application/advicer/advicer_state.dart
part of 'advicer_bloc.dart'; @immutable abstract class AdvicerState {} class AdvicerInitial extends AdvicerState with EquatableMixin { @override List<Object?> get props => []; } class AdvicerStateLoading extends AdvicerState with EquatableMixin { @override List<Object?> get props => []; } class AdvicerStateLoaded extends AdvicerState with EquatableMixin { @override List<Object?> get props => [advice]; final String advice; AdvicerStateLoaded({required this.advice}); } class AdvicerStateError extends AdvicerState with EquatableMixin { @override List<Object?> get props => [message]; final String message; AdvicerStateError({required this.message}); }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/application
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/application/advicer/advicer_bloc.dart
import 'dart:async'; import 'package:advicer/domain/entities/advice_enitity.dart'; import 'package:advicer/domain/failures/failures.dart'; import 'package:advicer/domain/usecases/advicer_usecases.dart'; import 'package:bloc/bloc.dart'; import 'package:dartz/dartz.dart'; import 'package:equatable/equatable.dart'; import 'package:meta/meta.dart'; part 'advicer_event.dart'; part 'advicer_state.dart'; const GENERAL_FAILURE_MESSAGE = "Ups, something gone wrong. Please try again!"; const SERVER_FAILURE_MESSAGE = "Ups, API Error. please try again!"; class AdvicerBloc extends Bloc<AdvicerEvent, AdvicerState> { AdvicerBloc({required this.usecases}) : super(AdvicerInitial()); final AdvicerUsecases usecases; @override Stream<AdvicerState> mapEventToState( AdvicerEvent event, ) async* { if (event is AdviceRequestedEvent) { yield AdvicerStateLoading(); Either<Failure, AdviceEntity> adviceOrFailure = await usecases.getAdviceUsecase(); yield adviceOrFailure.fold( (failure) => AdvicerStateError(message: _mapFailureToMessage(failure)), (advice) => AdvicerStateLoaded(advice: advice.advice)); } } String _mapFailureToMessage(Failure failure) { switch (failure.runtimeType) { case ServerFailure: return SERVER_FAILURE_MESSAGE; case GeneralFailure: return GENERAL_FAILURE_MESSAGE; default: return GENERAL_FAILURE_MESSAGE; } } }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/application
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/application/bloc/advicer_new_event.dart
part of 'advicer_new_bloc.dart'; abstract class AdvicerEvent {} /// event when button is pressed class AdviceRequestedEvent extends AdvicerEvent {} class ExampleEvent extends AdvicerEvent {}
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/application
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/application/bloc/advicer_new_bloc.dart
import 'package:advicer/domain/entities/advice_enitity.dart'; import 'package:advicer/domain/failures/failures.dart'; import 'package:advicer/domain/usecases/advicer_usecases.dart'; import 'package:bloc/bloc.dart'; import 'package:dartz/dartz.dart'; import 'package:equatable/equatable.dart'; part 'advicer_new_event.dart'; part 'advicer_new_state.dart'; const GENERAL_FAILURE_MESSAGE = "Ups, something gone wrong. Please try again!"; const SERVER_FAILURE_MESSAGE = "Ups, API Error. please try again!"; class AdvicerNewBloc extends Bloc<AdvicerEvent, AdvicerState> { final AdvicerUsecases usecases; AdvicerNewBloc({required this.usecases}) : super(AdvicerInitial()) { on<AdviceRequestedEvent>((event, emit) async { emit(AdvicerStateLoading()); Either<Failure, AdviceEntity> adviceOrFailure = await usecases.getAdviceUsecase(); adviceOrFailure.fold( (failure) => emit(AdvicerStateError(message: _mapFailureToMessage(failure))), (advice) => emit(AdvicerStateLoaded(advice: advice.advice))); }); } String _mapFailureToMessage(Failure failure) { switch (failure.runtimeType) { case ServerFailure: return SERVER_FAILURE_MESSAGE; case GeneralFailure: return GENERAL_FAILURE_MESSAGE; default: return GENERAL_FAILURE_MESSAGE; } } }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/application
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/application/bloc/advicer_new_state.dart
part of 'advicer_new_bloc.dart'; abstract class AdvicerState {} class AdvicerInitial extends AdvicerState with EquatableMixin { @override List<Object?> get props => []; } class AdvicerStateLoading extends AdvicerState with EquatableMixin { @override List<Object?> get props => []; } class AdvicerStateLoaded extends AdvicerState with EquatableMixin { @override List<Object?> get props => [advice]; final String advice; AdvicerStateLoaded({required this.advice}); } class AdvicerStateError extends AdvicerState with EquatableMixin { @override List<Object?> get props => [message]; final String message; AdvicerStateError({required this.message}); }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/application
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/application/theme/theme_service.dart
import 'package:advicer/domain/reposetories/theme_repositroy.dart'; import 'package:flutter/material.dart'; abstract class ThemeService extends ChangeNotifier { late bool isDarkModeOn; late bool useSystemTheme; Future<void> toggleTheme(); Future<void> toggleUseSystemTheme(); Future<void> setTheme({required bool mode}); Future<void> setUseSystemTheme({required bool sytemTheme}); Future<void> init(); } class ThemeServiceImpl extends ChangeNotifier implements ThemeService { final ThemeRepository themeRepository; ThemeServiceImpl({required this.themeRepository}); @override bool isDarkModeOn = true; @override late bool useSystemTheme; @override Future<void> setTheme({required bool mode}) async { isDarkModeOn = mode; notifyListeners(); await themeRepository.setThemeMode(mode: isDarkModeOn); } @override Future<void> toggleTheme() async { isDarkModeOn = !isDarkModeOn; await setTheme(mode: isDarkModeOn); } @override Future<void> setUseSystemTheme({required bool sytemTheme}) async { useSystemTheme = sytemTheme; notifyListeners(); await themeRepository.setUseSytemTheme(useSystemTheme: useSystemTheme); } @override Future<void> toggleUseSystemTheme() async { useSystemTheme = !useSystemTheme; await setUseSystemTheme(sytemTheme: useSystemTheme); } @override Future<void> init() async { final useSystemThemeOrFailure = await themeRepository.getUseSytemTheme(); await useSystemThemeOrFailure.fold((failure) async { await setUseSystemTheme(sytemTheme: false); }, (useSystemTheme) async { await setUseSystemTheme(sytemTheme: useSystemTheme); }); final modeOrFailure = await themeRepository.getThemeMode(); await modeOrFailure.fold((failure) async { await setTheme(mode: true); }, (mode) => setTheme(mode: mode)); } }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/infrastructure
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/infrastructure/models/advice_model.dart
import 'package:advicer/domain/entities/advice_enitity.dart'; import 'package:equatable/equatable.dart'; class AdviceModel extends AdviceEntity with EquatableMixin{ AdviceModel({required String advice, required int id}) : super(advice: advice, id: id); factory AdviceModel.fromJson(Map<String,dynamic> json){ return AdviceModel( advice: json["advice"], id: json["id"] ); } @override List<Object?> get props => [advice, id]; }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/infrastructure
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/infrastructure/datasources/theme_local_datasource.dart
import 'package:advicer/infrastructure/exceptions/exceptions.dart'; import 'package:shared_preferences/shared_preferences.dart'; const CACHED_THEME_MODE = 'CACHED_THEME_MODE'; const CACHED_USE_SYSTEM_THEME = 'CACHED_USE_SYSTEM_THEME'; abstract class ThemeLocalDatasource { Future<bool> getCachedThemeData(); Future<bool> getUseSystemTheme(); Future<void> cacheThemeData({required bool mode}); Future<void> cacheUseSystemTheme({required bool useSystemTheme}); } class ThemeLocalDatasourceImpl implements ThemeLocalDatasource { final SharedPreferences sharedPreferences; ThemeLocalDatasourceImpl({required this.sharedPreferences}); @override Future<void> cacheThemeData({required bool mode}) { return sharedPreferences.setBool(CACHED_THEME_MODE, mode); } @override Future<bool> getCachedThemeData() { final modeBool = sharedPreferences.getBool(CACHED_THEME_MODE); if (modeBool != null) { return Future.value(modeBool); } else { throw CacheException(); } } @override Future<void> cacheUseSystemTheme({required bool useSystemTheme}) { return sharedPreferences.setBool(CACHED_USE_SYSTEM_THEME, useSystemTheme); } @override Future<bool> getUseSystemTheme() { final useSystemTheme = sharedPreferences.getBool(CACHED_USE_SYSTEM_THEME); if (useSystemTheme != null) { return Future.value(useSystemTheme); } else { throw CacheException(); } } }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/infrastructure
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/infrastructure/datasources/advicer_remote_datasource.dart
import 'package:advicer/domain/entities/advice_enitity.dart'; import 'package:advicer/infrastructure/exceptions/exceptions.dart'; import 'package:advicer/infrastructure/models/advice_model.dart'; import 'package:http/http.dart' as http; import 'dart:convert'; abstract class AdvicerRemoteDatasource { /// requests a randmom advice from free api /// throws a server-Exception if respond code is not 200 Future<AdviceEntity> getRandomAdviceFromApi(); } class AdvicerRemoteDatasourceImpl implements AdvicerRemoteDatasource { final http.Client client; AdvicerRemoteDatasourceImpl({required this.client}); @override Future<AdviceEntity> getRandomAdviceFromApi() async { final response = await client.get( Uri.parse("https://api.adviceslip.com/advice"), headers: { 'Content-Type': 'application/json', }, ); if (response.statusCode != 200) { throw SeverException(); } else { final responseBody = json.decode(response.body); return AdviceModel.fromJson(responseBody["slip"]); } } }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/infrastructure
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/infrastructure/repositories/advicer_repository_impl.dart
import 'package:advicer/domain/failures/failures.dart'; import 'package:advicer/domain/entities/advice_enitity.dart'; import 'package:advicer/domain/reposetories/advicer_repository.dart'; import 'package:advicer/infrastructure/datasources/advicer_remote_datasource.dart'; import 'package:advicer/infrastructure/exceptions/exceptions.dart'; import 'package:dartz/dartz.dart'; class AdvicerRepositoryImpl implements AdvicerRepository { final AdvicerRemoteDatasource advicerRemoteDatasource; AdvicerRepositoryImpl({required this.advicerRemoteDatasource}); @override Future<Either<Failure, AdviceEntity>> getAdviceFromApi() async { try { final remoteAdvice = await advicerRemoteDatasource.getRandomAdviceFromApi(); return Right(remoteAdvice); } catch (e) { if (e is SeverException) { return Left(ServerFailure()); } else { return Left(GeneralFailure()); } } } }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/infrastructure
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/infrastructure/repositories/theme_repository_impl.dart
import 'package:advicer/domain/failures/failures.dart'; import 'package:advicer/domain/reposetories/theme_repositroy.dart'; import 'package:advicer/infrastructure/datasources/theme_local_datasource.dart'; import 'package:dartz/dartz.dart'; class ThemeRespositoryImpl implements ThemeRepository { final ThemeLocalDatasource themeLocalDatasource; ThemeRespositoryImpl({required this.themeLocalDatasource}); @override Future<Either<Failure, bool>> getThemeMode() async { try { final themeMode = await themeLocalDatasource.getCachedThemeData(); return Right(themeMode); } catch (e) { return Left(CacheFailure()); } } @override Future<void> setThemeMode({required bool mode}) { return themeLocalDatasource.cacheThemeData(mode: mode); } @override Future<Either<Failure, bool>> getUseSytemTheme() async { try { final themeMode = await themeLocalDatasource.getUseSystemTheme(); return Right(themeMode); } catch (e) { return Left(CacheFailure()); } } @override Future<void> setUseSytemTheme({required bool useSystemTheme}) { return themeLocalDatasource.cacheUseSystemTheme(useSystemTheme: useSystemTheme); } }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/infrastructure
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/infrastructure/exceptions/exceptions.dart
class SeverException implements Exception{} class CacheException implements Exception{}
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/presentation
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/presentation/advicer/advicer_page.dart
import 'package:advicer/application/bloc/advicer_new_bloc.dart'; import 'package:advicer/application/theme/theme_service.dart'; import 'package:advicer/presentation/advicer/widgets/advice_field.dart'; import 'package:advicer/presentation/advicer/widgets/custom_button.dart'; import 'package:advicer/presentation/advicer/widgets/error_message.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:provider/provider.dart'; class AdvicerPage extends StatelessWidget { const AdvicerPage({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final themeData = Theme.of(context); return Scaffold( appBar: AppBar( centerTitle: false, actions: [ Visibility( visible: !Provider.of<ThemeService>(context).useSystemTheme, child: Switch( value: Provider.of<ThemeService>(context).isDarkModeOn, onChanged: (_) { Provider.of<ThemeService>(context, listen: false) .toggleTheme(); }), ), Switch( value: Provider.of<ThemeService>(context).useSystemTheme, activeColor: Colors.redAccent, onChanged: (_) { Provider.of<ThemeService>(context, listen: false) .toggleUseSystemTheme(); }) ], title: Text( "Advicer", style: themeData.textTheme.displayLarge, )), body: Center( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 50), child: Column( children: [ Expanded( child: Center( child: BlocBuilder<AdvicerNewBloc, AdvicerState>( bloc: BlocProvider.of<AdvicerNewBloc>(context), builder: (context, adviceState) { if (adviceState is AdvicerInitial) { return Text( "Your Advice is waiting for you!", style: themeData.textTheme.displayLarge, ); } else if (adviceState is AdvicerStateLoading) { return CircularProgressIndicator( color: themeData.colorScheme.secondary, ); } else if (adviceState is AdvicerStateLoaded) { return AdviceField( advice: adviceState.advice, ); } else if (adviceState is AdvicerStateError) { return ErrorMessage( message: adviceState.message, ); } return const Placeholder(); }, )), ), const SizedBox( height: 200, child: Center( child: CustomButton(), ), ) ], ), ), ), ); } }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/presentation/advicer
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/presentation/advicer/widgets/error_message.dart
import 'package:flutter/material.dart'; class ErrorMessage extends StatelessWidget { final String message; const ErrorMessage({Key? key, required this.message}) : super(key: key); @override Widget build(BuildContext context) { final themeData = Theme.of(context); return Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const Icon( Icons.error, size: 40, color: Colors.redAccent, ), const SizedBox( height: 20, ), Text( message, style: themeData.textTheme.displayLarge, textAlign: TextAlign.center, ) ], ); } }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/presentation/advicer
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/presentation/advicer/widgets/custom_button.dart
import 'package:advicer/application/bloc/advicer_new_bloc.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class CustomButton extends StatelessWidget { const CustomButton({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final themeData = Theme.of(context); return InkResponse( onTap: () => BlocProvider.of<AdvicerNewBloc>(context).add(AdviceRequestedEvent()), child: Material( elevation: 20, borderRadius: BorderRadius.circular(15), child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(15), color: themeData.colorScheme.secondary), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 15), child: Text( "Get Advice", style: themeData.textTheme.displayLarge, ), ), ), ), ); } }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/presentation/advicer
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/presentation/advicer/widgets/advice_field.dart
import 'package:flutter/material.dart'; class AdviceField extends StatelessWidget { final String advice; const AdviceField({ Key? key , required this.advice}) : super(key: key); @override Widget build(BuildContext context) { final themeData = Theme.of(context); return Material( elevation: 20, borderRadius: BorderRadius.circular(15), child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(15), color: themeData.colorScheme.onPrimary), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 20), child: Text('''" $advice "''', style: themeData.textTheme.bodyLarge,textAlign: TextAlign.center,), ), ), ); } }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/domain
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/domain/reposetories/advicer_repository.dart
import 'package:advicer/domain/entities/advice_enitity.dart'; import 'package:advicer/domain/failures/failures.dart'; import 'package:dartz/dartz.dart'; abstract class AdvicerRepository { /// Calls free Advice Slip api to get a random advice /// returns a [serverFailure] if status code was not 200 /// it will return a [genralFailure] for all other failures Future<Either<Failure, AdviceEntity>> getAdviceFromApi(); }
0
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/domain
mirrored_repositories/FlutterLeichtGemacht_ZeroToMasery/advicer/lib/domain/reposetories/theme_repositroy.dart
import 'package:advicer/domain/failures/failures.dart'; import 'package:dartz/dartz.dart'; abstract class ThemeRepository { Future<Either<Failure, bool>> getThemeMode(); Future<void> setThemeMode({required bool mode}); Future<Either<Failure, bool>> getUseSytemTheme(); Future<void> setUseSytemTheme({required bool useSystemTheme}); }
0