repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/kryptonian-flutter-app/lib
mirrored_repositories/kryptonian-flutter-app/lib/widgets/category_item.dart
import 'package:flutter/material.dart'; import 'package:flutter_complete_guide/pallete/deepBlue.dart'; import 'package:flutter_complete_guide/screens/products_overview_screen.dart'; class CategoryItem extends StatelessWidget { final String id; final String title; final String imgUrl; CategoryItem({ @required this.id, @required this.title, @required this.imgUrl, }); /// Navigator PushNamed void selectCategory(BuildContext context) { Navigator.of(context).pushNamed( ProductsOverviewScreen.routeName, arguments: [id, true], ); } @override Widget build(BuildContext context) { return _buildGridContent(context); } Widget _buildGridContent(BuildContext context) { return ClipRRect( borderRadius: BorderRadius.circular(20), child: GridTile( child: GestureDetector( onTap: () => selectCategory(context), child: _buildImageAnimatedWidget(imgUrl), ), footer: GridTileBar( leading: Icon(Icons.apps), backgroundColor: Colors.black87, title: Text( title, textAlign: TextAlign.center, ), ), ), ); } Widget _buildImageAnimatedWidget(String imageUrl) { return FadeInImage( imageErrorBuilder: (context, _, __) => Image.asset('assets/images/product-placeholder.png'), placeholder: AssetImage('assets/images/product-placeholder.png'), image: NetworkImage(imageUrl), fit: BoxFit.cover, ); } Widget _buildInkWellContent(BuildContext context) { return InkWell( onTap: () => selectCategory(context), splashColor: Theme.of(context).primaryColor, borderRadius: BorderRadius.circular(15), child: Container( padding: EdgeInsets.all(0), child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(12), color: Colors.black.withOpacity(0.5), ), padding: EdgeInsets.all(10), margin: EdgeInsets.only(top: 65), width: double.infinity, height: 22, child: Text( title, style: TextStyle( color: Colors.white60, fontWeight: FontWeight.bold, fontSize: 18, fontFamily: 'Lato', ), ), ), decoration: BoxDecoration( gradient: LinearGradient( colors: [ DeepBlue.kToDark.shade900, DeepBlue.kToDark.shade100, ], begin: Alignment.topLeft, end: Alignment.bottomRight, ), image: DecorationImage( image: NetworkImage(imgUrl), fit: BoxFit.fill, ), borderRadius: BorderRadius.circular(15.0), ), ), ); } }
0
mirrored_repositories/kryptonian-flutter-app/lib
mirrored_repositories/kryptonian-flutter-app/lib/widgets/custom_raised_button.dart
import 'package:flutter/material.dart'; class CustomRaisedButton extends StatelessWidget { CustomRaisedButton({ this.child, this.backgroundColor, this.textColor, this.fontSize, this.borderRadius: 2.0, this.height: 50.0, this.onPressed, }) : assert(borderRadius != null); final Widget child; final Color backgroundColor; final Color textColor; final double fontSize; final double borderRadius; final double height; final VoidCallback onPressed; @override Widget build(BuildContext context) { return SizedBox( height: height, child: ElevatedButton( child: child, onPressed: onPressed, style: ElevatedButton.styleFrom( primary: backgroundColor, onPrimary: textColor, onSurface: backgroundColor, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(borderRadius), ), textStyle: TextStyle( fontSize: fontSize, ), ), ), ); } }
0
mirrored_repositories/kryptonian-flutter-app/lib
mirrored_repositories/kryptonian-flutter-app/lib/widgets/product_item.dart
import 'package:flutter/material.dart'; import 'package:flutter_complete_guide/providers/products.dart'; import 'package:flutter_complete_guide/widgets/badge.dart'; import 'package:flutter_complete_guide/providers/cart.dart'; import 'package:flutter_complete_guide/providers/product.dart'; import 'package:flutter_complete_guide/screens/product_details_screen.dart'; import 'package:provider/provider.dart'; import 'badge.dart'; class ProductItem extends StatelessWidget { final int index; ProductItem({this.index}); void _selectProduct(BuildContext context, Product productData, index) { Navigator.of(context).pushNamed( ProductDetailsScreen.routeName, arguments: [productData.id, index], ); } void _cartUpdateHandler( Products products, Product productData, Cart cartData) { products.addProductQuantity(productData.id, index); cartData.addItems(productData.id, productData.title, productData.price); print('CALL => CartUpdateHandler'); } void _gestureUpDownHandler(DragUpdateDetails direction, Product productData, Products productsData, Cart cartData) { int sensitivity = 0; if (direction.delta.direction > sensitivity) { /// Down Swipe productsData.decreaseProductQuantity(productData.id, index); cartData.reduceItems(productData.id); print('CALL => CartUpdateHandler, Decrease Qty'); } else if (direction.delta.direction < sensitivity) { /// Up Swipe productsData.addProductQuantity(productData.id, index); cartData.addItems(productData.id, productData.title, productData.price); print('CALL => CartUpdateHandler, Increase Qty'); } } void _dismissRightHandler(DismissDirection direction, Product productData, Products productsData, Cart cartData) { /// Right Swipe productsData.addProductQuantity(productData.id, index); cartData.addItems(productData.id, productData.title, productData.price); print('CALL => CartUpdateHandler, Increase Qty'); } void _dismissLeftHandler(DismissDirection direction, Product productData, Products productsData, Cart cartData) { /// Left Swipe productsData.decreaseProductQuantity(productData.id, index); cartData.reduceItems(productData.id); print('CALL => CartUpdateHandler, Decrease Qty'); } @override Widget build(BuildContext context) { /// Provider.of<> - way to extract data from Product class /// If listen: true => notifyListeners triggers the build method /// if listen: false => notifyListeners cannot trigger /// Consumer<Product> can be wrapped on the Child that needs rebuild when notified /// Child Argument in Consumer doesn't rebuild final productData = Provider.of<Product>(context, listen: true); final cartData = Provider.of<Cart>(context, listen: true); final productsData = Provider.of<Products>(context, listen: true); return ClipRRect( borderRadius: BorderRadius.circular(20), child: GridTile( child: GestureDetector( onTap: () => _selectProduct(context, productData, index), child: _buildImageAnimatedWidget(productData), ), footer: GridTileBar( leading: Consumer<Product>( builder: (ctx, product, child) => IconButton( icon: productData.isFavorite ? Icon(Icons.favorite) : Icon(Icons.favorite_border), onPressed: () => productData.toggleFavoriteStatus(), color: Theme.of(context).accentColor, ), ), backgroundColor: Colors.black87, title: Dismissible( key: UniqueKey(), direction: DismissDirection.horizontal, onDismissed: (direction) { print('DismissDirection => ${direction.toString()}'); if (direction.toString() == "DismissDirection.startToEnd") { _dismissRightHandler( direction, productData, productsData, cartData); } else if (direction.toString() == "DismissDirection.endToStart") { _dismissLeftHandler( direction, productData, productsData, cartData); } }, background: _buildDismissRightContainer(), secondaryBackground: _buildDismissLeftContainer(), child: Text( productData.title, textAlign: TextAlign.center, ), ), trailing: Consumer<Products>( builder: (_, products, __) => Badge( color: Colors.black54, textColor: Colors.white, //value: products.item[index].qty.toString(), //value: cartData.getItemQuantity(products.item[index].id).toString(), value: cartData .getItemQuantity(products .item[products.getIndexByProductId(productData.id)].id) .toString(), child: IconButton( icon: Icon(Icons.shopping_cart), onPressed: () { _cartUpdateHandler(products, productData, cartData); ScaffoldMessenger.of(context).hideCurrentSnackBar(); ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text( 'Item Added to Cart πŸ›’', style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold, ), ), duration: Duration(seconds: 3), backgroundColor: AppBarTheme.of(context).backgroundColor, action: SnackBarAction( onPressed: () { products.decreaseProductQuantity( productData.id, index); cartData.clearSingleItem(productData.id); }, label: 'Undo', ), ), ); }, color: Theme.of(context).accentColor, ), ), ), ), ), ); } Image _buildImageContent(Product productData) { return Image.network( productData.imageUrl, errorBuilder: (context, error, stackTrace) => Image.asset('assets/images/placeholder.png'), ); } Widget _buildImageAnimatedWidget(Product productData) { return Hero( tag: productData.id, child: FadeInImage( imageErrorBuilder: (context, _, __) => Image.asset('assets/images/product-placeholder.png'), placeholder: AssetImage('assets/images/product-placeholder.png'), image: NetworkImage(productData.imageUrl), fit: BoxFit.cover, ), ); } Container _buildDismissRightContainer() { return Container( height: 50.0, width: 50.0, color: Colors.black12, child: Icon( Icons.add_shopping_cart, color: Colors.greenAccent, size: 18, ), alignment: Alignment.centerLeft, padding: EdgeInsets.only(right: 0), margin: EdgeInsets.symmetric(vertical: 0, horizontal: 0), ); } Container _buildDismissLeftContainer() { return Container( height: 50.0, width: 50.0, color: Colors.black12, child: Icon( Icons.delete, color: Colors.redAccent, size: 18, ), alignment: Alignment.centerRight, padding: EdgeInsets.only(right: 0), margin: EdgeInsets.symmetric(vertical: 0, horizontal: 0), ); } }
0
mirrored_repositories/kryptonian-flutter-app/lib
mirrored_repositories/kryptonian-flutter-app/lib/models/http_exception.dart
class HttpException implements Exception { final String message; HttpException({this.message}); @override String toString() { // TODO: implement toString return message; //return super.toString(); } }
0
mirrored_repositories/kryptonian-flutter-app/lib
mirrored_repositories/kryptonian-flutter-app/lib/data/category_dummy_data.dart
import 'package:flutter_complete_guide/providers/category.dart'; List<Category> categoryDummyData = []; List<Category> categoryDummyDataTemp = [ Category( id: 'c1', title: 'Electronics', imgUrl: 'https://www.pngitem.com/pimgs/m/247-2474633_transparent-electronics-items-png-png-download.png', ), Category( id: 'c2', title: 'Clothing', imgUrl: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcR43UnRwuzRAlZiClSlNLirgvkY8eJCqAWHEQ&usqp=CAU', ), Category( id: 'c3', title: 'Toys', imgUrl: 'http://marveltoynews.com/wp-content/uploads/2013/07/Avengers-Hot-Toys-Thor-Black-Widow-Captain-America-Hawkeye.jpg', ), Category( id: 'c4', title: 'Sports', imgUrl: 'https://thumbs.dreamstime.com/b/assorted-sports-equipment-black-11153245.jpg', ), Category( id: 'c5', title: 'Beauty Care', imgUrl: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRooKtW-v4U8ArQ6I_j7WiIqHGl-KayjtEiIQ&usqp=CAU', ), Category( id: 'c6', title: 'Education', imgUrl: 'https://www.lego.com/cdn/cs/history/assets/blt002c90de12385725/LEGO_Education_EV3.jpg?disable=upscale&width=960&quality=50', ), Category( id: 'c7', title: 'Food', imgUrl: 'https://img.freepik.com/free-photo/chicken-wings-barbecue-sweetly-sour-sauce-picnic-summer-menu-tasty-food-top-view-flat-lay_2829-6471.jpg?size=626&ext=jpg&ga=GA1.2.1450000434.1639526400', ), Category( id: 'c8', title: 'Others', imgUrl: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSnNCvZQVZxOl7iMO80Cc6UwgvrEx_WnUbMqw&usqp=CAU', ), ];
0
mirrored_repositories/kryptonian-flutter-app/lib
mirrored_repositories/kryptonian-flutter-app/lib/helpers/custom_route.dart
import 'package:flutter/material.dart'; class CustomRoute<T> extends MaterialPageRoute<T> { CustomRoute({WidgetBuilder builder, RouteSettings settings}) : super( builder: builder, settings: settings, ); @override Widget buildTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) { // TODO: implement buildTransitions return FadeTransition( opacity: animation, child: child, ); } }
0
mirrored_repositories/kryptonian-flutter-app/lib
mirrored_repositories/kryptonian-flutter-app/lib/helpers/theme_config.dart
import 'package:flutter/material.dart'; import 'package:flutter_complete_guide/pallete/deepBlue.dart'; ThemeData lightTheme = ThemeData.light(); ThemeData darkTheme = ThemeData.dark(); ThemeData dayTheme = ThemeData( brightness: Brightness.light, cursorColor: DeepBlue.kToDark, fontFamily: 'Lato', primaryColor: DeepBlue.kToDark, accentColor: Colors.deepOrange, appBarTheme: AppBarTheme( backgroundColor: DeepBlue.kToDark, ), iconTheme: IconThemeData( color: DeepBlue.kToDark, ), textSelectionTheme: TextSelectionThemeData( cursorColor: Colors.deepOrange, selectionColor: Colors.deepOrange, selectionHandleColor: Colors.deepOrange, ), colorScheme: ColorScheme( background: Colors.white, onBackground: Colors.white, brightness: Brightness.light, primaryVariant: DeepBlue.kToDark, primary: DeepBlue.kToDark, secondaryVariant: Colors.deepOrange, secondary: Colors.deepOrange, surface: Colors.white, onSurface: Colors.white, error: Colors.red, onError: Colors.red, onPrimary: Colors.white, onSecondary: Colors.deepOrange, ), ); ThemeData nightTheme = ThemeData( cursorColor: Colors.deepOrange, textSelectionTheme: TextSelectionThemeData( cursorColor: Colors.deepOrange, selectionColor: Colors.deepOrange, selectionHandleColor: Colors.deepOrange, ), fontFamily: 'Lato', brightness: Brightness.dark, scaffoldBackgroundColor: Colors.black, splashColor: Colors.black, backgroundColor: Colors.black, primaryColor: DeepBlue.kToDark, accentColor: Colors.deepOrange, cardColor: DeepBlue.kToDark.shade500, colorScheme: ColorScheme( background: DeepBlue.kToDark, onBackground: Colors.white, brightness: Brightness.dark, primaryVariant: DeepBlue.kToDark, primary: DeepBlue.kToDark, secondaryVariant: Colors.deepOrange, secondary: Colors.deepOrange, surface: Colors.white, onSurface: Colors.white, error: Colors.red, onError: Colors.red, onPrimary: DeepBlue.kToDark, onSecondary: Colors.deepOrange, ), canvasColor: Colors.black, iconTheme: IconThemeData( color: Colors.deepOrange, ), appBarTheme: AppBarTheme( backgroundColor: DeepBlue.kToDark, ), );
0
mirrored_repositories/kryptonian-flutter-app/lib
mirrored_repositories/kryptonian-flutter-app/lib/screens/liquid_welcome_screen.dart
import 'package:eva_icons_flutter/eva_icons_flutter.dart'; import 'package:flutter/material.dart'; import 'package:flutter_complete_guide/screens/auth_screen.dart'; import 'package:flutter_complete_guide/widgets/welcome.dart'; import 'package:liquid_swipe/liquid_swipe.dart'; class LiquidWelcomeScreen extends StatefulWidget { @override State<LiquidWelcomeScreen> createState() => _LiquidWelcomeScreenState(); } class _LiquidWelcomeScreenState extends State<LiquidWelcomeScreen> { final pages = [ Container(child: Welcome()), Container(child: AuthScreen()), ]; @override Widget build(BuildContext context) { return LiquidSwipe( pages: pages, enableLoop: true, fullTransitionValue: 300, enableSlideIcon: true, waveType: WaveType.liquidReveal, positionSlideIcon: 0.5, slideIconWidget: Icon( EvaIcons.chevronLeft, color: Colors.deepOrange, size: 40, ), ); } }
0
mirrored_repositories/kryptonian-flutter-app/lib
mirrored_repositories/kryptonian-flutter-app/lib/screens/cart_screen.dart
import 'package:flutter/material.dart'; import 'package:flutter_complete_guide/pallete/deepBlue.dart'; import 'package:flutter_complete_guide/providers/auth.dart'; import 'package:flutter_complete_guide/providers/cart.dart' show Cart; import 'package:flutter_complete_guide/providers/light.dart'; import 'package:flutter_complete_guide/providers/orders.dart'; import 'package:flutter_complete_guide/providers/products.dart'; import 'package:flutter_complete_guide/screens/orders_screen.dart'; import 'package:flutter_complete_guide/widgets/cart_item.dart'; import 'package:provider/provider.dart'; class CartScreen extends StatelessWidget { static const routeName = '/cart'; @override Widget build(BuildContext context) { print('BUILD => CART SCREEN'); final cartData = Provider.of<Cart>(context); final ordersData = Provider.of<Orders>(context); final deviceSize = MediaQuery.of(context).size; return Scaffold( appBar: AppBar( title: Text('My Cart'), ), body: SingleChildScrollView( child: Column( children: <Widget>[ Card( color: Colors.blueGrey.withOpacity(0.2), elevation: 20, margin: EdgeInsets.all(14), child: _buildTopHeader(context, cartData, ordersData), ), SizedBox(height: 20), Container( height: deviceSize.height * 0.69, child: _buildListView(cartData), ), ], ), ), ); } Widget _buildListView(Cart cartData) { return ListView.builder( itemCount: cartData.itemCount, itemBuilder: (context, index) => CartItem( id: cartData.items.values.toList()[index].id, productId: cartData.items.values.toList()[index].productId, title: cartData.items.values.toList()[index].title, price: cartData.items.values.toList()[index].price, quantity: cartData.items.values.toList()[index].quantity, ), ); } ListView _buildListViewBody(Cart cartData) { return ListView.builder( itemCount: cartData.itemsList.length, itemBuilder: (context, index) => Dismissible( key: UniqueKey(), direction: DismissDirection.endToStart, onDismissed: (direction) => cartData.deleteItems(cartData.itemsList[index].productId), background: Container(color: Colors.red), child: Card( margin: EdgeInsets.symmetric(vertical: 8, horizontal: 12), elevation: 4, child: Padding( padding: const EdgeInsets.all(5.0), child: ListTile( leading: CircleAvatar( backgroundColor: Theme.of(context).primaryColor, radius: 30, child: FittedBox( child: Text( '\$${cartData.itemsList[index].price}', style: TextStyle(color: Colors.white), ), ), ), title: Text( cartData.itemsList[index].title, style: TextStyle( fontWeight: FontWeight.w700, ), ), subtitle: Text( 'Total: \$${cartData.getTotalItemPrice(cartData.itemsList[index])}'), trailing: Text( '${cartData.itemsList[index].quantity} x', style: TextStyle( fontSize: 18, fontWeight: FontWeight.bold, ), ), ), ), ), ), ); } Future<void> _showAlertDialog(BuildContext context) async { await showDialog<Null>( context: context, builder: (context) => AlertDialog( elevation: 10.4, title: Text('Attention Schmuck', textAlign: TextAlign.center), content: Text('Something Went Wrong. Try Creating Orders later!', textAlign: TextAlign.center), actions: [ TextButton( onPressed: () => Navigator.of(context).pop(), child: Text('Close'), ), ], ), ); } Widget _buildTopHeader( BuildContext context, Cart cartData, Orders ordersData) { final productsData = Provider.of<Products>(context); return Padding( padding: EdgeInsets.all(8), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Text('Total', style: TextStyle(fontSize: 20)), Spacer(), Chip( label: Text( '\$${cartData.itemSummaryPrice.toStringAsFixed(2)}', style: TextStyle(color: Colors.white), ), backgroundColor: Theme.of(context).primaryColor, ), SizedBox(width: 10), Consumer<Orders>( builder: (_, orders, __) => TextButton( onPressed: (cartData.itemSummaryPrice <= 0 || orders.loadingState == true) ? null : () async { try { orders.setLoading(); String auth = Provider.of<Auth>(context, listen: false).token; String uid = Provider.of<Auth>(context, listen: false).userId; await ordersData.addOrder( cartData.itemsList, cartData.itemSummaryPrice); cartData.clearCart(); orders.resetLoading(); productsData.clearProductQuantity(); ScaffoldMessenger.of(context).showSnackBar( SnackBar( backgroundColor: DeepBlue.kToDark, content: Text( 'Order Placed Successfully πŸ›’', style: TextStyle(color: Colors.white), ), ), ); Navigator.of(context).pushNamed(OrdersScreen.routeName); } catch (error) { _showAlertDialog(context); } }, child: orders.loadingState == true ? Center(child: CircularProgressIndicator()) : Text( 'ORDER NOW', style: TextStyle( fontWeight: FontWeight.w800, color: Provider.of<Light>(context).themeDark ? Colors.deepOrange : DeepBlue.kToDark, ), ), ), ), ], ), ); } ListTile _buildTopListTile(BuildContext context, Cart cartData) { return ListTile( title: Text( 'Total', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 20, ), ), trailing: Row( mainAxisAlignment: MainAxisAlignment.end, mainAxisSize: MainAxisSize.min, children: <Widget>[ Container( padding: EdgeInsets.all(10), decoration: BoxDecoration( color: Theme.of(context).primaryColor, shape: BoxShape.rectangle, borderRadius: BorderRadius.circular(20), ), child: Text( '\$${cartData.itemSummaryPrice.toStringAsFixed(2)}', style: TextStyle(color: Colors.white), ), ), SizedBox(width: 5), TextButton( onPressed: () => {}, child: Text( 'ORDER NOW', style: TextStyle(fontWeight: FontWeight.w900), ), ), ], ), ); } }
0
mirrored_repositories/kryptonian-flutter-app/lib
mirrored_repositories/kryptonian-flutter-app/lib/screens/new_category_drawer.dart
import 'package:flutter/material.dart'; import 'package:flutter_complete_guide/pallete/deepBlue.dart'; import 'package:flutter_complete_guide/providers/categories.dart'; import 'package:flutter_complete_guide/providers/category.dart'; import 'package:flutter_complete_guide/providers/light.dart'; import 'package:flutter_complete_guide/screens/categories_screen.dart'; import 'package:provider/provider.dart'; class NewCategoryDrawer extends StatefulWidget { @override State<NewCategoryDrawer> createState() => _NewCategoryDrawerState(); } class _NewCategoryDrawerState extends State<NewCategoryDrawer> { final _titleController = TextEditingController(); final _imageUrlController = TextEditingController(); void _submitData() { final enteredTitle = _titleController.text; final enteredImageUrl = _imageUrlController.text; if (enteredTitle.isEmpty || enteredImageUrl.isEmpty) { print("Form Contents Empty!"); return; } //TODO: Call add category Firebase Provider.of<Categories>(context, listen: false).addCategory( Category( title: enteredTitle, imgUrl: enteredImageUrl, ), ); Navigator.of(context).pop(); ScaffoldMessenger.of(context).showSnackBar( SnackBar( backgroundColor: Colors.black, content: Text( 'Product Category Added Successfully 🏁', style: TextStyle(color: Colors.deepOrange, fontWeight: FontWeight.bold), ), ), ); print('${enteredTitle} | ${enteredImageUrl}'); } @override Widget build(BuildContext context) { return SingleChildScrollView( child: Card( elevation: 30, child: Container( padding: EdgeInsets.all(10.0), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.end, children: <Widget>[ TextField( decoration: InputDecoration( enabledBorder: UnderlineInputBorder( borderSide: BorderSide( color: Provider.of<Light>(context).themeDark ? Colors.white60 : Colors.black.withOpacity(0.5), ), ), focusedBorder: UnderlineInputBorder( borderSide: BorderSide( color: Provider.of<Light>(context).themeDark ? Colors.lightBlueAccent : DeepBlue.kToDark, ), ), border: UnderlineInputBorder( borderSide: BorderSide( color: Provider.of<Light>(context).themeDark ? Colors.lightBlueAccent : DeepBlue.kToDark, ), ), labelText: 'Category Title', labelStyle: TextStyle( color: Provider.of<Light>(context).themeDark ? Colors.white60 : Colors.black.withOpacity(0.55), ), ), controller: _titleController, textInputAction: TextInputAction.next, /*onChanged: (value) => titleInput = value,*/ ), TextField( decoration: InputDecoration( enabledBorder: UnderlineInputBorder( borderSide: BorderSide( color: Provider.of<Light>(context).themeDark ? Colors.white60 : Colors.black.withOpacity(0.5), ), ), focusedBorder: UnderlineInputBorder( borderSide: BorderSide( color: Provider.of<Light>(context).themeDark ? Colors.lightBlueAccent : DeepBlue.kToDark, ), ), border: UnderlineInputBorder( borderSide: BorderSide( color: Provider.of<Light>(context).themeDark ? Colors.lightBlueAccent : DeepBlue.kToDark, ), ), labelText: 'Image Url', labelStyle: TextStyle( color: Provider.of<Light>(context).themeDark ? Colors.white60 : Colors.black.withOpacity(0.55), ), ), controller: _imageUrlController, keyboardType: TextInputType.text, textInputAction: TextInputAction.next, /*onChanged: (value) => amountInput = value,*/ ), SizedBox(height: 20), RaisedButton( onPressed: () => _submitData(), color: Provider.of<Light>(context).themeDark ? Colors.blueAccent : DeepBlue.kToDark, child: Text( 'Add Category', style: TextStyle( color: Colors.white, ), ), ) ], ), ), ), ); } }
0
mirrored_repositories/kryptonian-flutter-app/lib
mirrored_repositories/kryptonian-flutter-app/lib/screens/products_overview_screen.dart
import 'dart:async'; import 'package:animated_theme_switcher/animated_theme_switcher.dart'; import 'package:flutter/material.dart'; import 'package:flutter_complete_guide/helpers/theme_config.dart'; import 'package:flutter_complete_guide/providers/auth.dart'; import 'package:flutter_complete_guide/providers/cart.dart'; import 'package:flutter_complete_guide/providers/light.dart'; import 'package:flutter_complete_guide/providers/products.dart'; import 'package:flutter_complete_guide/screens/cart_screen.dart'; import 'package:flutter_complete_guide/widgets/badge.dart'; import 'package:flutter_complete_guide/widgets/main_drawer.dart'; import 'package:flutter_complete_guide/widgets/products_grid.dart'; import 'package:provider/provider.dart'; enum FilterOptions { favorites, all, } class ProductsOverviewScreen extends StatefulWidget { static const routeName = '/product-overview'; @override State<ProductsOverviewScreen> createState() => _ProductsOverviewScreenState(); } class _ProductsOverviewScreenState extends State<ProductsOverviewScreen> { bool _showFavoriteOnly = false; var _isInit = true; var _isLoading = false; @override void initState() { // TODO: implement initState super.initState(); } @override void didChangeDependencies() async { // TODO: implement didChangeDependencies bool isAuth = Provider.of<Auth>(context, listen: false).isAuth; String uid = Provider.of<Auth>(context, listen: false).userId; if (_isInit == true) { setState(() { _isLoading = true; }); try { await Provider.of<Products>(context).fetchProduct(); } catch (error) { setState(() { _isLoading = false; }); print('PRODUCTS ERROR => $error'); showDialog( context: context, builder: (ctx) => AlertDialog( elevation: 10.4, contentPadding: EdgeInsets.all(30.0), title: Text('Attention', textAlign: TextAlign.center), content: Text( 'Something went wrong, ${error}', textAlign: TextAlign.center, ), actions: [ TextButton( onPressed: () => Navigator.of(ctx).pop(false), child: Text('Close'), ), ], ), ); } } setState(() { _isLoading = false; }); _isInit = false; super.didChangeDependencies(); } @override Widget build(BuildContext context) { print('BUILD => PRODUCT OVERVIEW SCREEN'); final lightData = Provider.of<Light>(context); final isDark = lightData.themeDark; final List data = ModalRoute.of(context).settings.arguments; String categoryId = data[0]; bool categoryFlag = data[1]; return ThemeSwitchingArea( child: Scaffold( appBar: AppBar( title: Text('Krypton'), actions: <Widget>[ PopupMenuButton( icon: Icon(Icons.more_vert), onSelected: (FilterOptions selectedValue) { setState(() { if (selectedValue == FilterOptions.favorites) { _showFavoriteOnly = true; } else { _showFavoriteOnly = false; } }); }, itemBuilder: (_) => [ PopupMenuItem( child: Text('Only Favorites'), value: FilterOptions.favorites, ), PopupMenuItem( child: Text('Show All'), value: FilterOptions.all, ), ], ), Consumer<Cart>( builder: (_, cartData, ch) => Badge( child: ch, value: cartData.itemCount.toString(), ), child: IconButton( icon: Icon(Icons.shopping_cart), onPressed: () => Navigator.of(context).pushNamed(CartScreen.routeName), ), ), ThemeSwitcher( clipper: ThemeSwitcherCircleClipper(), builder: (ctx) => IconButton( icon: Icon(isDark ? Icons.wb_sunny : Icons.nights_stay_sharp), color: isDark ? Colors.yellow : Colors.grey, onPressed: () { lightData.toggleLights(); Timer( Duration(milliseconds: 50), () => ThemeSwitcher.of(ctx) .changeTheme(theme: isDark ? dayTheme : nightTheme), ); }, ), ), ], ), body: _isLoading == true ? Center( child: CircularProgressIndicator(), ) : productsGrid( showFavoriteOnly: _showFavoriteOnly, categoryId: categoryId, categoryFlag: categoryFlag, ), //drawer: MainDrawer(), ), ); } }
0
mirrored_repositories/kryptonian-flutter-app/lib
mirrored_repositories/kryptonian-flutter-app/lib/screens/user_products_screen.dart
import 'package:flutter/material.dart'; import 'package:flutter_complete_guide/providers/auth.dart'; import 'package:flutter_complete_guide/providers/products.dart'; import 'package:flutter_complete_guide/screens/edit_product_screen.dart'; import 'package:flutter_complete_guide/widgets/user_product_item.dart'; import 'package:provider/provider.dart'; class UserProductsScreen extends StatelessWidget { static const routeName = '/user-products'; Future<void> _refreshProducts(BuildContext context) async { String auth = Provider.of<Auth>(context, listen: false).token; String uid = Provider.of<Auth>(context, listen: false).userId; await Provider.of<Products>(context, listen: false) .fetchProduct(true); /// FilterByUser => True. } @override Widget build(BuildContext context) { print('BUILD => MANAGE USER PRODUCTS'); final productsData = Provider.of<Products>(context, listen: false); return Scaffold( appBar: AppBar( title: Text("My Products"), actions: [ IconButton( onPressed: () { Navigator.of(context).pushNamed(EditProductScreen.routeName); }, icon: Icon(Icons.add), ), IconButton( onPressed: () async { String auth = Provider.of<Auth>(context, listen: false).token; String uid = Provider.of<Auth>(context, listen: false).userId; await productsData.fetchProduct(true); }, icon: Icon(Icons.refresh_sharp), ), ], ), body: FutureBuilder( future: _refreshProducts(context), builder: (ctx, snapshot) => snapshot.connectionState == ConnectionState.waiting ? Center(child: CircularProgressIndicator()) : RefreshIndicator( onRefresh: () => _refreshProducts(context), child: Consumer<Products>( builder: (context, productsData, _) => Padding( padding: EdgeInsets.all(8), child: ListView.builder( itemCount: productsData.item.length, itemBuilder: (_, index) { return Column( children: [ UserProductItem( index: index, productId: productsData.item[index].id, title: productsData.item[index].title, imageUrl: productsData.item[index].imageUrl, ), Divider(), ], ); }, ), ), ), ), ), //drawer: MainDrawer(), ); } }
0
mirrored_repositories/kryptonian-flutter-app/lib
mirrored_repositories/kryptonian-flutter-app/lib/screens/perspective_zoom_screen.dart
import 'dart:async'; import 'dart:math'; import 'package:flutter/material.dart'; import 'package:flutter_complete_guide/pallete/purplay.dart'; import 'package:sensors/sensors.dart'; class PerspectiveZoomScreen extends StatefulWidget { static const routeName = '/perspective'; @override _PerspectiveZoomScreenState createState() => _PerspectiveZoomScreenState(); } class _PerspectiveZoomScreenState extends State<PerspectiveZoomScreen> { AccelerometerEvent acceleration; StreamSubscription<AccelerometerEvent> _streamSubscription; double bgMotionSensitivity = 0.3; double cartMotionSensitivity = 0.6; @override void initState() { // TODO: implement initState _streamSubscription = accelerometerEvents.listen( (event) { acceleration = event; }, ); super.initState(); } @override void dispose() { // TODO: implement dispose _streamSubscription.cancel(); super.dispose(); } @override Widget build(BuildContext context) { final deviceSize = MediaQuery.of(context).size; return Scaffold( resizeToAvoidBottomInset: true, backgroundColor: Colors.black, body: Container( height: deviceSize.height, width: deviceSize.width, child: Center( child: Stack( children: [ Container( decoration: BoxDecoration( gradient: LinearGradient( colors: [ Color(0xff18203d).withOpacity(1), Color(0xff18203d).withOpacity(1), Colors.black.withOpacity(1), Color(0xff232c51), ], begin: Alignment.topLeft, end: Alignment.bottomRight, stops: [0, 0, 1, 1], ), ), ), _buildPositioned( padTop: deviceSize.height * 0.73, padBottom: deviceSize.height * 0.07, padRight: deviceSize.width * 0.00, padLeft: deviceSize.width * 0.000, ImageLoc: 'assets/images/asteroid-belt-1.png', imgWidth: 500, imgHeight: 180, ), _buildPositioned( padTop: deviceSize.height * 0.85, padBottom: deviceSize.height * 0.07, padRight: deviceSize.width * 0.50, padLeft: deviceSize.width * 0.000, ImageLoc: 'assets/images/asteroids-removebg-preview.png', imgWidth: 500, imgHeight: 180, ), _buildPositioned( padTop: deviceSize.height * 0.57, padBottom: deviceSize.height * 0.07, padRight: deviceSize.width * 0.00, padLeft: deviceSize.width * 0.000, ImageLoc: 'assets/images/asteroid-belt.png', imgWidth: 500, imgHeight: 180, ), _buildPositioned( padTop: deviceSize.height * 0.07, padBottom: deviceSize.height * 0.67, padRight: deviceSize.width * 0.00, padLeft: deviceSize.width * 0.000, ImageLoc: 'assets/images/asteroid-belt.png', imgWidth: 500, imgHeight: 180, ), ], ), ), ), ); } AnimatedPositioned _buildPositioned({ double padTop, double padBottom, double padRight, double padLeft, String ImageLoc, double imgWidth, double imgHeight, }) { return AnimatedPositioned( child: Align( child: Container( padding: EdgeInsets.only( top: padTop, bottom: padBottom, right: padRight, left: padLeft, ), child: Image.asset( ImageLoc, width: imgWidth, height: imgHeight, fit: BoxFit.cover, ), ), ), duration: Duration(milliseconds: 250), top: acceleration != null ? acceleration.z * cartMotionSensitivity : 0.0, bottom: acceleration != null ? acceleration.z * -cartMotionSensitivity : 0.0, right: acceleration != null ? acceleration.x * -cartMotionSensitivity : 0.0, left: acceleration != null ? acceleration.x * cartMotionSensitivity : 0.0, ); } }
0
mirrored_repositories/kryptonian-flutter-app/lib
mirrored_repositories/kryptonian-flutter-app/lib/screens/edit_product_screen.dart
import 'package:flutter/material.dart'; import 'package:flutter_complete_guide/pallete/deepBlue.dart'; import 'package:flutter_complete_guide/providers/auth.dart'; import 'package:flutter_complete_guide/providers/cart.dart'; import 'package:flutter_complete_guide/providers/categories.dart'; import 'package:flutter_complete_guide/providers/light.dart'; import 'package:flutter_complete_guide/providers/product.dart'; import 'package:flutter_complete_guide/providers/products.dart'; import 'package:flutter_complete_guide/screens/new_category_drawer.dart'; import 'package:provider/provider.dart'; import 'package:dropdown_formfield/dropdown_formfield.dart'; class EditProductScreen extends StatefulWidget { static const routeName = '/edit-product'; @override _EditProductScreenState createState() => _EditProductScreenState(); } class _EditProductScreenState extends State<EditProductScreen> { final _imageUrlController = TextEditingController(); final _priceFocusNode = FocusNode(); final _imageUrlFocusNode = FocusNode(); final _form = GlobalKey<FormState>(); String _selectCategory; var _editedProduct = Product( id: null, title: '', description: '', price: 0, imageUrl: '', qty: 0, categoryId: ''); var _isInit = true; var isLoading = false; var _initValues = { 'id': null, 'title': '', 'price': '', 'description': '', 'imageUrl': '', 'category': '', }; @override void initState() { // TODO: implement initState //_selectCategory = ''; //_imageUrlFocusNode.addListener(_updateImageUrl); super.initState(); } @override void didChangeDependencies() { // TODO: implement didChangeDependencies if (_isInit) { final String productId = ModalRoute.of(context).settings.arguments; final catData = Provider.of<Categories>(context, listen: false); if (productId != null) { _editedProduct = Provider.of<Products>(context, listen: false).findById(productId); _initValues = { 'id': _editedProduct.id, 'title': _editedProduct.title, 'price': _editedProduct.price.toString(), 'description': _editedProduct.description, 'imageUrl': '', 'category': catData.fetchCategoryTitle(_editedProduct.categoryId), }; /// When controller used in TextFormField initial value can't be set _imageUrlController.text = _editedProduct.imageUrl; } } _isInit = false; super.didChangeDependencies(); } @override void dispose() { // TODO: implement dispose _priceFocusNode.dispose(); _imageUrlFocusNode.dispose(); _imageUrlController.dispose(); super.dispose(); } void _showCategoryDrawer() { final deviceSize = MediaQuery.of(context).size; showModalBottomSheet( elevation: 10, //constraints: BoxConstraints(maxHeight: deviceSize.height * 0.3), context: context, isScrollControlled: true, builder: (_) { return GestureDetector( onTap: () => {}, behavior: HitTestBehavior.opaque, child: Padding( padding: EdgeInsets.only( bottom: MediaQuery.of(context).viewInsets.bottom), child: NewCategoryDrawer(), ), ); }, ); } Future<void> _saveForm(Products productsData) async { final isValid = _form.currentState.validate(); String auth = Provider.of<Auth>(context, listen: false).token; String uid = Provider.of<Auth>(context, listen: false).userId; print('Valid: $isValid'); if (!isValid) { return; } _form.currentState.save(); // Set Loading Indicator:- setState(() { isLoading = true; }); /// Save Contents to Products Provider:- if (_editedProduct.id == null) { try { await productsData.addProduct(_editedProduct); } catch (error) { await showDialog<Null>( context: context, builder: (context) => AlertDialog( elevation: 10.4, title: Text('Attention Schmuck', textAlign: TextAlign.center), content: Text('Something Went Wrong!', textAlign: TextAlign.center), actions: [ TextButton( onPressed: () => Navigator.of(context).pop(), child: Text('Close'), ), ], ), ); } finally { // Reset Loading Indicator:- setState(() { isLoading = false; }); /// Pop this screen:- Navigator.of(context).pop(); } } else { /// EDIT Existing Products:- //Provider.of<Cart>(context, listen: false).updateItems(_editedProduct.id, _editedProduct); Provider.of<Cart>(context, listen: false).deleteItems(_editedProduct.id); String auth = Provider.of<Auth>(context, listen: false).token; await productsData.updateProduct(_editedProduct.id, _editedProduct); // Reset Loading Indicator:- setState(() { isLoading = false; }); /// Pop this screen:- Navigator.of(context).pop(); } } @override Widget build(BuildContext context) { print('BUILD => EDIT PRODUCTS SCREEN'); final productsData = Provider.of<Products>(context, listen: true); final cartData = Provider.of<Cart>(context, listen: true); final catData = Provider.of<Categories>(context, listen: false); final deviceSize = MediaQuery.of(context).size; return Scaffold( appBar: AppBar( title: Text("Edit My Products"), actions: [ IconButton( onPressed: () { _saveForm(productsData); }, icon: Icon(Icons.save), ), ], ), floatingActionButton: FloatingActionButton( elevation: 20, backgroundColor: Provider.of<Light>(context).themeDark ? Colors.deepOrange : DeepBlue.kToDark, foregroundColor: Provider.of<Light>(context).themeDark ? Colors.black : Colors.white, child: Icon(Icons.add), onPressed: () => _showCategoryDrawer(), ), body: isLoading == true ? Center(child: CircularProgressIndicator()) : Container( height: deviceSize.height * 0.74, padding: const EdgeInsets.all(16.0), child: Card( elevation: 10.0, child: Padding( padding: const EdgeInsets.all(16.0), child: Form( key: _form, child: ListView( shrinkWrap: true, children: [ TextFormField( initialValue: _initValues['title'], autovalidateMode: AutovalidateMode.onUserInteraction, decoration: InputDecoration( labelText: 'Title', labelStyle: TextStyle( color: Provider.of<Light>(context).themeDark ? Colors.white60 : Colors.black.withOpacity(0.55), ), enabledBorder: UnderlineInputBorder( borderSide: BorderSide( color: Provider.of<Light>(context).themeDark ? Colors.white60 : Colors.black.withOpacity(0.5), ), ), focusedBorder: UnderlineInputBorder( borderSide: BorderSide( color: Provider.of<Light>(context).themeDark ? Colors.lightBlueAccent : DeepBlue.kToDark, ), ), border: UnderlineInputBorder( borderSide: BorderSide( color: Provider.of<Light>(context).themeDark ? Colors.lightBlueAccent : DeepBlue.kToDark, ), ), ), textInputAction: TextInputAction.next, onFieldSubmitted: (_) { FocusScope.of(context) .requestFocus(_priceFocusNode); }, validator: (value) { if (value.isEmpty) { return "This Field Value Is Schmuck"; } return null; }, onSaved: (value) { /// ADD NEW PRODUCT/ EDIT EXISTING PRODUCT _editedProduct = Product( id: _editedProduct.id, title: value, description: _editedProduct.description, price: _editedProduct.price, imageUrl: _editedProduct.imageUrl, isFavorite: _editedProduct.isFavorite, categoryId: _editedProduct.categoryId, ); }, ), TextFormField( initialValue: _initValues['price'], autovalidateMode: AutovalidateMode.onUserInteraction, decoration: InputDecoration( labelText: 'Price', labelStyle: TextStyle( color: Provider.of<Light>(context).themeDark ? Colors.white60 : Colors.black.withOpacity(0.55), ), enabledBorder: UnderlineInputBorder( borderSide: BorderSide( color: Provider.of<Light>(context).themeDark ? Colors.white60 : Colors.black.withOpacity(0.5), ), ), focusedBorder: UnderlineInputBorder( borderSide: BorderSide( color: Provider.of<Light>(context).themeDark ? Colors.lightBlueAccent : DeepBlue.kToDark, ), ), border: UnderlineInputBorder( borderSide: BorderSide( color: Provider.of<Light>(context).themeDark ? Colors.lightBlueAccent : DeepBlue.kToDark, ), ), ), textInputAction: TextInputAction.next, keyboardType: TextInputType.number, focusNode: _priceFocusNode, validator: (value) { if (value.isEmpty) { return 'Enter a Price Schmuck'; } if (double.tryParse(value) == null) { return 'Enter a valid number Schmuck'; } if (double.parse(value) <= 0) { return 'Enter a number greater than zero'; } return null; }, onSaved: (value) { _editedProduct = Product( id: _editedProduct.id, title: _editedProduct.title, description: _editedProduct.description, price: double.parse(value), imageUrl: _editedProduct.imageUrl, isFavorite: _editedProduct.isFavorite, categoryId: _editedProduct.categoryId, ); }, ), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.end, children: [ Container( margin: EdgeInsets.only(top: 25, right: 10), height: 100, width: 100, decoration: BoxDecoration( border: Border.all(width: 1, color: Colors.black), borderRadius: BorderRadius.circular(1), ), child: _imageUrlController.text.isEmpty ? Text('Enter a Url') : FittedBox( child: Image.network( _imageUrlController.text, fit: BoxFit.fill, ), ), ), Expanded( child: TextFormField( autovalidateMode: AutovalidateMode.onUserInteraction, decoration: InputDecoration( labelText: 'Image Url', labelStyle: TextStyle( color: Provider.of<Light>(context).themeDark ? Colors.white60 : Colors.black.withOpacity(0.55), ), enabledBorder: UnderlineInputBorder( borderSide: BorderSide( color: Provider.of<Light>(context).themeDark ? Colors.white60 : Colors.black.withOpacity(0.5), ), ), focusedBorder: UnderlineInputBorder( borderSide: BorderSide( color: Provider.of<Light>(context).themeDark ? Colors.lightBlueAccent : DeepBlue.kToDark, ), ), border: UnderlineInputBorder( borderSide: BorderSide( color: Provider.of<Light>(context).themeDark ? Colors.lightBlueAccent : DeepBlue.kToDark, ), ), ), keyboardType: TextInputType.url, controller: _imageUrlController, textInputAction: TextInputAction.done, onEditingComplete: () { setState(() {}); }, validator: (value) { if (value.isEmpty) { return 'Enter an image URL Schmuck'; } if (!value.startsWith('http') && !value.startsWith('https')) { return 'Enter a valid URL Schmuck'; } return null; }, onSaved: (value) { // TODO: ADD PRODUCT _editedProduct = Product( id: _editedProduct.id, title: _editedProduct.title, description: _editedProduct.description, price: _editedProduct.price, imageUrl: value, isFavorite: _editedProduct.isFavorite, categoryId: _editedProduct.categoryId, ); }, onFieldSubmitted: (_) { _saveForm(productsData); }, ), ), ], ), TextFormField( initialValue: _initValues['description'], autovalidateMode: AutovalidateMode.onUserInteraction, decoration: InputDecoration( labelText: 'Description', labelStyle: TextStyle( color: Provider.of<Light>(context).themeDark ? Colors.white60 : Colors.black.withOpacity(0.55), ), enabledBorder: UnderlineInputBorder( borderSide: BorderSide( color: Provider.of<Light>(context).themeDark ? Colors.white60 : Colors.black.withOpacity(0.5), ), ), focusedBorder: UnderlineInputBorder( borderSide: BorderSide( color: Provider.of<Light>(context).themeDark ? Colors.lightBlueAccent : DeepBlue.kToDark, ), ), border: UnderlineInputBorder( borderSide: BorderSide( color: Provider.of<Light>(context).themeDark ? Colors.lightBlueAccent : DeepBlue.kToDark, ), ), ), maxLines: 3, keyboardType: TextInputType.multiline, onSaved: (value) { _editedProduct = Product( id: _editedProduct.id, title: _editedProduct.title, description: value, price: _editedProduct.price, imageUrl: _editedProduct.imageUrl, isFavorite: _editedProduct.isFavorite, categoryId: _editedProduct.categoryId, ); }, validator: (value) { if (value.isEmpty) { return 'Enter a Description Schmuck'; } if (value.length < 10) { return 'Should be at least 10 chars along Schmuck'; } return null; }, ), SizedBox(height: 10), DropDownFormField( titleText: 'Product Category', hintText: 'Choose a category', value: _selectCategory, onSaved: (newValue) { setState(() { _selectCategory = newValue; }); _editedProduct = Product( id: _editedProduct.id, title: _editedProduct.title, description: _editedProduct.description, price: _editedProduct.price, imageUrl: _editedProduct.imageUrl, isFavorite: _editedProduct.isFavorite, categoryId: _selectCategory, ); }, onChanged: (newValue) { setState(() { _selectCategory = newValue; }); }, dataSource: catData.categoryDropDownItems, textField: 'display', valueField: 'value', ), SizedBox(height: 10), TextFormField( initialValue: _initValues['category'], autovalidateMode: AutovalidateMode.onUserInteraction, decoration: InputDecoration( labelText: 'Selected Product Category', labelStyle: TextStyle( color: Provider.of<Light>(context).themeDark ? Colors.white60 : Colors.black.withOpacity(0.55), ), enabledBorder: UnderlineInputBorder( borderSide: BorderSide( color: Provider.of<Light>(context).themeDark ? Colors.white60 : Colors.black.withOpacity(0.5), ), ), focusedBorder: UnderlineInputBorder( borderSide: BorderSide( color: Provider.of<Light>(context).themeDark ? Colors.lightBlueAccent : DeepBlue.kToDark, ), ), border: UnderlineInputBorder( borderSide: BorderSide( color: Provider.of<Light>(context).themeDark ? Colors.lightBlueAccent : DeepBlue.kToDark, ), ), ), keyboardType: TextInputType.text, ), ], ), ), ), ), ), ); } }
0
mirrored_repositories/kryptonian-flutter-app/lib
mirrored_repositories/kryptonian-flutter-app/lib/screens/my_splash_screen.dart
import 'package:flutter/material.dart'; class MySplashScreen extends StatefulWidget { @override State<MySplashScreen> createState() => _MySplashScreenState(); } class _MySplashScreenState extends State<MySplashScreen> { @override Widget build(BuildContext context) { final deviceSize = MediaQuery.of(context).size; return Scaffold( backgroundColor: Colors.black38, body: Align( child: Container( padding: EdgeInsets.only( top: deviceSize.height * 0.2, bottom: deviceSize.height * 0.0, right: deviceSize.height * 0.0, left: deviceSize.height * 0.0, ), child: Image.asset( 'assets/images/asteroid-belt.png', width: 500, height: 180, fit: BoxFit.cover, ), ), ), ); } }
0
mirrored_repositories/kryptonian-flutter-app/lib
mirrored_repositories/kryptonian-flutter-app/lib/screens/liquid_app_switch_screen.dart
import 'package:animated_theme_switcher/animated_theme_switcher.dart'; import 'package:flutter/material.dart'; import 'package:flutter_complete_guide/providers/auth.dart'; import 'package:flutter_complete_guide/providers/light.dart'; import 'package:flutter_complete_guide/providers/users.dart'; import 'package:flutter_complete_guide/screens/cart_screen.dart'; import 'package:flutter_complete_guide/screens/categories_screen.dart'; import 'package:flutter_complete_guide/screens/orders_screen.dart'; import 'package:flutter_complete_guide/widgets/circular_menu.dart'; import 'package:liquid_swipe/liquid_swipe.dart'; import 'package:provider/provider.dart'; import 'package:eva_icons_flutter/eva_icons_flutter.dart'; class LiquidAppSwitchScreen extends StatefulWidget { static const routeName = '/liquid-app-switch'; @override _LiquidAppSwitchScreenState createState() => _LiquidAppSwitchScreenState(); } class _LiquidAppSwitchScreenState extends State<LiquidAppSwitchScreen> { var _isInit = true; final forwardPages = [ Container(child: CategoriesScreen()), Container(child: CartScreen()), Container(child: OrdersScreen()), ]; @override void didChangeDependencies() async { // TODO: implement didChangeDependencies if (_isInit) { String auth = Provider.of<Auth>(context, listen: false).token; String uid = Provider.of<Auth>(context, listen: false).userId; final List args = ModalRoute.of(context).settings.arguments ?? []; String _email = args.length != 0 ? args[0] : ''; bool _isSeller = args.length != 0 ? args[1] : false; print('EMAIL | Seller | uid => $_email | $_isSeller | $uid'); await Provider.of<Users>(context, listen: false) .addUser(_email, _isSeller); } _isInit = false; super.didChangeDependencies(); } @override Widget build(BuildContext context) { final lightData = Provider.of<Light>(context, listen: false); final isDark = lightData.themeDark; return ThemeSwitchingArea( child: Scaffold( floatingActionButton: CircularMenu(), body: LiquidSwipe( pages: forwardPages, enableLoop: true, fullTransitionValue: 300, enableSlideIcon: true, waveType: WaveType.liquidReveal, positionSlideIcon: 0.5, slideIconWidget: Icon( EvaIcons.chevronLeft, color: isDark ? Colors.deepOrange : Colors.red, size: 40, ), ), ), ); } }
0
mirrored_repositories/kryptonian-flutter-app/lib
mirrored_repositories/kryptonian-flutter-app/lib/screens/categories_screen.dart
import 'dart:async'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_complete_guide/providers/auth.dart'; import 'package:flutter_complete_guide/providers/categories.dart'; import 'package:flutter_complete_guide/providers/light.dart'; import 'package:flutter_complete_guide/providers/users.dart'; import 'package:flutter_complete_guide/widgets/category_item.dart'; import 'package:flutter_complete_guide/widgets/circular_menu.dart'; import 'package:flutter_complete_guide/widgets/main_drawer.dart'; import 'package:provider/provider.dart'; class CategoriesScreen extends StatefulWidget { static const routeName = '/categories'; @override State<CategoriesScreen> createState() => _CategoriesScreenState(); } class _CategoriesScreenState extends State<CategoriesScreen> { var _isInit = true; var _isLoading = false; @override void dispose() { // TODO: implement dispose _isInit = false; _isLoading = false; super.dispose(); } @override void initState() { // TODO: implement initState print('INIT_STATE => CATEGORIES-SCREEN'); super.initState(); WidgetsBinding.instance.addPostFrameCallback( (timeStamp) { String auth = Provider.of<Auth>(context, listen: false).token; String uid = Provider.of<Auth>(context, listen: false).userId; final List args = ModalRoute.of(context).settings.arguments ?? []; String _email = args.length != 0 ? args[0] : ''; bool _isSeller = args.length != 0 ? args[1] : false; print('EMAIL | Seller | uid => $_email | $_isSeller | $uid'); /// 1.ADD USERS: IF NOT ADDED ALREADY:- Provider.of<Users>(context, listen: false).addUser(_email, _isSeller); }, ); } @override void didChangeDependencies() async { // TODO: implement didChangeDependencies if (_isInit == true) { print('IS_INIT => CATEGORIES-SCREEN'); setState(() { _isLoading = true; }); /// FETCH ALL CATEGORIES:- /// 1.FETCH ALL USERS:- try { Provider.of<Users>(context).fetchUsers().then((_) => Provider.of<Categories>(context, listen: false).fetchCategories()); } catch (error) { Provider.of<Categories>(context, listen: false).fetchCategories(); setState(() { _isLoading = false; }); } } _isInit = false; setState(() { _isLoading = false; }); super.didChangeDependencies(); } Future<void> _refreshCategories(BuildContext context) async { await Provider.of<Categories>(context).fetchCategories(); } @override Widget build(BuildContext context) { print('BUILD => CATEGORIES SCREEN'); //final categoriesData = Provider.of<Categories>(context, listen: false).categories; return Scaffold( drawer: MainDrawer(), floatingActionButton: CircularMenu(), appBar: AppBar( title: Text('Product Categories'), actions: <Widget>[], ), body: _isLoading == true ? Center( child: CircularProgressIndicator(), ) : RefreshIndicator( onRefresh: () => _refreshCategories(context), child: Consumer<Categories>( builder: (context, categoriesData, _) => categoriesData.categories.length == 0 ? _buildEmptyContent(context) : GridView( padding: EdgeInsets.all(10), children: categoriesData.categories .map( (category) => CategoryItem( id: category.id, title: category.title, imgUrl: category.imgUrl, ), ) .toList(), gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent( maxCrossAxisExtent: 200, childAspectRatio: 3 / 2, /// height / width ratio bit taller than wide crossAxisSpacing: 5, /// Spacing b/w the columns mainAxisSpacing: 5, /// Spacing b/w Rows ), ), ), ), ); } Widget _buildEmptyContent(BuildContext context) { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( 'Nothing here 🎧', style: TextStyle( fontSize: 32, color: Provider.of<Light>(context).themeDark ? Colors.white60 : Colors.black54), ), SizedBox(height: 3), Text( 'Add Product Category to get started!', style: TextStyle( fontSize: 16, color: Provider.of<Light>(context).themeDark ? Colors.white60 : Colors.black54), ) ], ), ); } }
0
mirrored_repositories/kryptonian-flutter-app/lib
mirrored_repositories/kryptonian-flutter-app/lib/screens/product_details_screen.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_complete_guide/pallete/deepBlue.dart'; import 'package:flutter_complete_guide/providers/cart.dart'; import 'package:flutter_complete_guide/providers/product.dart'; import 'package:flutter_complete_guide/providers/products.dart'; import 'package:provider/provider.dart'; import 'package:stepper_touch/stepper_touch.dart'; class ProductDetailsScreen extends StatefulWidget { static const routeName = '/product-details'; @override State<ProductDetailsScreen> createState() => _ProductDetailsScreenState(); } class _ProductDetailsScreenState extends State<ProductDetailsScreen> { ScrollController _scrollController; bool lastStatus = true; void _scrollListener() { if (isShrink != lastStatus) { setState(() { lastStatus = isShrink; }); } } bool get isShrink { return (_scrollController.hasClients) && (_scrollController.offset > (295 - kToolbarHeight)); } @override void initState() { // TODO: implement initState _scrollController = ScrollController(); _scrollController.addListener(_scrollListener); super.initState(); } @override void dispose() { // TODO: implement dispose _scrollController.removeListener(_scrollListener); super.dispose(); } @override Widget build(BuildContext context) { final _deviceSize = MediaQuery.of(context).size; final List productId_index = ModalRoute.of(context).settings.arguments; final String productId = productId_index[0]; final int index = productId_index[1]; print("@ProductDetailsScreen => (productId, index): ${productId},${index}"); /// Provider Data:- final loadedProduct = Provider.of<Products>(context, listen: false).findById(productId); final products = Provider.of<Products>(context, listen: false); final cartData = Provider.of<Cart>(context, listen: true); void _productIncreaseQty( Products products, Product productData, Cart cartData) { products.addProductQuantity(productData.id, index); cartData.addItems(productData.id, productData.title, productData.price); print('CALL => CartUpdateHandler, Increase Qty'); } void _productReduceQty( Products products, Product productData, Cart cartData) { products.decreaseProductQuantity(productData.id, index); cartData.reduceItems(productData.id); print('CALL => CartUpdateHandler, Decrease Qty'); } return Scaffold( // appBar: AppBar( // title: Text(loadedProduct.title), // ), body: CustomScrollView( controller: _scrollController, slivers: [ SliverAppBar( centerTitle: true, expandedHeight: 300, pinned: true, flexibleSpace: FlexibleSpaceBar( title: Container( decoration: BoxDecoration( color: isShrink ? AppBarTheme.of(context).backgroundColor : Colors.black54, borderRadius: BorderRadius.circular(12)), width: _deviceSize.width, padding: isShrink ? EdgeInsets.all(0) : EdgeInsets.all(5), child: Text(loadedProduct.title, textAlign: TextAlign.justify), ), background: Hero( tag: loadedProduct.id, child: _buildImageContent(loadedProduct), ), ), ), SliverList( delegate: SliverChildListDelegate( [ SizedBox(height: 10), Card( color: DeepBlue.kToDark, shadowColor: Colors.black, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(13)), margin: EdgeInsets.all(10), elevation: 20.0, child: Container( padding: EdgeInsets.all(20), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Icon(Icons.monetization_on_outlined, size: 30, color: Colors.white), Container( margin: EdgeInsets.only(right: _deviceSize.width * 0.12), child: Text( 'Product Price', textAlign: TextAlign.left, style: TextStyle( fontSize: 20, fontWeight: FontWeight.bold, color: Colors.white60), ), ), Text( '\$${loadedProduct.price}', style: TextStyle(color: Colors.grey, fontSize: 20), ), ], ), ), ), Card( color: DeepBlue.kToDark, shadowColor: Colors.black, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(13), ), margin: EdgeInsets.all(10), elevation: 20.0, child: Container( padding: EdgeInsets.all(0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, mainAxisSize: MainAxisSize.min, children: [ Icon(Icons.add_shopping_cart_outlined, size: 30, color: Colors.white), Container( margin: EdgeInsets.only(right: _deviceSize.width * 0.06), child: Text( 'Modify Cart', textAlign: TextAlign.left, style: TextStyle( fontSize: 20, fontWeight: FontWeight.bold, color: Colors.white60), ), ), Flexible( flex: 1, fit: FlexFit.loose, child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(66), color: Colors.white.withOpacity(0.15), ), constraints: BoxConstraints( maxWidth: 38, maxHeight: 85, ), margin: EdgeInsets.only(top: 10, bottom: 10), child: Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ Container( height: 20, child: IconButton( onPressed: () => _productIncreaseQty( products, loadedProduct, cartData), icon: Icon( Icons.add, color: Colors.white, size: 14, ), ), ), SizedBox(height: 8), Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(18), color: Colors.white, ), constraints: BoxConstraints( minWidth: 38, minHeight: 38, ), child: Padding( padding: const EdgeInsets.all(8.0), child: Consumer<Products>( builder: (_, products, __) => Text( cartData .getItemQuantity(products .item[products .getIndexByProductId( loadedProduct.id)] .id) .toString(), textAlign: TextAlign.center, style: TextStyle( fontSize: 14, color: Colors.blueAccent), ), ), ), ), Container( height: 19, child: IconButton( onPressed: () => _productReduceQty( products, loadedProduct, cartData), icon: Icon( Icons.remove, color: Colors.white, size: 14, ), ), ) ], ), ), ), ], ), ), ), SizedBox(height: 10), Row( mainAxisAlignment: MainAxisAlignment.start, children: [ Card( margin: EdgeInsets.all(15), child: Container( width: _deviceSize.width * 0.86, margin: EdgeInsets.only( right: 1, left: 14, top: 12, bottom: 12), child: Text( 'Description', textAlign: TextAlign.left, style: TextStyle( fontSize: 30, fontWeight: FontWeight.bold, ), ), ), ), ], ), SizedBox(height: 20), Container( padding: EdgeInsets.symmetric(horizontal: 10), margin: EdgeInsets.symmetric(horizontal: 10), width: double.infinity, child: Text( loadedProduct.description, textAlign: TextAlign.justify, softWrap: true, ), ), SizedBox(height: 800), ], ), ), ], ), ); } Image _buildImageContent(Product productData) { return Image.network( productData.imageUrl, errorBuilder: (context, error, stackTrace) => Image.asset('assets/images/placeholder.png'), fit: BoxFit.cover, ); } }
0
mirrored_repositories/kryptonian-flutter-app/lib
mirrored_repositories/kryptonian-flutter-app/lib/screens/orders_screen.dart
import 'package:flutter/material.dart'; import 'package:flutter_complete_guide/providers/auth.dart'; import 'package:flutter_complete_guide/providers/light.dart'; import 'package:flutter_complete_guide/providers/orders.dart'; import 'package:flutter_complete_guide/widgets/main_drawer.dart'; import 'package:flutter_complete_guide/widgets/orders_item.dart'; import 'package:provider/provider.dart'; class OrdersScreen extends StatefulWidget { static const routeName = '/orders'; @override State<OrdersScreen> createState() => _OrdersScreenState(); } class _OrdersScreenState extends State<OrdersScreen> { @override void initState() { // TODO: implement initState Future.delayed(Duration.zero).then( (_) { String auth = Provider.of<Auth>(context, listen: false).token; String uid = Provider.of<Auth>(context, listen: false).userId; Provider.of<Orders>(context, listen: false).fetchAllOrders(); }, ); super.initState(); } @override Widget build(BuildContext context) { print('BUILD => ORDERS SCREEN'); final ordersData = Provider.of<Orders>(context); return Scaffold( appBar: AppBar( title: Text('My Orders'), ), body: RefreshIndicator( onRefresh: () { String auth = Provider.of<Auth>(context, listen: false).token; String uid = Provider.of<Auth>(context, listen: false).userId; return ordersData.fetchAllOrders(); }, child: ordersData.orders.length == 0 ? _buildEmptyContent() : ListView.builder( itemCount: ordersData.orders.length, itemBuilder: (context, index) => OrdersItem( id: ordersData.orders[index].id, amount: ordersData.orders[index].amount, dateTime: ordersData.orders[index].dateTime, products: ordersData.orders[index].products, ), ), ), //drawer: MainDrawer(), ); } Widget _buildEmptyContent() { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( 'Nothing here 🎧', style: TextStyle( fontSize: 32, color: Provider.of<Light>(context).themeDark ? Colors.white60 : Colors.black54), ), SizedBox(height: 3), Text( 'Place an Order to get started!', style: TextStyle( fontSize: 16, color: Provider.of<Light>(context).themeDark ? Colors.white60 : Colors.black54), ) ], ), ); } }
0
mirrored_repositories/kryptonian-flutter-app/lib
mirrored_repositories/kryptonian-flutter-app/lib/screens/auth_screen.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_complete_guide/models/http_exception.dart'; import 'package:flutter_complete_guide/providers/auth.dart'; import 'package:flutter_complete_guide/screens/categories_screen.dart'; import 'package:flutter_complete_guide/screens/perspective_zoom_screen.dart'; import 'package:flutter_complete_guide/widgets/social_sign_in_button.dart'; import 'package:provider/provider.dart'; import 'package:email_validator/email_validator.dart'; enum AuthMode { Login, SignUp } class AuthScreen extends StatelessWidget { static const routeName = '/auth'; @override Widget build(BuildContext context) { final deviceSize = MediaQuery.of(context).size; return Scaffold( resizeToAvoidBottomInset: true, body: Stack( children: [ PerspectiveZoomScreen(), SingleChildScrollView( child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Container( margin: EdgeInsets.only( right: deviceSize.width * 0.05, top: deviceSize.height * 0.045, left: deviceSize.width * 0.05, bottom: deviceSize.height * 0.0, ), child: Image.asset( 'assets/images/shopping_1.png', width: 90, height: 90, fit: BoxFit.cover, ), ), AuthCard(), ], ), ) ], ), ); } } class AuthCard extends StatefulWidget { @override _AuthCardState createState() => _AuthCardState(); } class _AuthCardState extends State<AuthCard> with SingleTickerProviderStateMixin { final _form = GlobalKey<FormState>(); AuthMode _authMode = AuthMode.Login; Map<String, dynamic> _authData = { 'email': '', 'password': '', }; var _isLoading = false; final _passwordController = TextEditingController(); double _passStrength = 0.0; String _password; String _passStrengthId; String _displayText = '* Password Strength: '; RegExp numReg = RegExp(r".*[0-9].*"); RegExp letterReg = RegExp(r".*[A-Za-z].*"); /// Animation Controller & Animations:- AnimationController _animationController; Animation<Size> _heightAnimation; Animation<double> _opacityAnimation; /// Obscure Password:- bool _passwordObscure = true; /// Seller Info: bool _isSeller = false; /// Control Button views:- bool _emailClick = false; bool _googleClick = false; @override void initState() { // TODO: implement initState super.initState(); } @override void didChangeDependencies() { // TODO: implement didChangeDependencies super.didChangeDependencies(); final deviceSize = MediaQuery.of(context).size; /// Animation Controller and Animations:- _animationController = AnimationController(vsync: this, duration: Duration(milliseconds: 500)); _heightAnimation = Tween<Size>( begin: Size(double.infinity, deviceSize.height * 0.67), end: Size(double.infinity, deviceSize.height * 0.72), ).animate(CurvedAnimation( parent: _animationController, curve: Curves.elasticInOut, )); _opacityAnimation = Tween<double>(begin: 0.0, end: 1.0).animate( CurvedAnimation(parent: _animationController, curve: Curves.decelerate), ); } @override void dispose() { // TODO: implement dispose _animationController.dispose(); _passwordController.dispose(); super.dispose(); } void _checkPassword(String value) { _password = value.trim(); if (_password.isEmpty) { setState(() { _passStrength = 0; _passStrengthId = 'Empty'; _displayText = '* Password Strength: $_passStrengthId'; }); } else if (_password.length < 6) { setState(() { _passStrength = 1 / 4; _passStrengthId = 'Weak'; _displayText = '* Password Strength: $_passStrengthId'; }); } else if (_password.length < 8) { setState(() { _passStrength = 2 / 4; _passStrengthId = 'Medium'; _displayText = '* Password Strength: $_passStrengthId'; }); } else { if (!letterReg.hasMatch(_password) || !numReg.hasMatch(_password)) { setState(() { // Password length >= 8 // But doesn't contain both letter and digit characters _passStrength = 3 / 4; _passStrengthId = 'Strong'; _displayText = '* Password Strength: $_passStrengthId'; }); } else { // Password length >= 8 // Password contains both letter and digit characters setState(() { _passStrength = 1; _passStrengthId = 'Great'; _displayText = '* Password Strength: $_passStrengthId'; }); } } } void _showErrorDialog(String message) { print('Inside ShowAlertDialog'); showDialog<Null>( context: context, builder: (ctx) { return AlertDialog( title: Text('An Error has Occurred', textAlign: TextAlign.center), content: Padding( padding: const EdgeInsets.all(14.0), child: Text('$message', textAlign: TextAlign.center), ), actions: [ TextButton( onPressed: () => Navigator.of(ctx).pop(), child: Text('Close'), ) ], ); }, ); } Future<void> _submit() async { if (!_form.currentState.validate()) { return; } _form.currentState.save(); setState(() { _isLoading = true; }); try { if (_authMode == AuthMode.Login) { // TODO: Log User In await Provider.of<Auth>(context, listen: false) .login( _authData['email'], _authData['password'], 'signInWithPassword', _emailClick) .then( (_) { setState(() { _emailClick = false; _googleClick = false; }); Navigator.of(context).popAndPushNamed(CategoriesScreen.routeName); }, ); } else { // TODO: Sign Up User await Provider.of<Auth>(context, listen: false) .signup(_authData['email'], _authData['password'], 'signUp', _emailClick) .then( (_) { setState(() { _emailClick = false; _googleClick = false; }); Navigator.of(context).pushNamed(CategoriesScreen.routeName, arguments: [_authData['email'], _isSeller]); }, ); } } on HttpException catch (error) { var errorMessage = 'Authentication Failed!'; if (error.toString().contains('EMAIL_EXISTS')) { errorMessage = 'This Email is already in use!'; } else if (error.toString().contains('EMAIL_NOT_FOUND')) { errorMessage = 'Cannot find this Email. Signup or Try later!'; } else if (error.toString().contains('INVALID_PASSWORD')) { errorMessage = 'Password Invalid. Try Again!'; } else if (error.toString().contains('WEAK_PASSWORD')) { errorMessage = 'Password is too weak!'; } else if (error.toString().contains('INVALID_EMAIL')) { errorMessage = 'This is not a valid Email!'; } _showErrorDialog(errorMessage); } catch (error) { const errorMessage = 'Authentication Failed. Try again Later!'; _showErrorDialog(errorMessage); } setState(() { _isLoading = false; }); } void _toggleAuthMode() { if (_authMode == AuthMode.Login) { setState(() { _authMode = AuthMode.SignUp; }); _animationController.forward(); } else { setState(() { _authMode = AuthMode.Login; }); _animationController.reverse(); } } void _emailClickHandler() { setState(() { _emailClick = true; }); } void _googleClickHandler() { setState(() { _googleClick = true; }); } @override Widget build(BuildContext context) { print('BUILD => AUTH SCREEN'); final deviceSize = MediaQuery.of(context).size; return Container( width: deviceSize.width, //padding: const EdgeInsets.all(16.0), margin: !_emailClick ? EdgeInsets.only(top: deviceSize.height * 0.15) : EdgeInsets.only(top: deviceSize.height * 0), child: Column( children: <Widget>[ AnimatedSwitcher( duration: Duration(milliseconds: 300), switchOutCurve: Curves.easeOut, transitionBuilder: (child, animation) => ScaleTransition( scale: animation, child: child, ), child: !_emailClick ? _buildSignInContent(deviceSize) : _buildEmailSignInCard(deviceSize), ), ], ), ); } Widget _buildSignInContent(Size deviceSize) { return Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ Text( 'Sign In', textAlign: TextAlign.center, style: TextStyle( fontSize: 30, color: Colors.white60, ), ), SizedBox(height: deviceSize.height * 0.1), SocialSignInButton( assetName: 'assets/images/red-mail-logo.png', text: 'Warp with Email', backgroundColor: Colors.black, textColor: Colors.white, onPressed: () => _emailClickHandler(), ), SizedBox(height: 8.0), Text( 'or', textAlign: TextAlign.center, style: TextStyle( fontSize: 14, color: Colors.deepOrangeAccent, ), ), SizedBox(height: 8.0), SocialSignInButton( assetName: 'assets/images/google-logo.png', text: 'Warp with Google', backgroundColor: Colors.black, textColor: Colors.white, onPressed: () async { await Provider.of<Auth>(context, listen: false).signInWithGoogle(); await Provider.of<Auth>(context, listen: false).login('', '', '', _emailClick); print( 'Google-USER => ${Provider.of<Auth>(context, listen: false).currentGoogleUser.uid}'); print( 'Google-USER => ${Provider.of<Auth>(context, listen: false).currentGoogleUser.email}'); setState(() { _emailClick = false; _googleClick = false; }); Navigator.of(context) .popAndPushNamed(CategoriesScreen.routeName, arguments: [ '', false, ]); }, ), ], ); } Widget _buildGoogleSignIn(Size deviceSize) { return Card( elevation: 400, shadowColor: Colors.deepPurpleAccent, borderOnForeground: true, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(30), ), color: Color(0x192841).withOpacity(0.4), margin: EdgeInsets.only( right: deviceSize.width * 0.05, top: deviceSize.height * 0.04, left: deviceSize.width * 0.05, ), child: Padding( padding: const EdgeInsets.all(24.0), child: ElevatedButton( onPressed: () => {}, child: Text('Google', style: TextStyle(color: Colors.white)), ), ), ); } Widget _buildEmailSignInCard(Size deviceSize) { return SingleChildScrollView( child: Card( elevation: 400, shadowColor: Colors.deepPurpleAccent, borderOnForeground: true, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(30), ), color: Color(0x192841).withOpacity(0.4), margin: EdgeInsets.only( right: deviceSize.width * 0.05, top: deviceSize.height * 0.03, left: deviceSize.width * 0.05, ), child: AnimatedContainer( duration: Duration(milliseconds: 500), curve: Curves.decelerate, height: _authMode == AuthMode.SignUp ? deviceSize.height * 0.73 : deviceSize.height * 0.56, constraints: BoxConstraints( minHeight: _authMode == AuthMode.SignUp ? deviceSize.height * 0.73 : deviceSize.height * 0.56), width: deviceSize.width * 0.95, padding: EdgeInsets.all(20), child: _buildEmailForm(deviceSize), ), ), ); } Widget _buildEmailForm(Size deviceSize) { return Form( key: _form, child: SingleChildScrollView( child: Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ Flexible( child: Container( width: deviceSize.width, padding: EdgeInsets.only(left: 0.1), child: Text( _authMode == AuthMode.Login ? 'Login' : 'New User', textAlign: TextAlign.left, style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 30, ), ), ), ), IconButton( onPressed: () { setState(() { _emailClick = false; }); }, icon: Icon( Icons.exit_to_app_sharp, color: Colors.deepOrangeAccent, ), ), ], ), SizedBox(height: 20), Container( width: deviceSize.width, margin: EdgeInsets.only( right: deviceSize.width * 0, top: deviceSize.height * 0.0, left: deviceSize.width * 0.005, bottom: deviceSize.height * 0.03, ), child: Text( _authMode == AuthMode.Login ? 'Please SignIn to continue' : 'Please create an account', style: TextStyle( color: Colors.grey, fontWeight: FontWeight.bold, ), ), ), TextFormField( style: TextStyle(color: Colors.white), decoration: InputDecoration( labelText: 'Enter Email', focusColor: Colors.white, fillColor: Colors.white, icon: Icon(Icons.email_outlined, color: Colors.cyan), labelStyle: TextStyle(color: Colors.white30), hintStyle: TextStyle(color: Colors.white, fontWeight: FontWeight.w700), errorStyle: TextStyle(color: Colors.red, fontWeight: FontWeight.bold), ), autovalidateMode: AutovalidateMode.onUserInteraction, validator: (value) { if (value.isEmpty) { return 'Email is empty schmuck!'; } else if (EmailValidator.validate(value) == false) { return 'Email is invalid schmuck!'; } else { return null; } }, onSaved: (value) => _authData['email'] = value, ), TextFormField( controller: _passwordController, style: TextStyle(color: Colors.white), decoration: InputDecoration( labelText: 'Enter Password', icon: Icon(Icons.lock_outlined, color: Colors.cyan), suffixIcon: IconButton( onPressed: () => { setState(() { _passwordObscure = !_passwordObscure; }), }, icon: Icon( _passwordObscure ? Icons.remove_red_eye_outlined : Icons.remove_red_eye, color: Colors.blueGrey, ), ), labelStyle: TextStyle(color: Colors.white30), helperStyle: TextStyle(color: Colors.white30), hintStyle: TextStyle(color: Colors.white, fontWeight: FontWeight.w700), errorStyle: TextStyle( color: Colors.red, fontWeight: FontWeight.bold, ), ), autovalidateMode: AutovalidateMode.onUserInteraction, obscureText: _passwordObscure, onChanged: (value) => _checkPassword(value), onSaved: (value) => _authData['password'] = value, ), AnimatedContainer( constraints: BoxConstraints( minHeight: _authMode == AuthMode.SignUp ? 60 : 0, maxHeight: _authMode == AuthMode.SignUp ? 120 : 0, ), duration: Duration(milliseconds: 500), curve: Curves.easeIn, child: FadeTransition( opacity: _opacityAnimation, child: TextFormField( style: TextStyle(color: Colors.white), decoration: InputDecoration( labelText: 'Confirm Password', suffixIcon: IconButton( onPressed: () => { setState(() { _passwordObscure = !_passwordObscure; }), }, icon: Icon( _passwordObscure ? Icons.remove_red_eye_outlined : Icons.remove_red_eye, color: Colors.blueGrey, ), ), icon: Icon(Icons.lock_outlined, color: Colors.cyan), labelStyle: TextStyle(color: Colors.white30), hintStyle: TextStyle( color: Colors.white, fontWeight: FontWeight.w700), errorStyle: TextStyle( color: Colors.red, fontWeight: FontWeight.bold, ), ), autovalidateMode: AutovalidateMode.onUserInteraction, obscureText: _passwordObscure, validator: _authMode == AuthMode.SignUp ? (value) { if (value != _passwordController.text) { return 'Passwords do not match schmuck!'; } return null; } : null, ), ), ), SizedBox(height: 8.5), _authMode == AuthMode.SignUp ? Container( width: deviceSize.width, padding: EdgeInsets.only( top: deviceSize.height * 0, right: deviceSize.width * 0.19, left: deviceSize.width * 0.1, bottom: deviceSize.height * 0.01, ), child: Text(_displayText, style: TextStyle(color: Colors.white30, fontSize: 12)), ) : Container(), _authMode == AuthMode.SignUp ? Container( width: deviceSize.width * 0.56, child: LinearProgressIndicator( minHeight: 1, value: _passStrength, color: _passStrength <= 1 / 4 ? Colors.red : _passStrength == 2 / 4 ? Colors.yellow : _passStrength == 3 / 4 ? Colors.blue : Colors.green, backgroundColor: Colors.blueGrey, ), ) : Container(), _authMode == AuthMode.SignUp ? _buildPasswordHelper(context, deviceSize) : Container(), SizedBox(height: 14), _authMode == AuthMode.SignUp ? Center( child: Container( width: deviceSize.width, child: Row( children: [ IconButton( onPressed: () { setState(() { _isSeller = !_isSeller; }); }, icon: Icon( _isSeller ? Icons.check_box_rounded : Icons.check_box_outline_blank, color: _isSeller ? Colors.greenAccent : Colors.deepOrangeAccent, ), ), Text( 'Are you a seller ?', style: TextStyle(color: Colors.white60), ) ], ), ), ) : Container(), _isLoading == true ? CircularProgressIndicator() : Container( height: 50, padding: EdgeInsets.only(bottom: 10), width: double.infinity, child: ElevatedButton( style: ElevatedButton.styleFrom( elevation: 20, onSurface: Colors.blueGrey, fixedSize: const Size(199, 50), primary: Colors.cyan, onPrimary: Colors.black, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), ), onPressed: _passStrength >= 3 / 4 ? _submit : null, child: Text( _authMode == AuthMode.Login ? 'Login with Email' : 'Create an account', style: TextStyle(fontWeight: FontWeight.bold)), ), ), TextButton( onPressed: _toggleAuthMode, child: Text( _authMode == AuthMode.Login ? 'Need an account? Register' : 'Have an account? Sign in', style: TextStyle( color: Colors.cyan, fontWeight: FontWeight.bold, ), ), ), _builderCardFooter(deviceSize), ], ), ), ); } Widget _builderCardFooter(Size deviceSize) { return Container( width: deviceSize.width, margin: EdgeInsets.only( right: deviceSize.width * 0, top: deviceSize.height * 0.037, left: deviceSize.width * 0, bottom: deviceSize.height * 0.01, ), child: Center( child: Text( 'πŸš€ Powered by Neural Bots Inc', style: TextStyle( color: Colors.orange, fontWeight: FontWeight.bold, ), ), ), ); } Widget _buildPasswordHelper(BuildContext context, Size deviceSize) { return Container( padding: EdgeInsets.all(10), //margin: EdgeInsets.only(top: 10, left: 48, right: 45), margin: EdgeInsets.only( top: deviceSize.height * 0.015, left: deviceSize.height * 0.00, right: deviceSize.height * 0.0, ), constraints: BoxConstraints( minHeight: deviceSize.height * 0.05, minWidth: deviceSize.height * 0.75, ), color: Colors.blueGrey.withOpacity(0.1), child: Column( mainAxisAlignment: MainAxisAlignment.start, children: [ Row( children: [ Icon( _passStrength >= 3 / 4 ? Icons.check_circle : Icons.check_circle, size: 20, color: _passStrength >= 3 / 4 ? Colors.lightGreenAccent : Colors.blueGrey, ), SizedBox(width: 5), Text( 'Required: Must contain at least 8 characters', style: TextStyle( fontSize: 12, color: _passStrength >= 3 / 4 ? Colors.lightGreenAccent : Colors.blueGrey, ), ), ], ), Row( children: [ Icon( _passStrength >= 1 ? Icons.check_circle : Icons.check_circle, size: 20, color: _passStrength >= 1 ? Colors.lightGreenAccent : Colors.blueGrey, ), SizedBox(width: 5), Text( 'Optional: contains both letter and digits', style: TextStyle( fontSize: 12, color: _passStrength >= 1 ? Colors.lightGreenAccent : Colors.blueGrey, ), ), ], ), ], ), ); } }
0
mirrored_repositories/kryptonian-flutter-app/lib
mirrored_repositories/kryptonian-flutter-app/lib/providers/cart.dart
import 'package:flutter/foundation.dart'; import 'package:flutter_complete_guide/providers/product.dart'; class CartItem { final String id; final String productId; final String title; final double price; final int quantity; CartItem({ @required this.id, @required this.productId, @required this.title, @required this.price, @required this.quantity, }); } class Cart with ChangeNotifier { /// Map with Product Id as key & value as CarItem Map<String, CartItem> _items = {}; int item_qty = 0; Map<String, CartItem> get items { return {..._items}; } List<CartItem> get itemsList { return _items.values.toList(); } double get itemSummaryPrice { var _itemPriceTotal = 0.0; _items.forEach( (key, value) { _itemPriceTotal += value.price * value.quantity; }, ); return _itemPriceTotal; } int get itemCount { return _items.length; } int getItemQuantity(String productId) { _items.forEach( (key, item) { if (item.productId == productId) { item_qty = item.quantity; } }, ); if (_items.containsKey(productId)) { return item_qty; } else { return 0; } } void deleteItems(String productId) { if (_items.containsKey(productId)) { _items.remove(productId); } else { return; } notifyListeners(); } void clearCart() { _items = {}; notifyListeners(); } void clearSingleItem(String productId) { if (!_items.containsKey(productId)) { return; } if (_items[productId].quantity > 1) { _items.update( productId, (item) => CartItem( id: item.id, productId: item.productId, title: item.title, price: item.price, quantity: item.quantity - 1, ), ); } else { _items.remove(productId); } notifyListeners(); } double getTotalItemPrice(CartItem item) { /// SubTitle => cartData.itemsList[index].price * cartData.itemsList[index].quantity //print('Method => getTotalItemPrice: $item'); return item.price * item.quantity; } void addItems(String productID, String title, double price) { if (_items.containsKey(productID)) { /// If Item present in Cart then increase the quantity and price /// map.update(key, (value) => newValue ) _items.update( productID, (existingItem) { return CartItem( id: existingItem.id, productId: existingItem.productId, title: existingItem.title, quantity: existingItem.quantity + 1, price: existingItem.price, ); }, ); } else { /// Add a new Item if Product not present in Cart _items.putIfAbsent( productID, () => CartItem( id: DateTime.now().toString(), productId: productID, title: title, price: price, quantity: 1, ), ); //print("Method => addItems: cartItem: $_items"); } notifyListeners(); } void reduceItems(String productID) { if (_items.containsKey(productID) && _items[productID].quantity > 1) { /// If Item present in Cart then decrease the quantity and price /// map.update(key, (value) => newValue ) _items.update( productID, (existingItem) { return CartItem( id: existingItem.id, productId: existingItem.productId, title: existingItem.title, quantity: existingItem.quantity > 0 ? existingItem.quantity - 1 : 0, price: existingItem.price, ); }, ); } else { _items.remove(productID); } notifyListeners(); } void updateItems(String productId, Product updatedProduct) { if (_items.containsKey(productId)) { _items.update( productId, (existingItem) { return CartItem( id: existingItem.id, productId: productId, title: updatedProduct.title, price: updatedProduct.price, quantity: existingItem.quantity, ); }, ); } notifyListeners(); } }
0
mirrored_repositories/kryptonian-flutter-app/lib
mirrored_repositories/kryptonian-flutter-app/lib/providers/light.dart
import 'package:flutter/material.dart'; class Light with ChangeNotifier { bool _isDark = false; bool get themeDark => _isDark; void toggleLights() { _isDark = !_isDark; notifyListeners(); } }
0
mirrored_repositories/kryptonian-flutter-app/lib
mirrored_repositories/kryptonian-flutter-app/lib/providers/auth.dart
/// Docs => https://firebase.google.com/docs/reference/rest/auth import 'dart:async'; import 'dart:convert'; import 'package:flutter/cupertino.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_complete_guide/models/http_exception.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:http/http.dart' as http; import 'package:shared_preferences/shared_preferences.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:google_sign_in/google_sign_in.dart'; class Auth with ChangeNotifier { String _token; DateTime _expiryDate; String _uid; Timer _authTimer; String _googleToken; String _googleUid; /// Instantiate FireBase Auth:- final _firebaseAuth = FirebaseAuth.instance; /// Get google-current-user:- User get currentGoogleUser => _firebaseAuth.currentUser; String get googleToken { final String SECRET_KEY = dotenv.env['SECRET_KEY']; _googleToken = SECRET_KEY; return _googleToken; } String get googleUid { _googleUid = _firebaseAuth.currentUser == null ? null : currentGoogleUser.uid; return _googleUid; } bool get isAuth { return token != null; } /// If you have a token and didn't expire => User Authenticated:- String get token { if (_token != null && _expiryDate != null && _expiryDate.isAfter(DateTime.now())) { return _token; } else if (_token != null && googleToken != null) { return _token; } return null; } String get userId { return _uid; } Future<void> _authenticate(String email, String password, String urlSegment, bool isEmailSignIn) async { final String API_KEY = dotenv.env['API_KEY']; final String SECRET_KEY = dotenv.env['SECRET_KEY']; if (isEmailSignIn) { /// Email SignIn print('Inside Email Sign In: $isEmailSignIn'); final url = Uri.parse( 'https://identitytoolkit.googleapis.com/v1/accounts:${urlSegment}?key=$API_KEY'); try { final response = await http.post( url, body: json.encode( { 'email': email, 'password': password, 'returnSecureToken': true, }, ), ); var responseData = json.decode(response.body); if (responseData['error'] != null) { throw HttpException(message: responseData['error']['message']); } /// Save Token and Expiry date:- _token = responseData['idToken']; _uid = responseData['localId']; _expiryDate = DateTime.now().add( Duration(seconds: int.parse(responseData['expiresIn'])), //_expiryDate = DateTime.now().add( // Duration(seconds: 6), ); // Auto-Logout will be triggered after token expiry:- _autoLogout(); notifyListeners(); /// Shared Pref to Store/Get data from Device:- final prefs = await SharedPreferences.getInstance(); final userData = json.encode( { 'token': _token, 'userId': _uid, 'expiryDate': _expiryDate.toIso8601String(), }, ); prefs.setString('userData', userData); } catch (error) { throw error; } } else { /// Google SignIn print('Inside Google Sign In: ${!isEmailSignIn}'); _token = SECRET_KEY; _uid = googleUid; notifyListeners(); } } Future<void> signup(String email, String password, String urlSegment, bool isEmailSignIn) async { return _authenticate(email, password, urlSegment, isEmailSignIn); } Future<void> login(String email, String password, String urlSegment, bool isEmailSignIn) async { return _authenticate(email, password, urlSegment, isEmailSignIn); } void logout() async { /// Reset Google Sign In Params:- final googleSignIn = GoogleSignIn(); await googleSignIn.signOut(); await _firebaseAuth.signOut(); /// Reset Email Sign In params:- _token = null; _uid = null; _expiryDate = null; if (_authTimer != null) { _authTimer.cancel(); _authTimer = null; } notifyListeners(); final prefs = await SharedPreferences.getInstance(); //prefs.remove('userData'); prefs.clear(); } void _autoLogout() { if (_authTimer != null) { _authTimer.cancel(); } final _timeToExpiry = _expiryDate.difference(DateTime.now()).inSeconds; _authTimer = Timer( Duration(seconds: _timeToExpiry), logout, ); } Future<bool> tryAutoLogin() async { final prefs = await SharedPreferences.getInstance(); if (!prefs.containsKey('userData')) { return false; } final Map<String, Object> extractedData = json.decode(prefs.getString('userData')); final expiryDate = DateTime.parse(extractedData['expiryDate']); if (expiryDate.isBefore(DateTime.now())) { return false; } // Initialize the Auth params:- _token = extractedData['token']; _uid = extractedData['userId']; _expiryDate = expiryDate; notifyListeners(); _autoLogout(); return true; } /// GOOGLE SIGN IN:- Future<User> signInWithGoogle() async { final googleSignIn = GoogleSignIn(); final googleUser = await googleSignIn.signIn(); if (googleUser != null) { final googleAuth = await googleUser.authentication; if (googleAuth.idToken != null) { final userCredential = await _firebaseAuth .signInWithCredential(GoogleAuthProvider.credential( idToken: googleAuth.idToken, accessToken: googleAuth.accessToken, )); return userCredential.user; } else { throw FirebaseAuthException( code: 'ERROR_MISSING_GOOGLE_ID_TOKEN', message: 'Missing Google ID Token', ); } } else { throw FirebaseAuthException( code: 'ERROR_ABORTED_BY_USER', message: 'Sign in aborted by user', ); } } }
0
mirrored_repositories/kryptonian-flutter-app/lib
mirrored_repositories/kryptonian-flutter-app/lib/providers/category.dart
import 'package:flutter/material.dart'; class Category with ChangeNotifier { final String id; final String title; final String imgUrl; Category({ this.id, this.title, this.imgUrl, }); }
0
mirrored_repositories/kryptonian-flutter-app/lib
mirrored_repositories/kryptonian-flutter-app/lib/providers/orders.dart
import 'dart:convert'; import 'package:flutter/foundation.dart'; import 'package:flutter_complete_guide/models/http_exception.dart'; import 'package:flutter_complete_guide/providers/cart.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:http/http.dart' as http; class OrderItem { final String id; final double amount; final List<CartItem> products; final DateTime dateTime; OrderItem({ @required this.id, @required this.amount, @required this.products, @required this.dateTime, }); } class Orders with ChangeNotifier { List<OrderItem> _orders = []; String productTitle = ''; int productQuantity = 0; double productTotal = 0.0; bool isLoading; final String auth; final String uid; Orders(this.auth, this.uid, this._orders); void setLoading() { isLoading = true; notifyListeners(); } void resetLoading() { isLoading = false; notifyListeners(); } bool get loadingState { return isLoading; } List<OrderItem> get orders { return [..._orders]; } String getOrderTitle(int index) { _orders[index].products.map((item) => productTitle = item.title); print('OrderTitle: ${productTitle}'); return productTitle; } int getOrderQuantity(int index) { _orders[index].products.map((item) => productQuantity = item.quantity); return productQuantity; } double getOrderProductTotal(int index) { _orders[index] .products .map((item) => productTotal = item.price * item.quantity); return productTotal; } Future<void> fetchAllOrders() async { // TODO: final String DOMAIN = dotenv.env['DOMAIN']; final url = Uri.https( '${DOMAIN}-default-rtdb.europe-west1.firebasedatabase.app', '/orders.json', {'auth': auth}); try { final response = await http.get(url); final Map<String, dynamic> result = json.decode(response.body); final List<OrderItem> loadedOrder = []; //print(result); if (result != null) { result.forEach( (orderId, order) { if (order['userId'] == uid) { loadedOrder.add( OrderItem( id: orderId, amount: order['amount'], dateTime: DateTime.parse(order['dateTime']), products: (order['products'] as List<dynamic>) .map( (cartItem) => CartItem( id: cartItem['id'], title: cartItem['title'], price: cartItem['price'], quantity: cartItem['quantity'], productId: cartItem['productId'], ), ) .toList(), ), ); } }, ); } _orders = loadedOrder.reversed.toList(); notifyListeners(); } catch (error) { throw error; } notifyListeners(); } Future<void> addOrder( List<CartItem> cartProducts, double total) async { // TODO: final timeStamp = DateTime.now(); final String DOMAIN = dotenv.env['DOMAIN']; final url = Uri.https( '${DOMAIN}-default-rtdb.europe-west1.firebasedatabase.app', '/orders.json', {'auth': auth}); final response = await http.post( url, body: json.encode( { 'userId': uid, 'amount': total, 'dateTime': timeStamp.toIso8601String(), 'products': cartProducts.map( (item) { return { 'id': item.id, 'productId': item.productId, 'title': item.title, 'price': item.price, 'quantity': item.quantity, }; }, ).toList(), }, ), ); if (response.statusCode == 200) { final orderId = json.decode(response.body)['name']; _orders.insert( 0, OrderItem( id: orderId, amount: total, products: cartProducts, dateTime: timeStamp, ), ); notifyListeners(); } else if (response.statusCode >= 400) { print('ORDER INSERT => Failed'); throw HttpException(message: 'Insert Failed!'); } } }
0
mirrored_repositories/kryptonian-flutter-app/lib
mirrored_repositories/kryptonian-flutter-app/lib/providers/product.dart
import 'package:flutter/foundation.dart'; class Product with ChangeNotifier { final String id; final String title; final String description; final double price; final String imageUrl; final String categoryId; bool isFavorite; int qty; Product({ @required this.id, @required this.title, @required this.description, @required this.price, @required this.imageUrl, @required this.categoryId, this.isFavorite = false, this.qty = 0, }); void toggleFavoriteStatus() { isFavorite = !isFavorite; //print('favorite: $isFavorite'); notifyListeners(); } Product copyWith({ String id, String title, String description, double price, String imageUrl, String catId, }) { return Product( id: id ?? this.id, title: title ?? this.title, price: price ?? this.price, description: description ?? this.description, imageUrl: imageUrl ?? this.imageUrl, categoryId: catId ?? this.categoryId, ); } }
0
mirrored_repositories/kryptonian-flutter-app/lib
mirrored_repositories/kryptonian-flutter-app/lib/providers/categories.dart
/// TODO: Later Refactor this block by automating configuration in FireBase /// i.e Adding Custom Categories by Product Owners /// Current Feature Supports fixed 8 Categories import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter_complete_guide/providers/category.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:http/http.dart' as http; class CategoriesItem { final String categoryId; final String categoryTitle; CategoriesItem({this.categoryId, this.categoryTitle}); } class Categories with ChangeNotifier { Map<String, dynamic> _categoriesItems = {}; List<Category> _categories = []; final String auth; Categories(this.auth, this._categories); List<Category> get categories { return _categories; } /// Fetch CategoryId for Matching Category Title:- String fetchCategoryId(String title) { String catId = ''; categoriesItems.forEach( (key, value) { if (value == title) { catId = key; } }, ); return catId; } /// Fetch CategoryTitle for Matching Category Id:- String fetchCategoryTitle(String catId) { String catTitle = ''; categoriesItems.forEach( (key, value) { if (key == catId) { catTitle = value; } }, ); return catTitle; } /// Get a map of Category Items:- Map<String, dynamic> get categoriesItems { _categories.forEach( (category) { _categoriesItems.addAll({'${category.id}': '${category.title}'}); }, ); return _categoriesItems; } /// categoryDropDownItems => Product Categories DropDown:- List<Map<String, dynamic>> get categoryDropDownItems { List<Map<String, dynamic>> data = []; categoriesItems.forEach( (catId, catTitle) { data.add( { 'display': catTitle, 'value': catId, }, ); }, ); return data; } /// TODO: For Future Advanced Product Configuration which allows users to add Categories:- /// Firebase CRED => Categories:- Future<void> addCategory(Category newCategory) async { String newCategoryId; final String DOMAIN = dotenv.env['DOMAIN']; final url = Uri.https( '${DOMAIN}-default-rtdb.europe-west1.firebasedatabase.app', '/categories.json', {'auth': auth}); try { final response = await http.post( url, body: json.encode( { 'title': newCategory.title, 'imageUrl': newCategory.imgUrl, }, ), ); newCategoryId = json.decode(response.body)['name']; /// ADD NEW Category:- //print('ADD => Category'); final categoryData = Category( id: newCategoryId, title: newCategory.title, imgUrl: newCategory.imgUrl, ); _categories.add(categoryData); notifyListeners(); } catch (error) { //print('Add Categories-Error => ${error}'); throw error; } } void updateCategory(String categoryId, Category newCategory) {} void deleteCategory(String categoryId) {} Future<void> fetchCategories() async { print('FETCHED => CATEGORIES'); final String DOMAIN = dotenv.env['DOMAIN']; final url = Uri.https( '${DOMAIN}-default-rtdb.europe-west1.firebasedatabase.app', '/categories.json', {'auth': auth}); try { final response = await http.get(url); final Map<String, dynamic> result = json.decode(response.body); //print(result); final List<Category> LoadedCategory = []; result['error'] == 'Permission denied' ? throw 'Authentication Failed Permission Denied!' : result.forEach( (key, category) { LoadedCategory.add( Category( id: key, title: category['title'], imgUrl: category['imageUrl'], ), ); }, ); _categories = LoadedCategory; //print(_categories); notifyListeners(); } catch (error) { print('Fetch Categories-ERROR => $error'); throw error; } } }
0
mirrored_repositories/kryptonian-flutter-app/lib
mirrored_repositories/kryptonian-flutter-app/lib/providers/products.dart
import 'dart:convert'; import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter_complete_guide/providers/product.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:http/http.dart' as http; class Products with ChangeNotifier { List<Product> _items = []; final String auth; final String uid; Products(this.auth, this.uid, this._items); List<Product> get item { return [..._items]; } List<Product> get favoriteItems { return _items.where((product) => product.isFavorite == true).toList(); } /// Filter Products by Categories if category flag == true else all items:- List<Product> fetchProductByCategories(String catId, bool categoryFlag) { return categoryFlag == true && catId != '' ? _items.where((product) => product.categoryId == catId).toList() : item; } Product findById(String id) { return _items.firstWhere((product) => product.id == id); } int getIndexByProductId(String id) { return _items.indexWhere((product) => product.id == id); } void addProductQuantity(String id, int index) { _items[index].id == id ? _items[index].qty += 1 : 0; notifyListeners(); } void decreaseProductQuantity(String id, int index) { (_items[index].id == id) && (_items[index].qty > 0) ? _items[index].qty -= 1 : 0; notifyListeners(); } void clearUnitProductQuantity(String productId) { final filteredItem = _items.firstWhere((item) => item.id == productId); filteredItem.qty = 0; notifyListeners(); } void clearProductQuantity() { _items.forEach((product) { product.qty = 0; }); notifyListeners(); } /// Firebase CRED Methods:- Future<void> fetchProduct([bool filterByUser = false]) async { print('FETCH => PRODUCTS, $uid'); final String DOMAIN = dotenv.env['DOMAIN']; final url = Uri.https( '${DOMAIN}-default-rtdb.europe-west1.firebasedatabase.app', '/products.json', filterByUser ? { 'auth': auth, 'orderBy': json.encode("userId"), 'equalTo': json.encode(uid), } : { 'auth': auth, }, ); try { final response = await http.get(url); final Map<String, dynamic> result = json.decode(response.body); final List<Product> LoadedProduct = []; result['error'] == 'Permission denied' ? throw 'Authentication Failed Permission Denied!' : result.forEach( (key, product) { LoadedProduct.add( Product( id: key, title: product['title'], price: product['price'], description: product['description'], isFavorite: product['isFavorite'], imageUrl: product['imageUrl'], categoryId: product['categoryId'], ), ); }, ); _items = LoadedProduct; //print(_items); notifyListeners(); } catch (error) { print('ERROR => $error'); print('FETCH? => PRODUCTS, $uid'); throw error; } } Future<void> addProduct(Product newProduct) async { String newProductId; final String DOMAIN = dotenv.env['DOMAIN']; final url = Uri.https( '${DOMAIN}-default-rtdb.europe-west1.firebasedatabase.app', '/products.json', {'auth': auth}); try { final response = await http.post( url, body: json.encode( { 'title': newProduct.title, 'price': newProduct.price, 'description': newProduct.description, 'qty': newProduct.qty, 'imageUrl': newProduct.imageUrl, 'isFavorite': newProduct.isFavorite, 'userId': uid, 'categoryId': newProduct.categoryId, }, ), ); newProductId = json.decode(response.body)['name']; /// ADD NEW PRODUCT //print('ADD => Product'); final product = Product( id: newProductId, title: newProduct.title, price: newProduct.price, description: newProduct.description, imageUrl: newProduct.imageUrl, categoryId: newProduct.categoryId, ); _items.add(product); notifyListeners(); } catch (error) { print('ERROR: ${error}'); throw error; } } Future<void> deleteProductTwin(String productId) async { // TODO: Alternate Approach to Delete! print('DELETE => Product: ${productId}'); final url = Uri.https( 'kryptonian-flutter-app-default-rtdb.europe-west1.firebasedatabase.app', '/products/${productId}.json', {'auth': auth}); final response = await http.delete(url); //print('DELETE Response => ${response.statusCode}'); if (response.statusCode == 200) { _items.removeWhere((product) => product.id == productId); } else if (response.statusCode >= 400) { print('DELETE => Failed: ${response.body}'); throw HttpException('Delete Failed. Try Again Later!'); } notifyListeners(); } Future<void> deleteProduct(String productId) async { //print('DELETE => Product: ${productId}'); final String DOMAIN = dotenv.env['DOMAIN']; final existingProdIndex = _items.indexWhere((item) => item.id == productId); Product existingProduct = _items[existingProdIndex]; _items.removeWhere((product) => product.id == productId); final url = Uri.https( '${DOMAIN}-default-rtdb.europe-west1.firebasedatabase.app', '/products/${productId}.json', {'auth': auth}); final response = await http.delete(url); //print('DELETE Response => ${response.statusCode}'); if (response.statusCode == 200) { existingProduct = null; } else if (response.statusCode >= 400) { _items.insert(existingProdIndex, existingProduct); notifyListeners(); throw HttpException('Delete Failed. Try Again Later!'); } notifyListeners(); } Future<void> updateProduct(String id, Product updatedProduct) async { //TODO: Work on this!! //print('UPDATE => Product'); final String DOMAIN = dotenv.env['DOMAIN']; final productIndex = _items.indexWhere((product) => product.id == id); if (productIndex >= 0) { final url = Uri.https( '${DOMAIN}-default-rtdb.europe-west1.firebasedatabase.app', '/products/${id}.json', {'auth': auth}); final response = await http.patch( url, body: json.encode({ 'title': updatedProduct.title, 'price': updatedProduct.price, 'description': updatedProduct.description, 'qty': updatedProduct.qty, 'imageUrl': updatedProduct.imageUrl, 'categoryId': updatedProduct.categoryId, }), ); _items[productIndex] = updatedProduct; notifyListeners(); } } }
0
mirrored_repositories/kryptonian-flutter-app/lib
mirrored_repositories/kryptonian-flutter-app/lib/providers/users.dart
import 'dart:convert'; import 'package:flutter/cupertino.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; import 'package:http/http.dart' as http; class User { final String sellerId; final String userId; final String email; final bool isSeller; User({this.sellerId, this.userId, this.email, this.isSeller}); } class Users with ChangeNotifier { /// TODO: SELLER-USER Relationship:- List<User> _usersList = []; final String auth; final String uid; Users(this.auth, this.uid, this._usersList); List<User> get usersList { return [..._usersList]; } bool get fetchIsSeller { bool isSeller; _usersList.forEach( (user) { if (user.userId == uid) { isSeller = user.isSeller; } }, ); return isSeller; } String get userName { String email; int startIndex; int endIndex; _usersList.forEach( (user) { if (user.userId == uid) { email = user.email; } }, ); /// Extract name from email:- const start = ""; const end = "@"; try { startIndex = email.indexOf(start); endIndex = email.indexOf(end, startIndex + start.length); } catch (error) { startIndex = 0; endIndex = 0; } if (email != null) { return email.substring(startIndex + start.length, endIndex); } else return ''; } Future<void> addUser(String email, bool isSeller) async { print('ADD => User | $email | isSeller: $isSeller | uid: $uid | auth'); String newSellerId; final String DOMAIN = dotenv.env['DOMAIN']; try { final url = Uri.https( '${DOMAIN}-default-rtdb.europe-west1.firebasedatabase.app', '/users.json', {'auth': auth}); if (email != '') { final response = await http.post( url, body: json.encode( { 'userId': uid, 'email': email, 'isSeller': isSeller, }, ), ); newSellerId = json.decode(response.body)['name']; /// ADD NEW PRODUCT final user = User( sellerId: newSellerId, userId: uid, email: email, isSeller: isSeller, ); _usersList.add(user); print('ADD => User Added'); notifyListeners(); } else { print('ADD => User not Added'); } } catch (error) { print('ADD USER-ERROR: ${error}'); throw error; } } Future<void> fetchUsers() async { print('FETCHED => All Users'); final String DOMAIN = dotenv.env['DOMAIN']; final url = Uri.https( '${DOMAIN}-default-rtdb.europe-west1.firebasedatabase.app', '/users.json', { 'auth': auth, }, ); try { final response = await http.get(url); final Map<String, dynamic> result = json.decode(response.body); final List<User> LoadedUsers = []; result['error'] == 'Permission denied' ? throw 'Authentication Failed Permission Denied!' : result.forEach( (key, user) { LoadedUsers.add( User( sellerId: key, userId: user['userId'], email: user['email'], isSeller: user['isSeller'], ), ); }, ); _usersList = LoadedUsers; //print(_usersList); notifyListeners(); } catch (error) { print('FETCH: USERS-ERROR => $error'); //throw error; } } }
0
mirrored_repositories/kryptonian-flutter-app
mirrored_repositories/kryptonian-flutter-app/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_shop_app/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/Flutter-APP
mirrored_repositories/Flutter-APP/lib/ContentWidget.dart
import 'package:flutter/material.dart'; import 'dart:math'; import 'Profil.dart'; import 'Search.dart'; import 'package:epicture/NiceText.dart'; class ContentWidget extends StatelessWidget { final int page; ContentWidget(this.page); @override Widget build(BuildContext context) { final children = <Widget>[]; Future<Null> refreshList() async { await Future.delayed(Duration(seconds: 10)); print("refresh"); return null; } GlobalKey<RefreshIndicatorState> refreshKey; switch (page) { case 0: { children.add(Profil()); } break; case 1: { children.add(SearchPage()); } break; case 2: { children.add(Center(child: Text("upload Page"))); } break; default: { children.add(Text("default")); } break; } // if (page == 0) { // } else { // children.add( // LoginPage(), // ); // } return Scaffold( appBar: AppBar( title: Center(child: NiceText("Epicture")), ), body: ListView(children: children), ); } }
0
mirrored_repositories/Flutter-APP
mirrored_repositories/Flutter-APP/lib/NiceText.dart
import 'package:flutter/material.dart'; class NiceText extends StatelessWidget { final String text; NiceText(this.text); @override Widget build(BuildContext context) { return Text( this.text, style: TextStyle(shadows: [ Shadow( blurRadius: 5, color: Color.fromARGB(155, 0, 0, 255), offset: Offset(1, 1)) ]), ); } }
0
mirrored_repositories/Flutter-APP
mirrored_repositories/Flutter-APP/lib/LoginPage.dart
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:url_launcher/url_launcher.dart'; import './StyleText/Titre.dart'; import 'package:flutter/services.dart'; import 'package:uni_links/uni_links.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'Connected.dart'; class LoginPage extends StatefulWidget { const LoginPage({Key key, @required this.parent}) : super(key: key); final parent; @override LoginPageState createState() => LoginPageState(); } class LoginPageState extends State<LoginPage> { String urlConnexion = 'https://api.imgur.com/oauth2/authorize?client_id=3ac22aa91d98294&response_type=token&state=login_token'; String urlRegister = 'https://imgur.com/register'; StreamSubscription _sub; @override void initState() { super.initState(); initLinks(); } @override void dispose() { super.dispose(); if (_sub != null) _sub.cancel(); } void initLinks() async { await initUniLinks(); } Future<void> getLink(String url) async { print("connexion OK "); url = url.replaceFirst('#', '&'); Uri uri = Uri.parse(url); final prefs = await SharedPreferences.getInstance(); prefs.setString('access_token', uri.queryParameters['access_token']); prefs.setString('refresh_token', uri.queryParameters['refresh_token']); prefs.setString( 'account_username', uri.queryParameters['account_username']); prefs.setString('account_id', uri.queryParameters['account_id']); prefs.setInt( 'expires', DateTime.now().millisecondsSinceEpoch + int.parse(uri.queryParameters['expires_in'])); widget.parent.setState(() { widget.parent.findPrefs(); }); } /// Initialise DeepLinking listener Future<Null> initUniLinks() async { try { String initialLink = await getInitialLink(); if (initialLink != null) { await getLink(initialLink); } } on PlatformException { return; } _sub = getLinksStream().listen((String link) async { await getLink(link); }, onError: (err) { print(err); }); } Future<void> addCookie() async { Connected( "d4b4b4af033710d2d423568a64b084df8851018a", "950f1271de45aa8e821ed8bea24fc4546c28207e", "badbouns", "146548119", "315360000"); print("click effectuer"); final prefs = await SharedPreferences.getInstance(); final access_token = prefs.getString('access_token'); final refresh_token = prefs.getString('refresh_token'); final name = prefs.getString('account_username'); final account_id = prefs.getString('account_id'); final expires = prefs.getString('expires'); print(access_token.toString()); print(refresh_token.toString()); print(name.toString()); print(account_id.toString()); print(expires.toString()); } /// Displays a button to login /// Redirects to imgur site for user to login @override Widget build(BuildContext context) { return Container( child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Titre("Epicture"), Padding( padding: EdgeInsets.fromLTRB(0, 70, 0, 70), child: ClipRRect( borderRadius: BorderRadius.circular(100.0), child: Image.network( "https://media.discordapp.net/attachments/643948072141062194/818879424459178045/Epicture.png", height: 150, width: 150, ))), ClipRRect( borderRadius: BorderRadius.circular(25.0), child: OutlinedButton( onPressed: () async { launch(urlConnexion); }, child: Padding( padding: EdgeInsets.fromLTRB(55, 10, 55, 10), child: Text('Login on Imgur !', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 25, color: Colors.white))), style: TextButton.styleFrom( backgroundColor: Color.fromARGB(255, 52, 199, 89)))), Padding( padding: EdgeInsets.fromLTRB(0, 30, 0, 30), child: ClipRRect( borderRadius: BorderRadius.circular(25.0), child: OutlinedButton( onPressed: () async { launch(urlRegister); }, child: Padding( padding: EdgeInsets.fromLTRB(30, 10, 30, 10), child: Text('Register on Imgur !', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 22, color: Colors.white))), style: TextButton.styleFrom( backgroundColor: Color.fromARGB(255, 0, 122, 196)))), ), Padding( padding: EdgeInsets.fromLTRB(0, 10, 0, 10), child: ClipRRect( borderRadius: BorderRadius.circular(25.0), child: OutlinedButton( onPressed: () async { addCookie(); }, child: Padding( padding: EdgeInsets.fromLTRB(30, 10, 30, 10), child: Text('Add Token to cookie', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 22, color: Colors.white))), style: TextButton.styleFrom( backgroundColor: Color.fromARGB(255, 216, 32, 32)))), ) ]), )); } }
0
mirrored_repositories/Flutter-APP
mirrored_repositories/Flutter-APP/lib/Search.dart
import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; class SearchPage extends StatefulWidget { @override SearchPageState createState() => SearchPageState(); } class SearchPageState extends State<SearchPage> { var _pictures = []; List arrayRecherche = []; int statusSearch = 0; bool etat = false; final myController = TextEditingController(); String clientId = "817c9afd3f7a826"; String bearerToken = "a7c5407135610fd6ee7da764fcea6c795ebddd6b"; String clientSecret = "016a2267088f4c786f7bcd3d77083890acc7b712"; String refreshToken = "c90586fffad99b26edda1f602e3c5b1777839f90"; String accountUsername = "badbouns"; // Profil(); @override void initState() { super.initState(); SearchPage(); } Future<Null> SearchPage() async { print("Search"); var queryParameters = { 'q': myController.text, }; var response = await http.get( Uri.https( "api.imgur.com", "/3/gallery/search/viral/all/0", queryParameters), headers: {"Authorization": "Client-ID 817c9afd3f7a826"}, ); // if (response.statusCode != 200) { // return; // } var data = jsonDecode(response.body); print(data["data"]); // print(data["data"]["success"]); setState(() { etat = true; // status = data["data"]["status"]; statusSearch = data["status"]; arrayRecherche = data["data"]; }); } @override Widget build(BuildContext context) { final children = <Widget>[]; children.add(Padding( padding: const EdgeInsets.fromLTRB(20, 10, 20, 10), child: ClipRRect( borderRadius: BorderRadius.circular(25.0), child: Container( color: Color.fromRGBO(229, 229, 234, 100), child: TextField( style: TextStyle(color: Colors.green), cursorColor: Colors.red, controller: myController, decoration: InputDecoration( prefixIcon: Icon( Icons.search, color: Colors.black, ), hintText: 'Search...', hintStyle: TextStyle(color: Colors.black), ), ), )), )); children.add(ElevatedButton( onPressed: () async { SearchPage(); }, child: Text("Search"))); if (statusSearch == 200) { for (var search in arrayRecherche) { if (search["images"] != null) { children.add(Padding( padding: EdgeInsets.all(10), child: Container( decoration: new BoxDecoration( color: Color.fromARGB(255, 199, 199, 204), borderRadius: BorderRadius.all(Radius.circular(20))), child: Center( child: Column(children: [ Padding( padding: EdgeInsets.fromLTRB(15, 15, 15, 5), child: ClipRRect( borderRadius: BorderRadius.circular(8.0), child: Image.network( search["images"][0]["link"], semanticLabel: search["images"][0]["id"], ))), (search["images"][0]["description"] != null) ? (Padding( padding: const EdgeInsets.fromLTRB(0, 0, 0, 10), child: Text(search["images"][0]["description"], style: TextStyle(fontSize: 15)), )) : (Padding( padding: const EdgeInsets.fromLTRB(0, 0, 0, 10), child: Text(search["title"], style: TextStyle(fontSize: 15)), )), ]), )))); } else { children.add(Padding( padding: EdgeInsets.all(10), child: Container( decoration: new BoxDecoration( color: Color.fromARGB(255, 199, 199, 204), borderRadius: BorderRadius.all(Radius.circular(20))), child: Center( child: Column(children: [ Padding( padding: EdgeInsets.fromLTRB(15, 15, 15, 5), child: ClipRRect( borderRadius: BorderRadius.circular(8.0), child: Image.network( search["link"], // semanticLabel: search["images"][0]["id"], ))), Padding( padding: const EdgeInsets.fromLTRB(0, 0, 0, 10), child: Text(search["title"], style: TextStyle(fontSize: 15)), ), ]), )))); } } // children.add(Text("coucou")); } //i = 0; i < arrayRecherche[0].length; i++ return Container( child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: children), )); } } // SearchPage() { // return Padding( // padding: const EdgeInsets.fromLTRB(20, 10, 20, 10), // child: ClipRRect( // borderRadius: BorderRadius.circular(25.0), // child: Container( // color: Color.fromRGBO(229, 229, 234, 100), // child: TextField( // style: TextStyle(color: Colors.green), // cursorColor: Colors.red, // decoration: InputDecoration( // prefixIcon: Icon( // Icons.search, // color: Colors.black, // ), // hintText: 'Search...', // hintStyle: TextStyle(color: Colors.black), // ), // ), // )), // ); // }
0
mirrored_repositories/Flutter-APP
mirrored_repositories/Flutter-APP/lib/Connected.dart
import 'package:shared_preferences/shared_preferences.dart'; class Connected { Connected(var accessToken, var refreshToken, var accountUsername, var accountId, var expire) { print("on add cookie"); addCookie(accessToken, refreshToken, accountUsername, accountId, expire); } Future<void> addCookie( accessToken, refreshToken, accountUsername, accountId, expire) async { final prefs = await SharedPreferences.getInstance(); prefs.setString('access_token', accessToken); prefs.setString('refresh_token', refreshToken); prefs.setString('account_username', accountUsername); prefs.setString('account_id', accountId); prefs.setInt( 'expires', DateTime.now().millisecondsSinceEpoch + int.parse(expire)); } }
0
mirrored_repositories/Flutter-APP
mirrored_repositories/Flutter-APP/lib/main.dart
import 'package:flutter/material.dart'; import 'package:epicture/NiceText.dart'; import 'package:epicture/ContentWidget.dart'; import 'LoginPage.dart'; import 'Connected.dart'; void main() { runApp(MyApp()); Connected( "d4b4b4af033710d2d423568a64b084df8851018a", "950f1271de45aa8e821ed8bea24fc4546c28207e", "badbouns", "146548119", "315360000"); } class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { print(Uri.base); return MaterialApp( title: 'Epicture', theme: ThemeData( primaryColor: Color.fromARGB(255, 0, 122, 196), ), home: MyHomePage(title: 'Epicture'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _selectedIndex = 0; bool connecter = true; void _onItemTapped(int index) { setState(() { _selectedIndex = index; }); } @override Widget build(BuildContext context) { return Scaffold( body: connecter ? ContentWidget(_selectedIndex) : (LoginPage()), bottomNavigationBar: connecter ? BottomNavigationBar( items: const <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: Icon(Icons.home), title: Text('Home')), BottomNavigationBarItem( icon: Icon(Icons.search), title: Text('Search')), BottomNavigationBarItem( icon: Icon(Icons.camera_alt), title: Text('Camera')), ], currentIndex: _selectedIndex, // selectedItemColor: Colors.amber[800], onTap: _onItemTapped, ) : (null)); } } // Center( // child: Column( // mainAxisAlignment: MainAxisAlignment.center, // children: <Widget>[ // Text( // 'You have pushed the button this many times:', // ), // Text( // '$_counter', // style: Theme.of(context).textTheme.headline4, // ), // Image.network('https://picsum.photos/250?image=9'), // Image.network('https://picsum.photos/250?image=9'), // ], // ), // ) //bottom bar // , // bottomNavigationBar: BottomNavigationBar( // items: const <BottomNavigationBarItem>[ // BottomNavigationBarItem( // icon: Icon(Icons.home), // label: 'Home', // ), // BottomNavigationBarItem( // icon: Icon(Icons.account_box_rounded), // label: 'Account', // ), // ], // currentIndex: _selectedIndex, // // selectedItemColor: Colors.amber[800], // onTap: _onItemTapped, // )
0
mirrored_repositories/Flutter-APP
mirrored_repositories/Flutter-APP/lib/Profil.dart
import 'dart:convert'; import 'dart:io'; import 'dart:math'; import 'package:flutter/material.dart'; import 'package:epicture/NiceText.dart'; import 'package:http/http.dart' as http; class Profil extends StatefulWidget { @override ProfilState createState() => ProfilState(); } class ProfilState extends State<Profil> { var _pictures = []; var linkAvatar = ""; var bio = ""; int reputation = 0; var reputationName = "bg"; List arrayImageProfils = []; int status = 0; String clientId = "817c9afd3f7a826"; String bearerToken = "a7c5407135610fd6ee7da764fcea6c795ebddd6b"; String clientSecret = "016a2267088f4c786f7bcd3d77083890acc7b712"; String refreshToken = "c90586fffad99b26edda1f602e3c5b1777839f90"; String accountUsername = "badbouns"; // Profil(); @override void initState() { super.initState(); getPictures(); getImages(); } Future<Null> getPictures() async { var response = await http.get( Uri.https("api.imgur.com", "/3/account/badbouns"), headers: {"Authorization": "Client-ID 817c9afd3f7a826"}, ); // if (response.statusCode != 200) { // return; // } var data = jsonDecode(response.body); // List pictures = data["data"]; if (data["status"] == 200) { setState(() { status = data["status"]; linkAvatar = data["data"]["avatar"]; bio = data["data"]["bio"]; reputation = data["data"]["reputation"]; reputationName = data["data"]["reputation_name"]; }); // print(data); print(linkAvatar); print(bio); print(reputation); print(reputationName); } else { status = data["status"]; } } Future<Null> getImages() async { var response = await http.get( Uri.https("api.imgur.com", "/3/account/me/images"), headers: {"Authorization": "Bearer $bearerToken"}, ); // if (response.statusCode != 200) { // return; // } var data = jsonDecode(response.body); // List pictures = data["data"]; // print(data); setState(() { arrayImageProfils = data["data"]; }); print(arrayImageProfils); } // Future<Null> getImagee() async { // var response = await http.get( // Uri.https("api.imgur.com", "/3/account/me/images"), // headers: {HttpHeaders.authorizationHeader: "Bearer $bearerToken"}, // ); // if (response.statusCode != 200) { // return; // } // var data = jsonDecode(response.body); // List pictures = data["data"]; // var responseAlbums = await http.get( // Uri.https("api.imgur.com", "/3/account/me/albums/0"), // headers: {HttpHeaders.authorizationHeader: "Bearer $bearerToken"}, // ); // if (responseAlbums.statusCode != 200) { // return; // } // var albumData = jsonDecode(responseAlbums.body)['data']; // for (var album in albumData) { // var res = await http.get( // Uri.https("api.imgur.com", "/3/account/me/album/${album['id']}"), // headers: {HttpHeaders.authorizationHeader: "Bearer $bearerToken"}, // ); // var albumRes = await jsonDecode(res.body)['data']; // if (albumRes['images'] == null) continue; // for (var imageAlbum in albumRes['images']) { // pictures.removeWhere((element) => (element['id'] == imageAlbum['id'])); // } // pictures.add(albumRes); // } // pictures.sort((a, b) => b['datetime'].compareTo(a['datetime'])); // setState(() { // _pictures = pictures; // }); // print("les picture modifier:"); // print(_pictures); // } @override Widget build(BuildContext context) { final children = <Widget>[]; if (status == 200) { children.add(Padding( padding: EdgeInsets.fromLTRB(0, 20, 0, 30), child: Text("badbouns", style: TextStyle(fontSize: 30)))); children.add(Padding( padding: EdgeInsets.fromLTRB(0, 0, 0, 20), child: ClipRRect( borderRadius: BorderRadius.circular(100.0), child: new Container( width: 190.0, height: 190.0, decoration: new BoxDecoration( shape: BoxShape.circle, image: new DecorationImage( fit: BoxFit.fill, image: new NetworkImage(linkAvatar))))))); children.add(Padding( padding: EdgeInsets.fromLTRB(0, 0, 0, 0), child: Text("$reputation ㆍ $reputationName", style: TextStyle(fontSize: 25)))); if (bio != null) { children.add(Center( child: Padding( padding: EdgeInsets.fromLTRB(0, 0, 0, 50), child: Text(bio, style: TextStyle(fontSize: 15, fontStyle: FontStyle.italic))), )); } for (var i = 0; i < arrayImageProfils.length; i++) { children.add(Padding( padding: EdgeInsets.all(10), child: Container( decoration: new BoxDecoration( color: Color.fromARGB(255, 199, 199, 204), borderRadius: BorderRadius.all(Radius.circular(20))), child: Center( child: Column(children: [ Padding( padding: EdgeInsets.fromLTRB(15, 15, 15, 5), child: ClipRRect( borderRadius: BorderRadius.circular(8.0), child: Image.network( arrayImageProfils[i]["link"], semanticLabel: "coucou", ))), Padding( padding: const EdgeInsets.fromLTRB(0, 0, 0, 10), child: Text(arrayImageProfils[i]["description"], style: TextStyle(fontSize: 15)), ), ]), )))); } } else { children.add(Center( child: Text("erreur", style: TextStyle(fontSize: 30, color: Colors.red)), )); } // children.add(RefreshIndicator( // color: Colors.green, // onRefresh: getPictures, // child: CustomScrollView( // scrollDirection: Axis.vertical, // slivers: <Widget>[Text("coucou")], // ), // )); // children.add(GridView.count( // crossAxisCount: 4, // // Generate 100 widgets that display their index in the List. // children: List.generate(4, (index) { // return Center( // child: Text( // 'Item $index', // style: Theme.of(context).textTheme.headline5, // ), // ); // }), // )); return Container( child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: children), )); } }
0
mirrored_repositories/Flutter-APP/lib
mirrored_repositories/Flutter-APP/lib/StyleText/Titre.dart
import 'package:flutter/material.dart'; Text Titre(String text) { return Text(text, style: TextStyle(fontWeight: FontWeight.bold , fontSize: 50)); }
0
mirrored_repositories/Flutter-APP
mirrored_repositories/Flutter-APP/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:epicture/LoginPage.dart'; import 'package:epicture/Profil.dart'; import 'package:epicture/StyleText/Titre.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:epicture/main.dart'; void main() { testWidgets('Verification de la mΓ©thode Titre', (WidgetTester tester) async { var titre = Titre("test"); expect(titre.data, "test"); expect(titre.style.fontWeight, FontWeight.bold); expect(titre.style.fontSize, 50); }); testWidgets('Verification de la mΓ©thode LoginPage', (WidgetTester tester) async { var titre = LoginPage(); expect(titre.toString(), "LoginPage"); }); testWidgets('Verification de la mΓ©thode Profils', (WidgetTester tester) async { var titre = Profil(); expect(titre.toString(), "Profil"); }); // 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/wallapop-app
mirrored_repositories/wallapop-app/lib/main.dart
import 'package:flutter/material.dart'; import 'package:form_validation_app/src/bloc/provider.dart'; import 'package:form_validation_app/src/pages/home_page.dart'; import 'package:form_validation_app/src/pages/login_page.dart'; import 'package:form_validation_app/src/pages/producto_page.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return Provider( child: MaterialApp( debugShowCheckedModeBanner: false, title: 'Material App', initialRoute: 'home', routes: { 'login': (BuildContext context) => LoginPage(), 'home': (BuildContext context) => HomePage(), 'producto': (BuildContext context) => ProductoPage(), }, theme: ThemeData( brightness: Brightness.dark, primaryColor: Colors.black, accentColor: Colors.cyan[600], textTheme: TextTheme( headline: TextStyle(fontSize: 72.0, fontWeight: FontWeight.bold), title: TextStyle(fontSize: 36.0, fontStyle: FontStyle.italic), body1: TextStyle(fontSize: 14.0), ), ))); } }
0
mirrored_repositories/wallapop-app/lib/src
mirrored_repositories/wallapop-app/lib/src/pages/home_page.dart
import 'package:flutter/material.dart'; import 'package:form_validation_app/src/bloc/provider.dart'; class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { final bloc = Provider.of(context); return Scaffold( appBar: AppBar( title: Text('home'), ), body: Container(), floatingActionButton: _crearBoton(context), ); } _crearBoton(BuildContext context) { return FloatingActionButton( onPressed: () => Navigator.pushNamed(context, 'producto'), child: Icon(Icons.add), ); } }
0
mirrored_repositories/wallapop-app/lib/src
mirrored_repositories/wallapop-app/lib/src/pages/producto_page.dart
import 'package:flutter/material.dart'; import 'package:form_validation_app/src/models/producto_model.dart'; import 'package:form_validation_app/src/providers/productos_provider.dart'; import 'package:form_validation_app/src/utils/utils.dart' as utils; class ProductoPage extends StatefulWidget { @override _ProductoPageState createState() => _ProductoPageState(); } class _ProductoPageState extends State<ProductoPage> { final formKey = GlobalKey<FormState>(); final productoProvider = new ProductosProvider(); ProductoModel producto = new ProductoModel(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('producto'), actions: <Widget>[ IconButton( icon: Icon(Icons.photo_size_select_large), onPressed: () {}, ), IconButton( icon: Icon(Icons.camera_alt), onPressed: () {}, ), ], ), body: SingleChildScrollView( child: Container( padding: EdgeInsets.all(15.0), child: Form( key: formKey, child: Column( children: <Widget>[ _crearNombre(), SizedBox( height: 30.0, ), _crearPrecio(), SizedBox( height: 50.0, ), _crearBoton(context), _crearDisponible(), ], )), ), ), ); } Widget _crearNombre() { return TextFormField( initialValue: producto.titulo, onSaved: (value) => producto.titulo = value, validator: (value) { if (value.length < 3) { Text('insert product name'); } return null; }, textCapitalization: TextCapitalization.sentences, decoration: InputDecoration(labelText: 'Product name'), ); } Widget _crearPrecio() { return TextFormField( initialValue: producto.valor.toString(), onSaved: (value) => producto.valor = double.parse(value), validator: (value) { if (utils.isNumeric(value)) { return null; } else { return 'just numbers'; } }, keyboardType: TextInputType.numberWithOptions(decimal: true), decoration: InputDecoration(labelText: 'Product price [€]'), ); } Widget _crearBoton(BuildContext context) { return RaisedButton.icon( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10.0), ), color: Theme.of(context).accentColor, textColor: Colors.white, label: Text('save'), icon: Icon(Icons.save), onPressed: _submit, ); } Widget _crearDisponible() { return SwitchListTile( value: producto.disponible, onChanged: (value) => setState(() { producto.disponible = value; }), title: Text('available'), activeColor: Theme.of(context).accentColor, ); } void _submit() { if (!formKey.currentState.validate()) return; formKey.currentState.save(); print(producto.titulo); print(producto.valor); print(producto.disponible); productoProvider.crearProducto(producto); } }
0
mirrored_repositories/wallapop-app/lib/src
mirrored_repositories/wallapop-app/lib/src/pages/login_page.dart
import 'package:flutter/material.dart'; import 'package:form_validation_app/src/bloc/provider.dart'; class LoginPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Color.fromRGBO(0, 31, 51, 1), body: Stack( children: <Widget>[ _crearFondo(context), _loginForm(context), ], )); } Widget _crearFondo(BuildContext context) { final size = MediaQuery.of(context).size; final fondo = Container( height: size.height * 0.4, width: double.infinity, decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment(0.5, 0), end: Alignment(0.5, 1), colors: <Color>[ Color.fromRGBO(0, 61, 102, 1), Color.fromRGBO(0, 61, 102, 0.9) ])), ); final circulo = Container( width: 200.0, height: 200.0, decoration: BoxDecoration( borderRadius: BorderRadius.circular(200.0), color: Color.fromRGBO(255, 255, 255, 0.07)), ); return Stack( children: <Widget>[ fondo, Positioned(top: 50.0, left: 168.0, child: circulo), Positioned(top: 29.0, left: 7.0, child: circulo), Positioned(top: 150.0, left: 70.0, child: circulo), Container( padding: EdgeInsets.only(top: 80.0), child: Column( children: <Widget>[ Icon( Icons.person_pin_circle, color: Color.fromRGBO(255, 255, 255, 0.6), size: 95.0, ), SizedBox( height: 5.0, width: double.infinity, ), Text( 'Paula Romero', style: TextStyle(color: Colors.white, fontSize: 18), ) ], ), ) ], ); } Widget _loginForm(BuildContext context) { final bloc = Provider.of(context); final size = MediaQuery.of(context).size; return SingleChildScrollView( child: Column( children: <Widget>[ SafeArea( child: Container(height: 170.0), ), Container( margin: EdgeInsets.symmetric(vertical: 5.0), width: size.width * 0.85, padding: EdgeInsets.symmetric(vertical: 50.0), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(5.0)), child: Column( children: <Widget>[ Text( 'sign in', style: TextStyle(fontSize: 20), ), SizedBox( height: 10.0, ), _crearEmail(bloc), SizedBox( height: 20.0, ), _crearPassword(bloc), SizedBox( height: 70.0, ), _crearBoton(bloc) ], ), ), SizedBox( height: 30.0, ), Text( 'Forgot your password?', style: TextStyle(fontSize: 12.0, color: Colors.white), ), SizedBox( height: 100.0, ), ], ), ); } Widget _crearEmail(LoginBloc bloc) { return StreamBuilder( stream: bloc.emailStream, builder: (BuildContext context, AsyncSnapshot snapshot) { return Container( padding: EdgeInsets.symmetric(horizontal: 20.0), child: TextField( keyboardType: TextInputType.emailAddress, decoration: InputDecoration( // counterText: snapshot.data, icon: Icon( Icons.email, size: 25.0, color: Colors.black26, ), // hintText: 'email', labelText: 'email', labelStyle: TextStyle(color: Colors.black38), errorText: snapshot.error, ), onChanged: bloc.changeEmail, ), ); }); } Widget _crearPassword(LoginBloc bloc) { return StreamBuilder( stream: bloc.passwordStream, builder: (BuildContext context, AsyncSnapshot snapshot) { return Container( padding: EdgeInsets.symmetric(horizontal: 20.0), child: TextField( obscureText: true, keyboardType: TextInputType.emailAddress, onChanged: bloc.changePassword, decoration: InputDecoration( errorText: snapshot.error, // counterText: snapshot.data, icon: Icon( Icons.lock, size: 25.0, color: Colors.black26, ), // hintText: 'email', labelText: 'password', labelStyle: TextStyle(color: Colors.black38)), ), ); }); } Widget _crearBoton(LoginBloc bloc) { return StreamBuilder( stream: bloc.formValidStream, builder: (BuildContext context, AsyncSnapshot snapshot) { return RaisedButton( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(5.0), ), color: Colors.amberAccent, elevation: 0.0, padding: EdgeInsets.symmetric(horizontal: 70.0, vertical: 13.0), child: Container( child: Text( 'sign in', style: TextStyle(fontSize: 20.0, color: Colors.white), ), ), onPressed: snapshot.hasData ? () => _login(bloc, context) : null, ); }, ); } _login(LoginBloc bloc, BuildContext context) { Navigator.pushReplacementNamed(context, 'home'); } }
0
mirrored_repositories/wallapop-app/lib/src
mirrored_repositories/wallapop-app/lib/src/models/producto_model.dart
// To parse this JSON data, do // // final productoModel = productoModelFromJson(jsonString); import 'dart:convert'; ProductoModel productoModelFromJson(String str) => ProductoModel.fromJson(json.decode(str)); String productoModelToJson(ProductoModel data) => json.encode(data.toJson()); class ProductoModel { String id; String titulo; double valor; bool disponible; String fotoUrl; ProductoModel({ this.id, this.titulo = '', this.valor = 0.0, this.disponible = true, this.fotoUrl, }); factory ProductoModel.fromJson(Map<String, dynamic> json) => ProductoModel( id: json["id"], titulo: json["titulo"], valor: json["valor"], disponible: json["disponible"], fotoUrl: json["fotoUrl"], ); Map<String, dynamic> toJson() => { "id": id, "titulo": titulo, "valor": valor, "disponible": disponible, "fotoUrl": fotoUrl, }; }
0
mirrored_repositories/wallapop-app/lib/src
mirrored_repositories/wallapop-app/lib/src/bloc/login_bloc.dart
import 'dart:async'; import 'package:form_validation_app/src/bloc/validators.dart'; import 'package:rxdart/rxdart.dart'; class LoginBloc with Validators { final _emailController = BehaviorSubject<String>(); final _passwordController = BehaviorSubject<String>(); //Recuperar datos del stream Stream<String> get emailStream => _emailController.stream.transform(validarEmail); Stream<String> get passwordStream => _passwordController.stream.transform(validarPassword); Stream<bool> get formValidStream => CombineLatestStream.combine2(emailStream, passwordStream, (e, p) => true); //Insertar valores del Stream Function(String) get changeEmail => _emailController.sink.add; Function(String) get changePassword => _passwordController.sink.add; //Obtener ΓΊltimo valor ingresado String get email => _emailController.value; String get password => _passwordController.value; dispose() { _emailController?.close(); _passwordController?.close(); } }
0
mirrored_repositories/wallapop-app/lib/src
mirrored_repositories/wallapop-app/lib/src/bloc/validators.dart
import 'dart:async'; class Validators { final validarEmail = StreamTransformer<String, String>.fromHandlers(handleData: (email, sink) { Pattern pattern = r'^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$'; RegExp regExp = new RegExp(pattern); if (regExp.hasMatch(email)) { sink.add(email); } sink.addError('error'); }); final validarPassword = StreamTransformer<String, String>.fromHandlers( handleData: (password, sink) { if (password.length >= 6) { sink.add(password); } else { sink.addError('Wrong password :('); } }); }
0
mirrored_repositories/wallapop-app/lib/src
mirrored_repositories/wallapop-app/lib/src/bloc/provider.dart
import 'package:flutter/material.dart'; import 'package:form_validation_app/src/bloc/login_bloc.dart'; export 'package:form_validation_app/src/bloc/login_bloc.dart'; class Provider extends InheritedWidget { static Provider _instancia; factory Provider({Key key, Widget child}) { if (_instancia == null) { _instancia = new Provider._internal( key: key, child: child, ); } return _instancia; } final loginBloc = LoginBloc(); Provider._internal({Key key, Widget child}) : super(key: key, child: child); @override bool updateShouldNotify(InheritedWidget oldWidget) => true; // static LoginBloc of(BuildContext context) { // return context.dependOnInheritedWidgetOfExactType<Provider>().loginBloc; // } static LoginBloc of(BuildContext context) { return context.dependOnInheritedWidgetOfExactType<Provider>().loginBloc; } // static ProductosBloc productosBloc ( BuildContext context ) { // return context.dependOnInheritedWidgetOfExactType<Provider>()._productosBloc; // } }
0
mirrored_repositories/wallapop-app/lib/src
mirrored_repositories/wallapop-app/lib/src/utils/utils.dart
bool isNumeric(String s) { if (s.isEmpty) { return false; } final n = num.tryParse(s); return (n == null) ? false : true; }
0
mirrored_repositories/wallapop-app/lib/src
mirrored_repositories/wallapop-app/lib/src/providers/productos_provider.dart
import 'dart:convert'; import 'package:http/http.dart' as http; import 'package:form_validation_app/src/models/producto_model.dart'; class ProductosProvider { final String _url = 'https://wallapop-8d0ba.firebaseio.com'; Future<bool> crearProducto(ProductoModel producto) async { final url = '$_url/productos.json'; final resp = await http.post(url, body: productoModelToJson(producto)); final decodedData = json.decode(resp.body); print(decodedData); return true; } }
0
mirrored_repositories/sms-forwarder
mirrored_repositories/sms-forwarder/lib/api.dart
import 'dart:convert'; import 'package:SMSRouter/main.dart'; import 'package:SMSRouter/model/SmsPayload.dart'; import 'package:dio/dio.dart'; import 'package:flutter/services.dart'; import 'package:intl/intl.dart'; class Api { static Future<Response> submit(SmsPayload payload) async { final mapping = await rootBundle.loadString('assets/sms_mapping.json'); final url = jsonDecode(mapping)['api']; final response = await Dio().get(url, queryParameters: { 'date': DateFormat('yyyy-MM-dd HH:mm').format(payload.date), 'smsBody': payload.smsBody, 'transactionAmount': payload.transactionAmount, 'balance': payload.balance }); print(response.data); if (response.data['status'] == 'SUCCESS') { smsModel.add(payload); } return response; } }
0
mirrored_repositories/sms-forwarder
mirrored_repositories/sms-forwarder/lib/utils.dart
import 'package:intl/intl.dart'; class Utils { } extension FormatDate on DateTime { String get formatted { return DateFormat.yMd().add_jm().format(this); } }
0
mirrored_repositories/sms-forwarder
mirrored_repositories/sms-forwarder/lib/main.dart
import 'package:SMSRouter/api.dart'; import 'package:SMSRouter/model/Config.dart'; import 'package:SMSRouter/model/SmsPayload.dart'; import 'package:SMSRouter/utils.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_slidable/flutter_slidable.dart'; import 'package:intl/intl.dart'; import 'package:provider/provider.dart'; import 'package:sms_maintained/sms.dart'; void main() { runApp(MyApp()); SmsReceiver receiver = SmsReceiver(); receiver.onSmsReceived.listen((SmsMessage msg) async { final smsPayload = await SmsPayload.from(msg.body); if (smsPayload != null) { await Api.submit(smsPayload); smsModel.add(smsPayload); } }); } final globalKey = GlobalKey<NavigatorState>(); final smsModel = SmsModel(); final configModel = ConfigModel()..init(); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MultiProvider( providers: [ ChangeNotifierProvider(create: (_) => smsModel), ChangeNotifierProvider(create: (_) => configModel), ], child: MaterialApp( title: 'Sms Forwarder', navigatorKey: globalKey, theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Sms Forwarder'), ), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { @override void initState() { super.initState(); init(); } /// testing void init() async { final sms = await SmsPayload.from('xxxxxxx'); if (sms != null) { await Api.submit(sms); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Sms Forwarder', style: TextStyle(color: Colors.white)), backgroundColor: Colors.blue, brightness: Brightness.light, ), body: Container( color: Colors.white, child: Consumer<SmsModel>( builder: (context, model, child) { return ListView.builder( itemCount: model.payloads.length, itemBuilder: (BuildContext context, int index) { final payload = model.payloads[index]; return Slidable( actionPane: SlidableBehindActionPane(), actions: <Widget>[ IconSlideAction( caption: 'Delete', color: Colors.blue, icon: Icons.delete, onTap: () async { smsModel.remove(model.payloads[index]); }, ) ], key: UniqueKey(), dismissal: SlidableDismissal( child: SlidableDrawerDismissal(), onDismissed: (actionType) { smsModel.remove(model.payloads[index]); }, ), child: ListTile( title: Text('${payload.transactionAmount}'), subtitle: Text(payload.smsBody, maxLines: 2, overflow: TextOverflow.ellipsis,), trailing: Text(payload.date.formatted), ), ); }); }, ), ), floatingActionButton: FloatingActionButton( onPressed: () { Navigator.push(context, CupertinoPageRoute( builder: (_) => SmsList() )); }, tooltip: 'Manual edit', child: Icon(Icons.edit), ), // This trailing comma makes auto-formatting nicer for build methods. ); } } class SmsList extends StatefulWidget { @override _SmsListState createState() => _SmsListState(); } class _SmsListState extends State<SmsList> { @override Widget build(BuildContext context) { final smsQuery = SmsQuery(); return Scaffold( appBar: AppBar( title: const Text('SMS List', style: TextStyle(color: Colors.white)), backgroundColor: Colors.blue, brightness: Brightness.light, ), body: Material( child: FutureBuilder( future: smsQuery.querySms( kinds: [SmsQueryKind.Inbox], ), builder: (context, AsyncSnapshot<List<SmsMessage>> snapshot) { if (snapshot.hasData) { final smss = snapshot.data.where((sms) { return RegExp(r'' + configModel.config.transactionMoney + '').hasMatch(sms.body) && RegExp(r'' + configModel.config.balance + '').hasMatch(sms.body) && sms.address == configModel.config.senderAddress; }).toList(); print('Total length: ${smss.length}'); return ListView.builder( itemCount: smss.length, itemBuilder: (context, index) { final sent = Provider.of<SmsModel>(context).payloads.firstWhere((payload) => payload.smsBody == smss[index].body, orElse: () => null) == null; return InkWell( onTap: () {}, child: Slidable( actionPane: SlidableDrawerActionPane(), actions: <Widget>[ IconSlideAction( caption: 'Send', color: Colors.blue, icon: Icons.send, onTap: () async { await Api.submit(await SmsPayload.from(smss[index].body)); }, ), ], child: ListTile( title: Text( smss[index].body, maxLines: 2, overflow: TextOverflow.ellipsis,), subtitle: Text(smss[index].dateSent.formatted), trailing: sent ? Text('') : Icon(Icons.check_circle), ), ), ); } ); } return CircularProgressIndicator(); }, ), ), ); } }
0
mirrored_repositories/sms-forwarder/lib
mirrored_repositories/sms-forwarder/lib/model/Config.dart
import 'dart:convert'; import 'package:flutter/cupertino.dart'; import 'package:flutter/services.dart'; class ConfigModel with ChangeNotifier { ConfigModel() { init(); } Config _config = Config(); init() async { final mapping = await rootBundle.loadString('assets/sms_mapping.json'); final json = jsonDecode(mapping); this._config = Config.fromJson(json); } Config get config => _config; set config(Config config) { this.config = config; this.notifyListeners(); } } class Config { String api; String transactionMoney; String balance; String senderAddress; Config({this.api, this.transactionMoney, this.balance, this.senderAddress}); Config.fromJson(Map<String, dynamic> json) { api = json['api']; transactionMoney = json['transactionMoney']; balance = json['balance']; senderAddress = json['senderAddress']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['api'] = this.api; data['transactionMoney'] = this.transactionMoney; data['balance'] = this.balance; data['senderAddress'] = this.senderAddress; return data; } }
0
mirrored_repositories/sms-forwarder/lib
mirrored_repositories/sms-forwarder/lib/model/SmsPayload.dart
import 'dart:convert'; import 'package:SMSRouter/main.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/services.dart'; import 'package:shared_preferences/shared_preferences.dart'; class SmsModel with ChangeNotifier { SmsModel() { _init(); } void _init() async { final preferences = await SharedPreferences.getInstance(); List<String> payloads = preferences.getStringList(SmsPayload.savedKey); if (payloads != null) { this.payloads = payloads.map((str) => SmsPayload.fromJson(jsonDecode(str))).toList(); } } final List<SmsPayload> _payloads = []; List<SmsPayload> get payloads => _payloads; void add(SmsPayload payload) { _payloads.add(payload); notifyListeners(); save(); } void save() async { final prefs = await SharedPreferences.getInstance(); prefs.setStringList( SmsPayload.savedKey, _payloads.map((p) => jsonEncode(p.toJson())).toList()); } set payloads(List<SmsPayload> payloads) { this._payloads.addAll(payloads); this.notifyListeners(); save(); } void remove(SmsPayload payload) { _payloads.remove(payload); notifyListeners(); save(); } void removeAll() { _payloads.clear(); notifyListeners(); save(); } } class SmsPayload { DateTime date; String smsBody; String transactionAmount; String balance; SmsPayload(this.date, this.smsBody, this.transactionAmount, this.balance); SmsPayload._(); static String savedKey = 'smsPayloads'; /// Nullable static Future<SmsPayload> from(String sms) async { final mapping = await rootBundle.loadString('assets/sms_mapping.json'); final json = jsonDecode(mapping); final transactionRegex = json['transactionMoney']; final balanceRegex = json['balance']; final transactionMoney = RegExp(r'' + transactionRegex + '').firstMatch(sms)?.group(1); final balance = RegExp(r'' + balanceRegex + '').firstMatch(sms)?.group(1); if (transactionMoney == null || balance == null) return null; return SmsPayload(DateTime.now(), sms, transactionMoney, balance); } factory SmsPayload.fromJson(Map<String, dynamic> json) { return SmsPayload._() ..date = DateTime.parse(json['date']) ..smsBody = json['smsBody'] ..transactionAmount = json['transactionAmount'] ..balance = json['balance']; } Map<String, dynamic> toJson() { final Map<String, dynamic> data = new Map<String, dynamic>(); data['date'] = this.date.toUtc().toIso8601String(); data['smsBody'] = this.smsBody; data['transactionAmount'] = this.transactionAmount; data['balance'] = this.balance; return data; } String toParams() { return '?date=${date.toIso8601String()}&smsBody=$smsBody&transactionAmount=$transactionAmount&balance=$balance'; } }
0
mirrored_repositories/sms-forwarder
mirrored_repositories/sms-forwarder/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:SMSRouter/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/whatsgram
mirrored_repositories/whatsgram/lib/profile.dart
import 'package:flutter/material.dart'; class Profile extends StatefulWidget { @override _CallsState createState() => _CallsState(); } class _CallsState extends State<Profile> { @override Widget build(BuildContext context) { return Column( children: [ //Profile picture Padding( padding: const EdgeInsets.all(20.0), child: Stack( children: [ Center( child: CircleAvatar( radius: 80, backgroundImage: AssetImage('images/profile.JPG'), ), ), Padding( padding: const EdgeInsets.only(top: 110, left: 200.0), child: FloatingActionButton( backgroundColor: Colors.black, elevation: 0, mini: true, onPressed: () {}, child: Icon(Icons.camera_alt_rounded), ), ), ], ), ), //Preferences Column( children: [ ListTile( leading: Icon(Icons.person), title: Text( 'Name', style: TextStyle(fontWeight: FontWeight.bold), ), subtitle: Text('Joe'), trailing: Icon(Icons.edit), ), Divider( indent: 70, height: 5, ), ListTile( leading: Icon(Icons.info_outline), title: Text( 'About', style: TextStyle(fontWeight: FontWeight.bold), ), subtitle: Text('Doge is your best bet !'), trailing: Icon(Icons.edit), ), Divider( indent: 70, height: 5, ), ListTile( leading: Icon(Icons.call), title: Text( 'Phone', style: TextStyle(fontWeight: FontWeight.bold), ), subtitle: Text('+60 17269 0420'), ), Divider( indent: 70, height: 5, ) ], ), ], ); } }
0
mirrored_repositories/whatsgram
mirrored_repositories/whatsgram/lib/main.dart
import 'package:flutter/material.dart'; import 'package:Whatsgram/home.dart'; import 'package:Whatsgram/calls.dart'; import 'package:Whatsgram/profile.dart'; void main() { runApp(Whatsgram()); } class Whatsgram extends StatefulWidget { @override _WhatsgramState createState() => _WhatsgramState(); } class _WhatsgramState extends State<Whatsgram> { var appBarIcon; int currentIndex = 0; PageController _pageController = PageController(); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Whatsgram', theme: ThemeData(visualDensity: VisualDensity.adaptivePlatformDensity), home: Scaffold( appBar: AppBar( elevation: 0, title: Text( 'Whatsgram', style: TextStyle( color: Colors.black, fontSize: 33, fontWeight: FontWeight.normal, fontFamily: 'Billabong'), ), actions: [ IconButton( onPressed: null, icon: Icon( appBarIcon, color: Colors.black, ), ), IconButton( onPressed: null, icon: Icon( Icons.more_vert, color: Colors.black, ), ), ], backgroundColor: Colors.grey[50], ), body: PageView( controller: _pageController, onPageChanged: (value) { setState(() { currentIndex = value; //changing AppBar dynamically on different pages switch (currentIndex) { case 0: { appBarIcon = Icons.search; } break; case 1: { appBarIcon = Icons.add_call; } break; case 2: { appBarIcon = null; } } }); }, children: [ Home(), Calls(), Profile(), ], ), bottomNavigationBar: BottomNavigationBar( showSelectedLabels: false, showUnselectedLabels: false, currentIndex: currentIndex, onTap: (value) { currentIndex = value; _pageController.jumpToPage(value); }, items: const <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: Icon(Icons.chat), label: 'Chat', ), BottomNavigationBarItem( icon: Icon(Icons.call), label: 'Call', ), BottomNavigationBarItem( icon: Icon(Icons.person_pin), label: 'Profile', ), ], selectedItemColor: Colors.black, ), ), ); } }
0
mirrored_repositories/whatsgram
mirrored_repositories/whatsgram/lib/home.dart
import 'package:flutter/material.dart'; import 'dart:math'; class Home extends StatefulWidget { @override _HomeState createState() => _HomeState(); } class _HomeState extends State<Home> { // close contacts list List<String> contacts = [ "Eilie Billish", "Zark Muckberg", "Kan Joum", "Sevin Kystrom", "Yang Zhiming", "Woni Tatson", "Cack Jonte" ]; // image locations List<String> images = [ "images/billie.png", "images/mark.jpg", "images/jan.jpg", "images/kevin.jpg", "images/zhang.jpg", "images/toni.jpg", "images/jack.jpg", ]; // chat text List<String> chat = [ "I'm the bad guy", "Should we buy TikTok ?", "I shouldn't have sold", "Alls well that ends well", "I'm not sure what his intentions are", "Now i beg to see you dance just one more time", "Link is in the description", ]; @override Widget build(BuildContext context) { return Column( children: [ Container( height: 100, color: Colors.grey[50], child: Row( children: [ Column( children: [ Padding( padding: EdgeInsets.only( top: 10, left: 10, right: 10, bottom: 5), //Layering Circle Avatars to achieve the gradient bordered stories child: CircleAvatar( radius: 35, backgroundColor: Colors.grey, child: CircleAvatar( radius: 33, backgroundColor: Colors.grey[50], child: CircleAvatar( radius: 31, child: Icon( Icons.group_add_outlined, color: Colors.white, size: 30, ), backgroundColor: Colors.grey, ), ), ), ), Container( width: 90, child: Center( child: Text( 'Pinned Contacts', style: TextStyle(fontSize: 11), overflow: TextOverflow.ellipsis, ), ), ) ], ), //Close Contacts stories Expanded( child: ListView.builder( reverse: true, scrollDirection: Axis.horizontal, itemCount: contacts.length, itemBuilder: (context, index) { return Column( children: [ Padding( padding: EdgeInsets.only( top: 10, left: 10, right: 10, bottom: 5), //Layering Circle Avatars to achieve the gradient bordered stories child: CircleAvatar( radius: 35, backgroundColor: Colors.green, child: CircleAvatar( radius: 33, backgroundColor: Colors.grey[50], child: CircleAvatar( radius: 31, backgroundImage: AssetImage(images[index]), ), ), ), ), Container( width: 80, child: Center( child: Text( contacts[index], style: TextStyle(fontSize: 11), overflow: TextOverflow.ellipsis, ), ), ) ], ); }), ), ], ), ), //Chat containers Expanded( child: ListView.builder( itemCount: contacts.length, itemBuilder: (context, index) { return Column( children: [ ListTile( leading: SizedBox( height: 60, width: 60, child: CircleAvatar( radius: 60, backgroundImage: AssetImage(images[index]), ), ), title: Padding( padding: const EdgeInsets.only(top: 8.0), child: Text( contacts[index], style: TextStyle(fontWeight: FontWeight.bold), ), ), subtitle: Padding( padding: const EdgeInsets.only(top: 2.0, bottom: 8.0), child: Text(chat[index]), ), trailing: Column( children: [ Text( '12:23 am', style: TextStyle(fontSize: 11, color: Colors.grey), ), SizedBox( height: 8, ), Container( height: 20, width: 20, decoration: BoxDecoration( color: Colors.green, shape: BoxShape.circle), child: Center( child: Text( (Random().nextInt(6) + 1).toString(), style: TextStyle( color: Colors.white, fontSize: 10))), ), ], ), ), Divider( indent: 90, height: 5, ) ], ); }), ), ], ); } }
0
mirrored_repositories/whatsgram
mirrored_repositories/whatsgram/lib/calls.dart
import 'package:flutter/material.dart'; import 'dart:math'; class Calls extends StatefulWidget { @override _CallsState createState() => _CallsState(); } class _CallsState extends State<Calls> { //close contacts list List<String> contacts = [ "Eilie Billish", "Zark Muckberg", "Kan Joum", "Sevin Kystrom", "Yang Zhiming", "Woni Tatson", "Cack Jonte" ]; //image locations List<String> images = [ "images/billie.png", "images/mark.jpg", "images/jan.jpg", "images/kevin.jpg", "images/zhang.jpg", "images/toni.jpg", "images/jack.jpg", ]; @override Widget build(BuildContext context) { return Expanded( child: ListView.builder( itemCount: contacts.length, itemBuilder: (context, index) { return Column( children: [ ListTile( // Profile image leading: SizedBox( height: 60, width: 60, child: CircleAvatar( radius: 50, backgroundImage: AssetImage(images[index]), ), ), // Contact name title: Text( contacts[index], style: TextStyle(fontWeight: FontWeight.bold), ), // Last called time subtitle: Row( children: [ Padding( padding: const EdgeInsets.only(right: 8.0), child: Icon( Icons.call_made_rounded, size: 18, ), ), Text((Random().nextInt(10) + 1).toString() + " minutes ago"), ], ), trailing: Icon(Icons.call), ), Divider( indent: 90, height: 5, ) ], ); }), ); } }
0
mirrored_repositories/fu_uber
mirrored_repositories/fu_uber/lib/main.dart
import 'package:flutter/material.dart'; import 'package:fu_uber/Core/ProviderModels/CurrentRideCreationModel.dart'; import 'package:fu_uber/Core/ProviderModels/MapModel.dart'; import 'package:fu_uber/Core/ProviderModels/NearbyDriversModel.dart'; import 'package:fu_uber/Core/ProviderModels/PermissionHandlerModel.dart'; import 'package:fu_uber/Core/ProviderModels/RideBookedModel.dart'; import 'package:fu_uber/Core/ProviderModels/UINotifiersModel.dart'; import 'package:fu_uber/Core/ProviderModels/UserDetailsModel.dart'; import 'package:fu_uber/Core/ProviderModels/VerificationModel.dart'; import 'package:fu_uber/UI/views/LocationPermissionScreen.dart'; import 'package:fu_uber/UI/views/MainScreen.dart'; import 'package:fu_uber/UI/views/OnGoingRideScreen.dart'; import 'package:fu_uber/UI/views/ProfileScreen.dart'; import 'package:fu_uber/UI/views/SignIn.dart'; import 'package:provider/provider.dart'; void main() => runApp(MyApp()); final GlobalKey<NavigatorState> navigatorKey = new GlobalKey<NavigatorState>(); class MyApp extends StatelessWidget { static const String TAG = "MyApp"; // This widget is the root of your application. @override Widget build(BuildContext context) { return MultiProvider( providers: [ ChangeNotifierProvider<PermissionHandlerModel>( builder: (context) => PermissionHandlerModel(), ), ChangeNotifierProvider<MapModel>( builder: (context) => MapModel(), ), ChangeNotifierProxyProvider<MapModel, RideBookedModel>( initialBuilder: (_) => RideBookedModel(), builder: (_, foo, bar) { bar.originLatLng = foo.pickupPosition; bar.destinationLatLng = foo.destinationPosition; return bar; }), ChangeNotifierProvider<VerificationModel>( builder: (context) => VerificationModel(), ), ChangeNotifierProvider<NearbyDriversModel>( builder: (context) => NearbyDriversModel(), ), ChangeNotifierProvider<UserDetailsModel>( builder: (context) => UserDetailsModel(), ), ChangeNotifierProvider<CurrentRideCreationModel>( builder: (context) => CurrentRideCreationModel(), ), ChangeNotifierProvider<UINotifiersModel>( builder: (context) => UINotifiersModel(), ) ], child: MaterialApp( title: 'Fu_Uber', theme: ThemeData( primarySwatch: Colors.blue, ), navigatorKey: navigatorKey, initialRoute: '/', routes: { LocationPermissionScreen.route: (context) => LocationPermissionScreen(), MainScreen.route: (context) => MainScreen(), SignInPage.route: (context) => SignInPage(), ProfileScreen.route: (context) => ProfileScreen(), OnGoingRideScreen.route: (context) => OnGoingRideScreen() }, home: Scaffold(body: LocationPermissionScreen())), ); } }
0
mirrored_repositories/fu_uber/lib/Core
mirrored_repositories/fu_uber/lib/Core/ProviderModels/NearbyDriversModel.dart
import 'dart:async'; import 'package:flutter/widgets.dart'; import 'package:fu_uber/Core/Models/Drivers.dart'; import 'package:fu_uber/Core/Repository/Repository.dart'; class NearbyDriversModel extends ChangeNotifier { List<Driver> nearbyDrivers; final nearbyDriverStreamController = StreamController<List<Driver>>(); get nearbyDriverList => nearbyDrivers; Stream<List<Driver>> get dataStream => nearbyDriverStreamController.stream; NearbyDriversModel() { //We will be listening to the nearbyDrivers events like, there location Updates etc. //using streams maybe.. Repository.getNearbyDrivers(nearbyDriverStreamController); dataStream.listen((list) { nearbyDrivers = list; notifyListeners(); }); } void closeStream() { nearbyDriverStreamController.close(); } }
0
mirrored_repositories/fu_uber/lib/Core
mirrored_repositories/fu_uber/lib/Core/ProviderModels/CurrentRideCreationModel.dart
import 'package:flutter/material.dart'; import 'package:fu_uber/Core/Enums/Enums.dart'; class CurrentRideCreationModel extends ChangeNotifier { RideType selectedRideType; bool riderFound = false; CurrentRideCreationModel() { selectedRideType = RideType.Classic; } String getEstimationFromOriginDestination() { return "200"; } carTypeChanged(int index) { selectedRideType = RideType.values[index]; notifyListeners(); } searchForRides() { Future.delayed(Duration(seconds: 5), () { riderFound = true; notifyListeners(); }); } }
0
mirrored_repositories/fu_uber/lib/Core
mirrored_repositories/fu_uber/lib/Core/ProviderModels/PermissionHandlerModel.dart
import 'package:flutter/cupertino.dart'; import 'package:location/location.dart'; class PermissionHandlerModel extends ChangeNotifier { Location location = Location(); bool isLocationPerGiven = false; bool isLocationSerGiven = false; PermissionHandlerModel() { location.changeSettings(accuracy: LocationAccuracy.LOW); location.hasPermission().then((isGiven) { if (isGiven) { isLocationPerGiven = true; location.serviceEnabled().then((isEnabled) { if (isEnabled) { isLocationSerGiven = true; } else { isLocationSerGiven = false; } notifyListeners(); }); } else { isLocationPerGiven = false; } notifyListeners(); }); } Future<bool> checkAppLocationGranted() { return location.hasPermission(); } requestAppLocationPermission() { location.requestPermission().then((isGiven) { isLocationPerGiven = isGiven; notifyListeners(); }); } Future<bool> checkLocationServiceEnabled() { return location.serviceEnabled(); } requestLocationServiceToEnable() { location.requestService().then((isGiven) { isLocationSerGiven = isGiven; notifyListeners(); }); } }
0
mirrored_repositories/fu_uber/lib/Core
mirrored_repositories/fu_uber/lib/Core/ProviderModels/VerificationModel.dart
import 'package:flutter/cupertino.dart'; import 'package:fu_uber/Core/Enums/Enums.dart'; import 'package:fu_uber/Core/Repository/Repository.dart'; class VerificationModel extends ChangeNotifier { String phoneNumber; String otp; bool ifOtpHasError = true; bool showCircularLoader = false; bool shopCircularLoaderOTP = false; updateCircularLoading(bool b) { showCircularLoader = b; notifyListeners(); } TextEditingController oTPTextController = TextEditingController(); setPhoneNumber(String phone) { phoneNumber = phone; notifyListeners(); } setOtp(String otpp) { otp = otpp; notifyListeners(); } Future<AuthStatus> isUserAlreadyAuthenticated() async { return await Repository.isUserAlreadyAuthenticated(); } Future<int> handlePhoneVerification() async { return await Repository.sendOTP(phoneNumber); } Future<int> oTPVerification() async { return await Repository.verifyOtp(otp); } void updateCircularLoadingOtp(bool param0) { shopCircularLoaderOTP = param0; notifyListeners(); } }
0
mirrored_repositories/fu_uber/lib/Core
mirrored_repositories/fu_uber/lib/Core/ProviderModels/UINotifiersModel.dart
import 'package:flutter/widgets.dart'; import 'package:sliding_up_panel/sliding_up_panel.dart'; class UINotifiersModel extends ChangeNotifier { double originDestinationVisibility = 1; bool isPanelOpen = false; bool isPanelScrollDisabled = true; bool searchingRide = false; ScrollController sheetScrollController = ScrollController(); PanelController panelController = PanelController(); UINotifiersModel() { sheetScrollController.addListener(() { if (sheetScrollController.offset <= 1.0) { disablePanelScroll(); } else enablePanelScroll(); }); } setOriginDestinationVisibility(double visibility) { visibility = (visibility - 1); if (visibility < 0) visibility *= -1; originDestinationVisibility = visibility; notifyListeners(); } disablePanelScroll() { isPanelScrollDisabled = true; isPanelOpen = false; notifyListeners(); } enablePanelScroll() { isPanelScrollDisabled = false; notifyListeners(); } onPanelOpen() { isPanelOpen = true; notifyListeners(); } onPanelClosed() { isPanelOpen = false; notifyListeners(); } void searchingRideNotify() { //closes the panel panelController.close(); // it hides the panel, so that we wont be able to use it for time if (!searchingRide) panelController.hide(); else panelController.show(); searchingRide = !searchingRide; notifyListeners(); } }
0
mirrored_repositories/fu_uber/lib/Core
mirrored_repositories/fu_uber/lib/Core/ProviderModels/RideBookedModel.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:fu_uber/Core/Constants/Constants.dart'; import 'package:fu_uber/Core/Constants/DemoData.dart'; import 'package:fu_uber/Core/Constants/colorConstants.dart'; import 'package:fu_uber/Core/Enums/Enums.dart'; import 'package:fu_uber/Core/Models/Drivers.dart'; import 'package:fu_uber/Core/Repository/mapRepository.dart'; import 'package:fu_uber/Core/Utils/LogUtils.dart'; import 'package:fu_uber/Core/Utils/Utils.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; class RideBookedModel extends ChangeNotifier { /// Tag for Logs static const TAG = "MapModel"; GoogleMapController _mapController; MapRepository mapRepository = MapRepository(); /// Origin Latitude and Longitude LatLng originLatLng; /// Destination Latitude and Longitude LatLng destinationLatLng; /// Default Camera Zoom double currentZoom = 19; Driver currentDriver = DemoData.nearbyDrivers[1]; DriverStatus driverStatus = DriverStatus.OnWay; LatLng driverLatLng = DemoData.nearbyDrivers[1].currentLocation; /// Set of all the markers on the map final Set<Marker> _markers = Set(); /// Set of all the polyLines/routes on the map final Set<Polyline> _polyLines = Set(); /// Markers Getter get markers => _markers; /// PolyLines Getter. get polyLines => _polyLines; String rideStatusAsText = "Driver enRoute"; int timeLeftToReach = 10; /// OnGoing Map onMapCreated(GoogleMapController controller) { ProjectLog.logIt(TAG, "onMapCreated", "null"); _mapController = controller; rootBundle.loadString('assets/mapStyle.txt').then((string) { _mapController.setMapStyle(string); }); listenToRideLocationUpdate(); addAllMarkers(); createOriginDestinationRoute(); createOriginDriverLocationRoute(); notifyListeners(); } /// On Camera Moved onCameraMove(CameraPosition position) {} void createOriginDestinationRoute() async { await mapRepository .getRouteCoordinates(originLatLng, destinationLatLng) .then((route) { createCurrentRoute(route, Constants.currentRoutePolylineId, ConstantColors.PrimaryColor, 3); notifyListeners(); }); } void createOriginDriverLocationRoute() async { await mapRepository .getRouteCoordinates(originLatLng, driverLatLng) .then((route) { createCurrentRoute(route, Constants.driverOriginPolyId, Colors.green, 5); notifyListeners(); }); } ///Creating a Route void createCurrentRoute(String encodedPoly, String polyId, Color color, int width) { ProjectLog.logIt(TAG, "createCurrentRoute", encodedPoly); _polyLines.add(Polyline( polylineId: PolylineId(polyId), width: width, geodesic: true, points: Utils.convertToLatLng(Utils.decodePoly(encodedPoly)), color: color)); notifyListeners(); } void addAllMarkers() async { _markers.add(Marker( markerId: MarkerId(Constants.pickupMarkerId), position: originLatLng, flat: true, icon: BitmapDescriptor.fromBytes( await Utils.getBytesFromAsset("images/pickupIcon.png", 70), ))); _markers.add(Marker( markerId: MarkerId(Constants.destinationMarkerId), position: destinationLatLng, flat: true, icon: BitmapDescriptor.fromBytes( await Utils.getBytesFromAsset("images/destinationIcon.png", 70), ))); /// for now we have added the single marker _markers.add(Marker( markerId: MarkerId(Constants.driverMarkerId), position: DemoData.nearbyDrivers[2].currentLocation, //taking demo data flat: true, icon: BitmapDescriptor.fromBytes( await Utils.getBytesFromAsset("images/carIcon.png", 60), ))); notifyListeners(); } void listenToRideLocationUpdate() { /// We will be listening to drivers location update and update here accordingly, /// like we did in the users current location update. Future.delayed(Duration(seconds: 20), () { driverStatus = DriverStatus.Reached; notifyListeners(); }); } }
0
mirrored_repositories/fu_uber/lib/Core
mirrored_repositories/fu_uber/lib/Core/ProviderModels/MapModel.dart
import 'dart:math'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:fu_uber/Core/Constants/Constants.dart'; import 'package:fu_uber/Core/Constants/DemoData.dart'; import 'package:fu_uber/Core/Constants/colorConstants.dart'; import 'package:fu_uber/Core/Models/Drivers.dart'; import 'package:fu_uber/Core/Repository/mapRepository.dart'; import 'package:fu_uber/Core/Utils/LogUtils.dart'; import 'package:fu_uber/Core/Utils/Utils.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'package:google_maps_webservice/places.dart'; import 'package:location/location.dart' as location; /// A viewModel kind of class for handling Map related information and updating. /// We are using Provider with notifyListeners() for the sake of simplicity but will update with dynamic approach /// Provider : https://pub.dev/packages/provider class MapModel extends ChangeNotifier { final mapScreenScaffoldKey = GlobalKey<ScaffoldState>(); // Tag for Logs static const TAG = "MapModel"; //Current Position and Destination Position and Pickup Point LatLng _currentPosition, _destinationPosition, _pickupPosition; // Default Camera Zoom double currentZoom = 19; // Set of all the markers on the map final Set<Marker> _markers = Set(); // Set of all the polyLines/routes on the map final Set<Polyline> _polyLines = Set(); // Pickup Predictions using Places Api, It is the list of Predictions we get from the textchanges the PickupText field in the mainScreen List<Prediction> pickupPredictions = []; //Same as PickupPredictions but for destination TextField in mainScreen List<Prediction> destinationPredictions = []; //Map Controller GoogleMapController _mapController; // Map Repository for connection to APIs MapRepository _mapRepository = MapRepository(); // FormField Controller for the pickup field TextEditingController pickupFormFieldController = TextEditingController(); // FormField Controller for the destination field TextEditingController destinationFormFieldController = TextEditingController(); // Location Object to get current Location location.Location _location = location.Location(); // currentPosition Getter LatLng get currentPosition => _currentPosition; // currentPosition Getter LatLng get destinationPosition => _destinationPosition; // currentPosition Getter LatLng get pickupPosition => _pickupPosition; // MapRepository Getter MapRepository get mapRepo => _mapRepository; // MapController Getter GoogleMapController get mapController => _mapController; // Markers Getter Set<Marker> get markers => _markers; // PolyLines Getter Set<Polyline> get polyLines => _polyLines; get randomZoom => 13.0 + Random().nextInt(4); /// Default Constructor MapModel() { ProjectLog.logIt(TAG, "MapModel Constructor", "..."); //getting user Current Location _getUserLocation(); fetchNearbyDrivers(DemoData.nearbyDrivers); //A listener on _location to always get current location and update it. _location.onLocationChanged().listen((event) async { _currentPosition = LatLng(event.latitude, event.longitude); markers.removeWhere((marker) { return marker.markerId.value == Constants.currentLocationMarkerId; }); markers.remove( Marker(markerId: MarkerId(Constants.currentLocationMarkerId))); markers.add(Marker( markerId: MarkerId(Constants.currentLocationMarkerId), position: _currentPosition, rotation: event.heading - 78, flat: true, anchor: Offset(0.5, 0.5), icon: BitmapDescriptor.fromBytes( await Utils.getBytesFromAsset("images/currentUserIcon.png", 280), ))); notifyListeners(); }); } ///Callback whenever data in Pickup TextField is changed ///onChanged() onPickupTextFieldChanged(String string) async { ProjectLog.logIt(TAG, "onPickupTextFieldChanged", string); if (string.isEmpty) { pickupPredictions = null; } else { try { await mapRepo.getAutoCompleteResponse(string).then((response) { updatePickupPointSuggestions(response.predictions); ProjectLog.logIt( TAG, "UpdatePickupPredictions", response.predictions.toString()); }); } catch (e) { print(e); } } } ///Callback whenever data in destination TextField is changed ///onChanged() onDestinationTextFieldChanged(String string) async { ProjectLog.logIt(TAG, "onDestinationTextFieldChanged", string); if (string.isEmpty) { destinationPredictions = null; } else { try { await mapRepo.getAutoCompleteResponse(string).then((response) { updateDestinationSuggestions(response.predictions); ProjectLog.logIt(TAG, "UpdateDestinationPredictions", response.predictions.toString()); }); } catch (e) { print(e); } } } ///Getting current Location : Works only one time void _getUserLocation() async { ProjectLog.logIt(TAG, "getUserCurrentLocation", "..."); _location.getLocation().then((data) async { _currentPosition = LatLng(data.latitude, data.longitude); _pickupPosition = _currentPosition; ProjectLog.logIt( TAG, "Initial Position is ", _currentPosition.toString()); pickupFormFieldController.text = await mapRepo .getPlaceNameFromLatLng(LatLng(data.latitude, data.longitude)); updatePickupMarker(); notifyListeners(); }); } ///Creating a Route void createCurrentRoute(String encodedPoly) { ProjectLog.logIt(TAG, "createCurrentRoute", encodedPoly); _polyLines.add(Polyline( polylineId: PolylineId(Constants.currentRoutePolylineId), width: 3, geodesic: true, points: Utils.convertToLatLng(Utils.decodePoly(encodedPoly)), color: ConstantColors.PrimaryColor)); notifyListeners(); } ///Adding or updating Destination Marker on the Map updateDestinationMarker() async { if (destinationPosition == null) return; ProjectLog.logIt( TAG, "updateDestinationMarker", destinationPosition.toString()); markers.add(Marker( markerId: MarkerId(Constants.destinationMarkerId), position: destinationPosition, draggable: true, onDragEnd: onDestinationMarkerDragged, anchor: Offset(0.5, 0.5), icon: BitmapDescriptor.fromBytes( await Utils.getBytesFromAsset("images/destinationIcon.png", 80)))); notifyListeners(); } ///Adding or updating Destination Marker on the Map updatePickupMarker() async { if (pickupPosition == null) return; ProjectLog.logIt(TAG, "updatePickupMarker", pickupPosition.toString()); _markers.add(Marker( markerId: MarkerId(Constants.pickupMarkerId), position: pickupPosition, draggable: true, onDragEnd: onPickupMarkerDragged, anchor: Offset(0.5, 0.5), icon: BitmapDescriptor.fromBytes( await Utils.getBytesFromAsset("images/pickupIcon.png", 80)))); notifyListeners(); } ///Updating Pickup Suggestions updatePickupPointSuggestions(List<Prediction> predictions) { ProjectLog.logIt( TAG, "updatePickupPointSuggestions", predictions.toString()); pickupPredictions = predictions; notifyListeners(); } ///Updating Destination updateDestinationSuggestions(List<Prediction> predictions) { ProjectLog.logIt( TAG, "updateDestinationSuggestions", predictions.toString()); destinationPredictions = predictions; notifyListeners(); } ///on Destination predictions item clicked onDestinationPredictionItemClick(Prediction prediction) async { updateDestinationSuggestions(null); ProjectLog.logIt( TAG, "onDestinationPredictionItemClick", prediction.description); destinationFormFieldController.text = prediction.description; _destinationPosition = await mapRepo.getLatLngFromAddress(prediction.description); onDestinationPositionChanged(); notifyListeners(); } ///on Pickup predictions item clicked onPickupPredictionItemClick(Prediction prediction) async { updatePickupPointSuggestions(null); ProjectLog.logIt( TAG, "onPickupPredictionItemClick", prediction.description); pickupFormFieldController.text = prediction.description; _pickupPosition = await mapRepo.getLatLngFromAddress(prediction.description); onPickupPositionChanged(); notifyListeners(); } // ! SEND REQUEST void sendRouteRequest() async { ProjectLog.logIt(TAG, "sendRouteRequest", "..."); if (_pickupPosition == null) { pickupFormFieldController.text = "This is required"; return; } else if (_destinationPosition == null) { destinationFormFieldController.text = "This is required"; return; } await mapRepo .getRouteCoordinates(_pickupPosition, _destinationPosition) .then((route) { createCurrentRoute(route); notifyListeners(); }); } /// listening to camera moving event void onCameraMove(CameraPosition position) { //ProjectLog.logIt(TAG, "onCameraMove", position.target.toString()); currentZoom = position.zoom; notifyListeners(); } /// when map is created void onMapCreated(GoogleMapController controller) { ProjectLog.logIt(TAG, "onMapCreated", "null"); _mapController = controller; rootBundle.loadString('assets/mapStyle.txt').then((string) { _mapController.setMapStyle(string); }); notifyListeners(); } bool checkDestinationOriginForNull() { if (pickupPosition == null || destinationPosition == null) return false; else return true; } void randomMapZoom() { mapController .animateCamera(CameraUpdate.zoomTo(15.0 + Random().nextInt(5))); } void onMyLocationFabClicked() { // check if ride is ongoing or not, if not that show current position // else we will show the camera at the mid point of both locations ProjectLog.logIt(TAG, "Moving to Current Position", "..."); mapController.animateCamera(CameraUpdate.newLatLngZoom( currentPosition, 15.0 + Random().nextInt(4))); //its overriding the above statement of zoom. beware //randomMapZoom(); } void fetchNearbyDrivers(List<Driver> list) { if (list != null && list.isNotEmpty) list.forEach((driver) async { markers.add(Marker( markerId: MarkerId(driver.driverId), infoWindow: InfoWindow(title: driver.carDetail.carCompanyName), position: driver.currentLocation, anchor: Offset(0.5, 0.5), icon: BitmapDescriptor.fromBytes( await Utils.getBytesFromAsset("images/carIcon.png", 80)))); notifyListeners(); }); } void onDestinationPositionChanged() { updateDestinationMarker(); mapController.animateCamera( CameraUpdate.newLatLngZoom(destinationPosition, randomZoom)); if (pickupPosition != null) sendRouteRequest(); notifyListeners(); } void onPickupPositionChanged() { updatePickupMarker(); mapController .animateCamera(CameraUpdate.newLatLngZoom(pickupPosition, randomZoom)); if (destinationPosition != null) sendRouteRequest(); notifyListeners(); } void onPickupMarkerDragged(LatLng value) async { _pickupPosition = value; pickupFormFieldController.text = await mapRepo.getPlaceNameFromLatLng(value); onPickupPositionChanged(); notifyListeners(); } void onDestinationMarkerDragged(LatLng latLng) async { _destinationPosition = latLng; destinationFormFieldController.text = await mapRepo.getPlaceNameFromLatLng(latLng); onDestinationPositionChanged(); notifyListeners(); } void panelIsOpened() { if (checkDestinationOriginForNull()) { animateCameraForOD(); } else { //Following statement is creating unnecessary zooms. maybe because panelIsOpened is called on every gesture. //randomMapZoom(); } } void animateCameraForOD() { mapController.animateCamera( CameraUpdate.newLatLngBounds( LatLngBounds( northeast: pickupPosition, southwest: destinationPosition), 100), ); } void panelIsClosed() { onMyLocationFabClicked(); } }
0
mirrored_repositories/fu_uber/lib/Core
mirrored_repositories/fu_uber/lib/Core/ProviderModels/UserDetailsModel.dart
import 'package:flutter/cupertino.dart'; import 'package:fu_uber/Core/Constants/DemoData.dart'; import 'package:fu_uber/Core/Models/UserDetails.dart'; import 'package:fu_uber/Core/Models/UserPlaces.dart'; import 'package:fu_uber/Core/Repository/Repository.dart'; class UserDetailsModel extends ChangeNotifier { String uuid; String photoUrl; String name; String email; String phone; String ongoingRide; List<String> previousRides; List<UserPlaces> favouritePlaces; UserDetailsModel() { UserDetails userDetails = DemoData.currentUserDetails; uuid = userDetails.uuid; photoUrl = userDetails.photoUrl; name = userDetails.name; email = userDetails.email; phone = userDetails.phone; ongoingRide = userDetails.ongoingRide; previousRides = userDetails.previousRides; favouritePlaces = userDetails.favouritePlaces; } setStaticData(UserDetails userDetails) {} changeName(String newName) {} addToFavouritePlace(UserPlaces userPlaces) { if (favouritePlaces.length >= 5) { favouritePlaces.insert(0, userPlaces); favouritePlaces.removeLast(); } else { favouritePlaces.add(userPlaces); } Repository.addFavPlacesToDataBase(favouritePlaces); notifyListeners(); } }
0
mirrored_repositories/fu_uber/lib/Core
mirrored_repositories/fu_uber/lib/Core/Constants/DemoData.dart
import 'package:fu_uber/Core/Enums/Enums.dart'; import 'package:fu_uber/Core/Models/CarTypeMenu.dart'; import 'package:fu_uber/Core/Models/Drivers.dart'; import 'package:fu_uber/Core/Models/UserDetails.dart'; import 'package:fu_uber/Core/Models/UserPlaces.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; class DemoData { static List<Driver> nearbyDrivers = [ Driver( "First", "https://cbsnews2.cbsistatic.com/hub/i/r/2017/12/20/205852a8-1105-48b5-98d4-d9ec18a577e0/thumbnail/1200x630/8cb0b627b158660d1e0a681a76fb012c/uber-europe-uk-851372958.jpg", 4, "FirstId", CarDetail( "firstCarId", "firstCarCompany", "firstCarModel", " firstCarName"), LatLng(28.625511, 77.374204)), Driver( "Second", "https://cbsnews2.cbsistatic.com/hub/i/r/2017/12/20/205852a8-1105-48b5-98d4-d9ec18a577e0/thumbnail/1200x630/8cb0b627b158660d1e0a681a76fb012c/uber-europe-uk-851372958.jpg", 3, "Second", CarDetail("secondCarId", "secondCarCompany", "secondCarModel", " secondCarName"), LatLng(28.623948, 77.373394)), Driver( "Third", "https://cbsnews2.cbsistatic.com/hub/i/r/2017/12/20/205852a8-1105-48b5-98d4-d9ec18a577e0/thumbnail/1200x630/8cb0b627b158660d1e0a681a76fb012c/uber-europe-uk-851372958.jpg", 4, "ThirdId", CarDetail( "thirdCarId", "thirdCarCompany", "thirdCarModel", " thridCarName"), LatLng(28.624372, 77.374220)), ]; static List<String> previousRides = [ "dsgffdsgdsagfds", "fdsafdsafas", "fdsafasffasd" ]; static List<UserPlaces> favPlaces = [ UserPlaces( "India Gate", "India Gate, New Delhi", LatLng(28.612912, 77.227321)), UserPlaces( "fdsagdsa rewfw", "nfdsbf, New Delhi", LatLng(29.612912, 70.227321)), UserPlaces( "dsagasdsa", "kldnwkvn, New Delhi", LatLng(22.612912, 70.227321)), UserPlaces( "dsafagdgg", "wqkjegcq, New Delhi", LatLng(38.612912, 67.227321)), UserPlaces( "jdskdsaksasaf", "cqucqjuwq, New Delhi", LatLng(28.012912, 77.297321)), ]; static UserDetails currentUserDetails = UserDetails( "FDSfdfdsafFtt324sdf", "https://i.pinimg.com/originals/61/36/8f/61368f9b0c3b7fcd22a4a1fbd4c28864.jpg", "Sahdeep Singh", "[email protected]", "0123456789", null, previousRides, favPlaces); static List<CarTypeMenu> typesOfCar = [ CarTypeMenu("images/affordableCarIcon.png", "Affordable Car in Budget", RideType.Affordable), CarTypeMenu("images/classicCarIcon.png", "Classic Car for your daily Commute ", RideType.Classic), CarTypeMenu("images/sedanCarIcon.png", " Car with extra leg Space and Storage", RideType.Sedan), CarTypeMenu("images/suvCarIcon.png", " Suv's for travelling with big Family", RideType.Suv), CarTypeMenu("images/luxuryCarIcon.png", "Luxury Cars for any occasion", RideType.Luxury), ]; }
0
mirrored_repositories/fu_uber/lib/Core
mirrored_repositories/fu_uber/lib/Core/Constants/Constants.dart
class Constants { static const mapApiKey = "add your api key"; static const anotherApiKey = "add your api key"; static const destinationMarkerId = "DestinationMarker"; static const pickupMarkerId = "PickupMarker"; static const currentLocationMarkerId = "currentLocationMarker"; static const currentRoutePolylineId = "currentRoutePolyline"; static const driverMarkerId = "CurrentDriverMarker"; static const driverOriginPolyId = "driverOriginPolyLine"; }
0
mirrored_repositories/fu_uber/lib/Core
mirrored_repositories/fu_uber/lib/Core/Constants/colorConstants.dart
import 'package:flutter/cupertino.dart'; class ConstantColors { static const Color PrimaryColor = Color(0xff656d74); static const Color ActivePink = Color(0xfffb376a); static const Color DeepBlue = Color(0xff13034d); }
0
mirrored_repositories/fu_uber/lib/Core
mirrored_repositories/fu_uber/lib/Core/Preferences/AuthPrefs.dart
class AuthPrefs {}
0
mirrored_repositories/fu_uber/lib/Core
mirrored_repositories/fu_uber/lib/Core/Utils/BasicShapeUtils.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class ShapeUtils { static BorderRadiusGeometry borderRadiusGeometry = BorderRadius.only( topLeft: Radius.circular(24.0), topRight: Radius.circular(24.0), ); static RoundedRectangleBorder selectedCardShape = RoundedRectangleBorder( side: new BorderSide(color: Colors.grey, width: 2.0), borderRadius: BorderRadius.circular(4.0)); static RoundedRectangleBorder notSelectedCardShape = RoundedRectangleBorder( side: new BorderSide(color: Colors.white, width: 2.0), borderRadius: BorderRadius.circular(4.0)); static RoundedRectangleBorder rounderCard = RoundedRectangleBorder( borderRadius: BorderRadius.circular(10.0)); }
0
mirrored_repositories/fu_uber/lib/Core
mirrored_repositories/fu_uber/lib/Core/Utils/LogUtils.dart
class ProjectLog { static void logIt(String className, String heading, dynamic data) { print(className + " with " + heading + " : ${data}"); } }
0
mirrored_repositories/fu_uber/lib/Core
mirrored_repositories/fu_uber/lib/Core/Utils/Utils.dart
import 'dart:typed_data'; import 'dart:ui'; import 'package:flutter/services.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; class Utils { // !DECODE POLY static List decodePoly(String poly) { var list = poly.codeUnits; var lList = new List(); int index = 0; int len = poly.length; int c = 0; // repeating until all attributes are decoded do { var shift = 0; int result = 0; // for decoding value of one attribute do { c = list[index] - 63; result |= (c & 0x1F) << (shift * 5); index++; shift++; } while (c >= 32); /* if value is negative then bitwise not the value */ if (result & 1 == 1) { result = ~result; } var result1 = (result >> 1) * 0.00001; lList.add(result1); } while (index < len); /*adding to previous value as done in encoding */ for (var i = 2; i < lList.length; i++) lList[i] += lList[i - 2]; print(lList.toString()); return lList; } static List<LatLng> convertToLatLng(List points) { List<LatLng> result = <LatLng>[]; for (int i = 0; i < points.length; i++) { if (i % 2 != 0) { result.add(LatLng(points[i - 1], points[i])); } } return result; } static Future<Uint8List> getBytesFromAsset(String path, int width) async { ByteData data = await rootBundle.load(path); Codec codec = await instantiateImageCodec(data.buffer.asUint8List(), targetWidth: width); FrameInfo fi = await codec.getNextFrame(); return (await fi.image.toByteData(format: ImageByteFormat.png)) .buffer .asUint8List(); } }
0
mirrored_repositories/fu_uber/lib/Core
mirrored_repositories/fu_uber/lib/Core/Repository/mapRepository.dart
import 'dart:convert'; import 'dart:core'; import 'dart:math' as Math; import 'package:fu_uber/Core/Constants/Constants.dart'; import 'package:fu_uber/Core/Utils/LogUtils.dart'; import 'package:geolocator/geolocator.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'package:google_maps_webservice/places.dart'; import 'package:http/http.dart' as http; import 'package:vector_math/vector_math.dart'; class MapRepository { static const TAG = "MapRepository"; GoogleMapsPlaces places = GoogleMapsPlaces(apiKey: Constants.mapApiKey); Future<String> getRouteCoordinates(LatLng l1, LatLng l2) async { String url = "https://maps.googleapis.com/maps/api/directions/json?origin=${l1.latitude},${l1.longitude}&destination=${l2.latitude},${l2.longitude}&key=${Constants.anotherApiKey}"; http.Response response = await http.get(url); Map values = jsonDecode(response.body); ProjectLog.logIt(TAG, "Predictions", values.toString()); return values["routes"][0]["overview_polyline"]["points"]; } Future<PlacesAutocompleteResponse> getAutoCompleteResponse( String search) async { return await places.autocomplete(search, sessionToken: "1212121"); } Future<String> getPlaceNameFromLatLng(LatLng latLng) async { List<Placemark> placemark = await Geolocator() .placemarkFromCoordinates(latLng.latitude, latLng.longitude); return placemark[0].name + ", " + placemark[0].locality + ", " + placemark[0].country; } Future<LatLng> getLatLngFromAddress(String address) async { List<Placemark> list = await Geolocator().placemarkFromAddress(address); return LatLng(list[0].position.latitude, list[0].position.longitude); } LatLng getMidPointBetween(LatLng one, LatLng two) { double lat1 = one.latitude; double lon1 = one.longitude; double lat2 = two.latitude; double lon2 = two.longitude; double dLon = radians(lon2 - lon1); //convert to radians lat1 = radians(lat1); lat2 = radians(lat2); lon1 = radians(lon1); double Bx = Math.cos(lat2) * Math.cos(dLon); double By = Math.cos(lat2) * Math.sin(dLon); double lat3 = Math.atan2(Math.sin(lat1) + Math.sin(lat2), Math.sqrt((Math.cos(lat1) + Bx) * (Math.cos(lat1) + Bx) + By * By)); double lon3 = lon1 + Math.atan2(By, Math.cos(lat1) + Bx); return LatLng(lat3, lon3); } }
0
mirrored_repositories/fu_uber/lib/Core
mirrored_repositories/fu_uber/lib/Core/Repository/Repository.dart
import 'dart:async'; import 'package:fu_uber/Core/Enums/Enums.dart'; import 'package:fu_uber/Core/Models/Drivers.dart'; import 'package:fu_uber/Core/Models/UserPlaces.dart'; import 'package:fu_uber/Core/Networking/ApiProvider.dart'; class Repository { static Future<AuthStatus> isUserAlreadyAuthenticated() async { return AuthStatus.Authenticated; } static Future<int> sendOTP(String phone) async { return await ApiProvider.sendOtpToUser(phone); } static Future<int> verifyOtp(String text) async { //just returning 1 //somehow check the otp return await ApiProvider.verifyOtp(text); } static void getNearbyDrivers( StreamController<List<Driver>> nearbyDriverStreamController) { nearbyDriverStreamController.sink.add(ApiProvider.getNearbyDrivers()); } static void addFavPlacesToDataBase(List<UserPlaces> data) { // } }
0
mirrored_repositories/fu_uber/lib/Core
mirrored_repositories/fu_uber/lib/Core/Models/CarTypeMenu.dart
import 'package:fu_uber/Core/Enums/Enums.dart'; class CarTypeMenu { final String image; final String info; final RideType rideType; CarTypeMenu(this.image, this.info, this.rideType); }
0
mirrored_repositories/fu_uber/lib/Core
mirrored_repositories/fu_uber/lib/Core/Models/UserPlaces.dart
import 'package:google_maps_flutter/google_maps_flutter.dart'; class UserPlaces { String title; String name; LatLng location; UserPlaces(this.title, this.name, this.location); }
0
mirrored_repositories/fu_uber/lib/Core
mirrored_repositories/fu_uber/lib/Core/Models/RideDetail.dart
class RideDetail {}
0
mirrored_repositories/fu_uber/lib/Core
mirrored_repositories/fu_uber/lib/Core/Models/Drivers.dart
import 'package:google_maps_flutter/google_maps_flutter.dart'; class Driver { String driverName; String driverImage; double driverRating; String driverId; CarDetail carDetail; LatLng currentLocation; //location should be of Location Type, for more data, not LatLng Driver(this.driverName, this.driverImage, this.driverRating, this.driverId, this.carDetail, this.currentLocation); } class CarDetail { String carId; String carCompanyName; String carModel; String carNumber; CarDetail(this.carId, this.carCompanyName, this.carModel, this.carNumber); }
0
mirrored_repositories/fu_uber/lib/Core
mirrored_repositories/fu_uber/lib/Core/Models/UserDetails.dart
import 'package:fu_uber/Core/Models/UserPlaces.dart'; class UserDetails { String uuid; String photoUrl; String name; String email; String phone; String ongoingRide; List<String> previousRides; List<UserPlaces> favouritePlaces; UserDetails(this.uuid, this.photoUrl, this.name, this.email, this.phone, this.ongoingRide, this.previousRides, this.favouritePlaces); }
0
mirrored_repositories/fu_uber/lib/Core
mirrored_repositories/fu_uber/lib/Core/Enums/Enums.dart
enum AuthStatus { Authenticated, UnAuthenticated } enum RideType { Affordable, Classic, Sedan, Suv, Luxury } enum DriverStatus { Booked, OnWay, Reached, InRoute, Free }
0
mirrored_repositories/fu_uber/lib/Core
mirrored_repositories/fu_uber/lib/Core/Networking/ApiProvider.dart
import 'package:fu_uber/Core/Constants/DemoData.dart'; import 'package:fu_uber/Core/Models/Drivers.dart'; class ApiProvider { static Future<int> sendOtpToUser(String phone) async { // WE Will be using APIs to send verification OTP. // 1 : OTP SENT Successfully // 0 : Something is wrong, network failure etc... return 1; } static Future<int> verifyOtp(String otp) async { // WE Will be using APIs to send verification OTP. // 1 : OTP SENT Successfully // 0 : Something is wrong, network failure etc... print(otp); if (otp == "1234") { return 1; } else return 0; } static List<Driver> getNearbyDrivers() { //somehow get the list of nearby drivers return DemoData.nearbyDrivers; } }
0
mirrored_repositories/fu_uber/lib/UI
mirrored_repositories/fu_uber/lib/UI/shared/NoInternetWidget.dart
import 'package:connectivity/connectivity.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class NoInternetWidget extends StatefulWidget { @override _NoInternetWidgetState createState() => _NoInternetWidgetState(); } class _NoInternetWidgetState extends State<NoInternetWidget> { bool isConnected; @override void initState() { super.initState(); } @override Widget build(BuildContext context) { return StreamBuilder( stream: Connectivity().onConnectivityChanged, builder: (context, snapshot) { return snapshot.data == ConnectivityResult.none ? Container( width: double.infinity, color: Colors.redAccent, child: Padding( padding: const EdgeInsets.all(16.0), child: Text( " Cannot connect to Aeober servers", style: TextStyle( color: Colors.black, fontWeight: FontWeight.bold), ), ), ) : SizedBox(); }); } @override void dispose() { super.dispose(); } }
0
mirrored_repositories/fu_uber/lib/UI
mirrored_repositories/fu_uber/lib/UI/shared/PredictionsLIstAutoComplete.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:fu_uber/UI/widgets/PredictionItemView.dart'; import 'package:google_maps_webservice/places.dart'; /// An list picker like Widget with textField to show /// AutoComplete just like Google Maps, /// @Required : TextField /// @Optional Data and onTap Callback typedef onListItemTap = void Function(Prediction prediction); class PredictionListAutoComplete extends StatefulWidget { final TextField textField; final List<Prediction> data; final onListItemTap itemTap; PredictionListAutoComplete( {Key key, @required this.textField, @required this.data, this.itemTap}) : super(key: key); @override _PredictionListAutoCompleteState createState() => _PredictionListAutoCompleteState(); } class _PredictionListAutoCompleteState extends State<PredictionListAutoComplete> { @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceAround, mainAxisSize: MainAxisSize.min, children: <Widget>[ widget.textField, widget.data != null && widget.data.isNotEmpty ? Column( children: <Widget>[ ListView.builder( shrinkWrap: true, itemCount: widget.data.length, itemBuilder: (BuildContext ctxt, int index) { return InkResponse( onTap: () => widget.itemTap(widget.data[index]), child: PredictionItemView( prediction: widget.data[index])); }), ListTile( title: Text("Powered By Google"), ) ], ) : SizedBox( height: 0, width: 0, ), ], ); } }
0
mirrored_repositories/fu_uber/lib/UI
mirrored_repositories/fu_uber/lib/UI/shared/CardSelectionCard.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:fu_uber/Core/Models/CarTypeMenu.dart'; import 'package:fu_uber/Core/Utils/BasicShapeUtils.dart'; class CarSelectionCard extends StatelessWidget { final CarTypeMenu carTypeMenu; const CarSelectionCard({Key key, this.carTypeMenu}) : super(key: key); @override Widget build(BuildContext context) { return SizedBox( width: double.infinity, child: Material( shape: ShapeUtils.rounderCard, elevation: 1, child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceEvenly, mainAxisSize: MainAxisSize.max, children: <Widget>[ Expanded( child: Padding( padding: const EdgeInsets.all(8.0), child: Image.asset( carTypeMenu.image, fit: BoxFit.fitHeight, ), ), ), Padding( padding: const EdgeInsets.all(8.0), child: Text( carTypeMenu.rideType.toString(), style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold), ), ), Padding( padding: const EdgeInsets.all(8.0), child: Text( carTypeMenu.info, style: TextStyle(fontSize: 12, fontWeight: FontWeight.normal), ), ) ], ), ), ); } }
0
mirrored_repositories/fu_uber/lib/UI
mirrored_repositories/fu_uber/lib/UI/shared/CircularFlatButton.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:fu_uber/Core/Constants/colorConstants.dart'; typedef OnPressed = void Function(); class CircularFlatButton extends StatelessWidget { final double size; final Widget child; final String name; final OnPressed onPressed; const CircularFlatButton( {Key key, this.size, this.name, this.onPressed, this.child}) : super(key: key); @override Widget build(BuildContext context) { return SizedBox( height: size, width: size, child: FlatButton( shape: CircleBorder(), disabledColor: ConstantColors.DeepBlue.withOpacity(0.2), onPressed: onPressed, child: Column( mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.max, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ child, Text( name, style: TextStyle( fontSize: 18, color: Colors.deepPurpleAccent, ), ) ], ))); } }
0
mirrored_repositories/fu_uber/lib/UI
mirrored_repositories/fu_uber/lib/UI/shared/ErrorDialogue.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class ErrorDialogue extends StatelessWidget { final String errorTitle; final String errorMessage; const ErrorDialogue( {Key key, @required this.errorMessage, @required this.errorTitle}) : super(key: key); @override Widget build(BuildContext context) { return AlertDialog( elevation: 10, title: Text(errorTitle), content: Text(errorMessage), actions: <Widget>[ RaisedButton( color: Colors.black87, onPressed: () { Navigator.of(context).pop(); }, child: Text( "OK", style: TextStyle(fontSize: 20, color: Colors.white), ), ) ], ); } }
0
mirrored_repositories/fu_uber/lib/UI
mirrored_repositories/fu_uber/lib/UI/views/ProfileScreen.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/widgets.dart'; import 'package:fu_uber/Core/Constants/DemoData.dart'; import 'package:fu_uber/Core/Models/UserDetails.dart'; import 'package:fu_uber/UI/shared/CircularFlatButton.dart'; class ProfileScreen extends StatefulWidget { // Material Page Route static const route = "/profilescreen"; // Tag for logging static const TAG = "ProfileScreen"; @override _ProfileScreenState createState() => _ProfileScreenState(); } class _ProfileScreenState extends State<ProfileScreen> { @override Widget build(BuildContext context) { UserDetails currentUser = DemoData.currentUserDetails; Size size = MediaQuery .of(context) .size; return Material( child: Scaffold( body: SingleChildScrollView( child: Column( children: <Widget>[ SizedBox( height: size.height / 1.7, child: Stack( children: <Widget>[ ClipRRect( borderRadius: BorderRadius.only( bottomLeft: Radius.circular(250), bottomRight: Radius.circular(10)), child: SizedBox( height: size.height / 2, width: double.infinity, child: Image.network( currentUser.photoUrl, fit: BoxFit.fitWidth, )), ), Align( alignment: Alignment(0, 1), child: Card( child: SizedBox( width: size.width / 1.3, height: 120, child: Column( mainAxisSize: MainAxisSize.max, crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Padding( padding: const EdgeInsets.all(5.0), child: Row( children: <Widget>[ Expanded( child: SizedBox(), ), Text( "edit", style: TextStyle(color: Colors.blue), ), Icon( Icons.edit, size: 15, color: Colors.blue, ) ], ), ), Text( currentUser.name, style: TextStyle(fontSize: 17), ), Text( currentUser.phone, style: TextStyle(fontSize: 17), ), Text( currentUser.email, style: TextStyle(fontSize: 17), ), Text( " ", style: TextStyle(fontSize: 17), ), ], ), ), ), ) ], ), ), Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Padding( padding: const EdgeInsets.only(top: 5.0), child: CircularFlatButton( size: 100, onPressed: null, child: Icon( Icons.directions_car, color: Colors.deepPurpleAccent, size: 50, ), name: "Rides", ), ), Padding( padding: const EdgeInsets.only(top: 60.0), child: CircularFlatButton( size: 120, onPressed: null, child: Icon( Icons.settings, color: Colors.deepPurpleAccent, size: 70, ), name: "Settings", ), ), Padding( padding: const EdgeInsets.only(top: 5.0), child: CircularFlatButton( size: 100, onPressed: null, child: Icon( Icons.help, color: Colors.deepPurpleAccent, size: 50, ), name: "Help", ), ) ], ), ], ), ), ), ); } }
0
mirrored_repositories/fu_uber/lib/UI
mirrored_repositories/fu_uber/lib/UI/views/LocationPermissionScreen.dart
import 'package:flutter/material.dart'; import 'package:flutter/physics.dart'; import 'package:fu_uber/Core/Constants/colorConstants.dart'; import 'package:fu_uber/Core/ProviderModels/MapModel.dart'; import 'package:fu_uber/Core/ProviderModels/PermissionHandlerModel.dart'; import 'package:fu_uber/UI/views/MainScreen.dart'; import 'package:provider/provider.dart'; class LocationPermissionScreen extends StatefulWidget { static final String route = "locationScreen"; @override _LocationPermissionScreenState createState() => _LocationPermissionScreenState(); } class _LocationPermissionScreenState extends State<LocationPermissionScreen> with SingleTickerProviderStateMixin { AnimationController loadingController; Animation<double> animation; @override void dispose() { loadingController.dispose(); super.dispose(); } @override void initState() { super.initState(); loadingController = AnimationController(vsync: this, duration: Duration(seconds: 5)); animation = Tween<double>(begin: 0, end: 40).animate(new CurvedAnimation( parent: loadingController, curve: Curves.easeInOutCirc)); loadingController.addStatusListener((AnimationStatus status) { if (status == AnimationStatus.completed) { loadingController.forward(from: 0); } }); loadingController.forward(); } @override Widget build(BuildContext context) { final permModel = Provider.of<PermissionHandlerModel>(context); final mapModel = Provider.of<MapModel>(context); return Material( child: Container( child: Stack( children: <Widget>[ SpringEffect(), permModel.isLocationPerGiven ? Align( alignment: Alignment(0, 0.5), child: permModel.isLocationSerGiven ? Text("Fetching Location...") : InkResponse( onTap: () { permModel.requestLocationServiceToEnable(); mapModel.randomMapZoom(); }, child: Padding( padding: const EdgeInsets.all(16.0), child: Container( color: ConstantColors.PrimaryColor, height: 40, width: double.infinity, child: Text( "Location Service Not Enabled", style: TextStyle( fontSize: 20, color: Colors.white), ), ), ), ), ) : Align( alignment: Alignment.bottomCenter, child: InkResponse( onTap: () { permModel.requestAppLocationPermission(); }, child: Padding( padding: const EdgeInsets.all(16.0), child: Container( color: ConstantColors.PrimaryColor, height: 60, width: double.infinity, child: Center( child: Text( "Location Permission is Not Given", style: TextStyle(fontSize: 15, color: Colors.white), )), ), ), ), ) ], ), ), ); } @override void didChangeDependencies() { final mapModel = Provider.of<MapModel>(context); if (mapModel.currentPosition != null) { Navigator.of(context).pushReplacementNamed(MainScreen.route); } super.didChangeDependencies(); } } class SpringEffect extends StatefulWidget { @override SpringState createState() => SpringState(); } class SpringState extends State<SpringEffect> with TickerProviderStateMixin { AnimationController controller; AnimationController controller2; Animation<double> animation; SpringSimulation simulation; double _position = 0; @override void initState() { super.initState(); simulation = SpringSimulation( SpringDescription( mass: 1.0, stiffness: 100.0, damping: 5.0, ), 200.0, 100.0, -2000.0, ); controller2 = AnimationController(vsync: this, duration: Duration(milliseconds: 70)); animation = Tween(begin: 100.0, end: 200.0).animate(controller2) ..addListener(() { if (controller2.status == AnimationStatus.completed) { controller.forward(from: 0); } setState(() { _position = animation.value; }); }); controller = AnimationController(vsync: this, duration: Duration(seconds: 2)) ..forward() ..addListener(() { if (controller.status == AnimationStatus.completed) { controller2.forward(from: 0); } setState(() { _position = simulation.x(controller.value); }); }); } @override void dispose() { controller.dispose(); controller2.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Container( child: Center( child: Stack( fit: StackFit.expand, children: <Widget>[ Align( alignment: Alignment(0, _position / 1000), child: Image.asset( "images/pickupIcon.png", width: 50, ), ), ], ), )); } }
0
mirrored_repositories/fu_uber/lib/UI
mirrored_repositories/fu_uber/lib/UI/views/SignIn.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:fu_uber/Core/ProviderModels/VerificationModel.dart'; import 'package:fu_uber/Core/Utils/LogUtils.dart'; import 'package:fu_uber/UI/widgets/OtpBottomSheet.dart'; import 'package:provider/provider.dart'; final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>(); final GlobalKey<FormState> _phoneFormKey = GlobalKey<FormState>(); class SignInPage extends StatefulWidget { // Material Page Route static const route = "/signinscreen"; // Tag for logging static const TAG = "SignInScreen"; @override _SignInPageState createState() => _SignInPageState(); } class _SignInPageState extends State<SignInPage> { final phoneTextController = TextEditingController(); @override void initState() { super.initState(); } @override Widget build(BuildContext context) { var width = MediaQuery.of(context).size.width; final verificationModel = Provider.of<VerificationModel>(context); return Scaffold( key: _scaffoldKey, body: Material( child: Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.max, children: <Widget>[ Padding( padding: const EdgeInsets.only(left: 15, right: 15), child: Text( 'Enter Your Phone Number to get Started...', style: TextStyle(fontSize: 35), ), ), Card( child: Container( height: kToolbarHeight, width: width / 1.2, margin: EdgeInsets.only(right: 0, top: 3, bottom: 3, left: 10), child: Form( key: _phoneFormKey, child: TextFormField( controller: phoneTextController, cursorWidth: 2, onFieldSubmitted: verificationModel.setPhoneNumber, validator: (value) { if (value.length < 10 || value.length > 13) { return "Enter a Valid Phone Number"; } else return null; }, keyboardType: TextInputType.phone, style: TextStyle( fontFamily: 'Righteous', fontStyle: FontStyle.normal, fontWeight: FontWeight.w200, wordSpacing: 2, fontSize: kToolbarHeight / 2.3, letterSpacing: 2, ), textInputAction: TextInputAction.done, decoration: InputDecoration( hintText: "Phone number", border: InputBorder.none), ), ), ), ), Padding( padding: EdgeInsets.all(8.0), child: verificationModel.showCircularLoader ? CircularProgressIndicator() : SizedBox( width: 0, height: 0, ), ), InkResponse( onTap: () { if (_phoneFormKey.currentState.validate()) verificationModel.updateCircularLoading(true); Future.delayed(Duration(seconds: 5)).then((_) { verificationModel.handlePhoneVerification().then((response) { ProjectLog.logIt( SignInPage.TAG, "PhoneVerification Response", response); verificationModel.updateCircularLoading(false); if (response == 1) { showModalBottomSheet( shape: RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(10.0)), ), context: context, builder: (context) => OtpBottomSheet(), ); } else { _scaffoldKey.currentState.showSnackBar(SnackBar( content: Text("Something Went Wrong.. Retry!"))); } }); }); }, child: Column( children: <Widget>[ Text('Lets Go...'), Icon(Icons.arrow_forward) ], ), ), ], ), ), ); } }
0
mirrored_repositories/fu_uber/lib/UI
mirrored_repositories/fu_uber/lib/UI/views/OnGoingRideScreen.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:fu_uber/Core/Enums/Enums.dart'; import 'package:fu_uber/Core/ProviderModels/RideBookedModel.dart'; import 'package:fu_uber/Core/Utils/BasicShapeUtils.dart'; import 'package:fu_uber/UI/widgets/DriverDetailsWithPin.dart'; import 'package:fu_uber/UI/widgets/DriverReachedWidget.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'package:provider/provider.dart'; import 'package:sliding_up_panel/sliding_up_panel.dart'; class OnGoingRideScreen extends StatefulWidget { static const route = "/onGoingRideScreen"; static const TAG = "OnGoingRideScreen"; @override _OnGoingRideScreenState createState() => _OnGoingRideScreenState(); } class _OnGoingRideScreenState extends State<OnGoingRideScreen> { @override Widget build(BuildContext context) { final rideBookedProvider = Provider.of<RideBookedModel>(context); return Scaffold( body: Stack( children: <Widget>[ SlidingUpPanel( maxHeight: 160, parallaxEnabled: true, parallaxOffset: 0.5, isDraggable: false, defaultPanelState: PanelState.OPEN, color: Colors.transparent, boxShadow: const <BoxShadow>[ BoxShadow( blurRadius: 8.0, color: Color.fromRGBO(0, 0, 0, 0), ) ], borderRadius: ShapeUtils.borderRadiusGeometry, body: GoogleMap( initialCameraPosition: CameraPosition( target: rideBookedProvider.originLatLng, zoom: 16), onMapCreated: rideBookedProvider.onMapCreated, mapType: MapType.normal, rotateGesturesEnabled: false, tiltGesturesEnabled: false, zoomGesturesEnabled: true, markers: rideBookedProvider.markers, onCameraMove: rideBookedProvider.onCameraMove, polylines: rideBookedProvider.polyLines, ), panel: rideBookedProvider.driverStatus == DriverStatus.OnWay ? DriverDetailsWithPin() : rideBookedProvider.driverStatus == DriverStatus.InRoute ? DriverDetailsWithPin() : DriverReachedWidget(), ), Padding( padding: const EdgeInsets.symmetric(vertical: 60.0, horizontal: 25.0), child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Icon( Icons.dehaze, color: Colors.black, ), Expanded( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 16.0), child: Text( "Home", style: TextStyle(fontSize: 20, color: Colors.black), ), ), ), Icon( Icons.more_vert, color: Colors.black, ), ], ), ), Padding( padding: const EdgeInsets.only( top: kToolbarHeight * 2, left: 20, right: 20), child: SizedBox( height: kToolbarHeight * 1.5, width: double.infinity, child: Card( color: Colors.black87, child: Row( children: <Widget>[ Padding( padding: const EdgeInsets.symmetric( vertical: 10.0, horizontal: 15), child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Icon( Icons.directions_car, color: Colors.white, ), Text( rideBookedProvider.timeLeftToReach.toString() + "min", style: TextStyle(color: Colors.white), ), ], ), ), Container( color: Colors.white30, height: kToolbarHeight * 1.5, width: 3, ), Expanded( child: Padding( padding: const EdgeInsets.all(10.0), child: Text( "Meet at fdsffds fd saf ffds", maxLines: 2, style: TextStyle(fontSize: 16, color: Colors.white), ), ), ) ], ), ), ), ) ], ), ); } }
0
mirrored_repositories/fu_uber/lib/UI
mirrored_repositories/fu_uber/lib/UI/views/MainScreen.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; import 'package:fu_uber/Core/Constants/colorConstants.dart'; import 'package:fu_uber/Core/ProviderModels/MapModel.dart'; import 'package:fu_uber/Core/ProviderModels/UINotifiersModel.dart'; import 'package:fu_uber/Core/ProviderModels/UserDetailsModel.dart'; import 'package:fu_uber/Core/Utils/BasicShapeUtils.dart'; import 'package:fu_uber/UI/shared/NoInternetWidget.dart'; import 'package:fu_uber/UI/shared/PredictionsLIstAutoComplete.dart'; import 'package:fu_uber/UI/views/ProfileScreen.dart'; import 'package:fu_uber/UI/widgets/BottomSheetMenuMap.dart'; import 'package:fu_uber/UI/widgets/SearchingRideBox.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'package:provider/provider.dart'; import 'package:sliding_up_panel/sliding_up_panel.dart'; /// MainScreen : It contains the code of the MAP SCREEN, the Screen just after the Location Permissions. class MainScreen extends StatefulWidget { // Material Page Route static const route = "/mainScreen"; // Tag for logging static const TAG = "MainScreen"; @override _MainScreenState createState() => _MainScreenState(); } class _MainScreenState extends State<MainScreen> with TickerProviderStateMixin { AnimationController loadingController; Animation<double> animation; @override void initState() { super.initState(); loadingController = AnimationController(vsync: this, duration: Duration(seconds: 5)); animation = Tween<double>(begin: 0, end: 40).animate(new CurvedAnimation( parent: loadingController, curve: Curves.easeInOutCirc)); loadingController.addStatusListener((AnimationStatus status) { if (status == AnimationStatus.completed) { loadingController.reverse(from: 1); } }); loadingController.forward(); } @override void dispose() { super.dispose(); loadingController.dispose(); } @override Widget build(BuildContext context) { final mapModel = Provider.of<MapModel>(context); final userDetailsModel = Provider.of<UserDetailsModel>(context); final uiNotifiersModel = Provider.of<UINotifiersModel>(context); return Material( child: Scaffold( resizeToAvoidBottomPadding: true, body: Stack( children: <Widget>[ SlidingUpPanel( onPanelSlide: uiNotifiersModel.setOriginDestinationVisibility, onPanelOpened: () { uiNotifiersModel.onPanelOpen(); mapModel.panelIsOpened(); }, onPanelClosed: () { uiNotifiersModel.onPanelClosed(); mapModel.panelIsClosed(); }, maxHeight: MediaQuery .of(context) .size .height / 1.3, parallaxEnabled: true, parallaxOffset: 0.5, color: Colors.transparent, boxShadow: const <BoxShadow>[ BoxShadow( blurRadius: 8.0, color: Color.fromRGBO(0, 0, 0, 0), ) ], controller: uiNotifiersModel.panelController, borderRadius: ShapeUtils.borderRadiusGeometry, body: GoogleMap( initialCameraPosition: CameraPosition( target: mapModel.currentPosition, zoom: mapModel.currentZoom), onMapCreated: mapModel.onMapCreated, mapType: MapType.normal, rotateGesturesEnabled: false, tiltGesturesEnabled: false, zoomGesturesEnabled: true, markers: mapModel.markers, onCameraMove: mapModel.onCameraMove, polylines: mapModel.polyLines, ), collapsed: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Expanded(child: SizedBox()), Padding( padding: const EdgeInsets.all(20.0), child: FloatingActionButton( onPressed: mapModel.onMyLocationFabClicked, backgroundColor: ConstantColors.PrimaryColor, child: Icon(Icons.my_location), ), ) ], ), panel: BottomSheetMapMenu(), ), SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.end, children: <Widget>[ Row( children: <Widget>[ Expanded( child: SizedBox(), ), Padding( padding: const EdgeInsets.only(top: 40.0, right: 20), child: SizedBox( height: 50, child: InkResponse( onTap: () { Navigator.pushNamed( context, ProfileScreen.route, arguments: "dsad"); }, child: ClipOval( child: FadeInImage( placeholder: AssetImage( "images/destinationIcon.png"), image: NetworkImage( userDetailsModel.photoUrl, scale: 0.5)), ), ), ), ), ], ), Visibility( visible: uiNotifiersModel.originDestinationVisibility < 0.2 || uiNotifiersModel.searchingRide ? false : true, child: Opacity( opacity: uiNotifiersModel.originDestinationVisibility, child: Padding( padding: const EdgeInsets.all(15.0), child: Card( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(15.0), ), child: Row( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Padding( padding: const EdgeInsets.only( top: 12.0, right: 10, left: 10, bottom: 10), child: SizedBox( width: 30, child: Image.asset( "images/originDestinationDistanceIcon.png", fit: BoxFit.fitWidth, )), ), Expanded( child: Column( children: <Widget>[ PredictionListAutoComplete( data: mapModel.pickupPredictions, textField: TextField( cursorColor: Colors.black, onSubmitted: mapModel.onPickupTextFieldChanged, //onChanged: mapModel.onPickupTextFieldChanged, not using it for now controller: mapModel .pickupFormFieldController, decoration: InputDecoration( labelText: "Origin", border: InputBorder.none, contentPadding: EdgeInsets.only( top: 15, right: 20, bottom: 10), ), ), itemTap: mapModel .onPickupPredictionItemClick, ), PredictionListAutoComplete( data: mapModel.destinationPredictions, textField: TextField( cursorColor: Colors.black, onSubmitted: mapModel .onDestinationTextFieldChanged, //onChanged:mapModel.onDestinationTextFieldChanged, controller: mapModel .destinationFormFieldController, decoration: InputDecoration( labelText: "Destination", border: InputBorder.none, contentPadding: EdgeInsets.only( right: 20, bottom: 15), ), ), itemTap: mapModel .onDestinationPredictionItemClick, ) ], ), ), ], ), ), ), ), ), ], ), ), Visibility( visible: uiNotifiersModel.searchingRide, child: Align( alignment: Alignment.bottomCenter, child: SearchingRideBox(), ), ), Align( alignment: Alignment.bottomCenter, child: NoInternetWidget(), ), ], )), ); } }
0
mirrored_repositories/fu_uber/lib/UI
mirrored_repositories/fu_uber/lib/UI/widgets/SearchingRideBox.dart
import 'package:flutter/material.dart'; import 'package:fu_uber/Core/Constants/colorConstants.dart'; import 'package:fu_uber/Core/ProviderModels/CurrentRideCreationModel.dart'; import 'package:fu_uber/Core/ProviderModels/UINotifiersModel.dart'; import 'package:provider/provider.dart'; class SearchingRideBox extends StatefulWidget { @override _SearchingRideBoxState createState() => _SearchingRideBoxState(); } class _SearchingRideBoxState extends State<SearchingRideBox> with SingleTickerProviderStateMixin { @override Widget build(BuildContext context) { final uiNotifier = Provider.of<UINotifiersModel>(context); final currentRideDetailsModel = Provider.of<CurrentRideCreationModel>(context); return Padding( padding: const EdgeInsets.all(16.0), child: Card( child: Container( width: double.infinity, margin: EdgeInsets.all(16.0), color: Colors.white, child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceEvenly, mainAxisSize: MainAxisSize.min, children: <Widget>[ Padding( padding: const EdgeInsets.all(8.0), child: Text( "Searching for a Ride", style: TextStyle(color: Colors.black, fontSize: 20), ), ), Padding( padding: const EdgeInsets.all(8.0), child: Container( constraints: BoxConstraints(maxHeight: 2.0), child: LinearProgressIndicator( valueColor: AlwaysStoppedAnimation<Color>(Colors.white), backgroundColor: ConstantColors.PrimaryColor, )), ), Padding( padding: const EdgeInsets.all(8.0), child: Text( "It may take few minutes, according to the availability", textAlign: TextAlign.center, style: TextStyle(color: Colors.black54), ), ), Padding( padding: const EdgeInsets.all(8.0), child: Row( children: <Widget>[ Expanded( child: FlatButton( onPressed: () { uiNotifier.searchingRideNotify(); }, color: ConstantColors.PrimaryColor, child: Text( "Cancel", style: TextStyle(color: Colors.white, fontSize: 20), )), ), ], ), ) ], ), ), ), ); } }
0
mirrored_repositories/fu_uber/lib/UI
mirrored_repositories/fu_uber/lib/UI/widgets/BottomSheetMenuMap.dart
import 'package:carousel_slider/carousel_slider.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:fu_uber/Core/Constants/DemoData.dart'; import 'package:fu_uber/Core/Constants/colorConstants.dart'; import 'package:fu_uber/Core/ProviderModels/CurrentRideCreationModel.dart'; import 'package:fu_uber/Core/ProviderModels/MapModel.dart'; import 'package:fu_uber/Core/ProviderModels/UINotifiersModel.dart'; import 'package:fu_uber/Core/Utils/BasicShapeUtils.dart'; import 'package:fu_uber/UI/shared/CardSelectionCard.dart'; import 'package:fu_uber/UI/views/OnGoingRideScreen.dart'; import 'package:fu_uber/main.dart'; import 'package:provider/provider.dart'; class BottomSheetMapMenu extends StatelessWidget { @override Widget build(BuildContext context) { final currentRideCreationModel = Provider.of<CurrentRideCreationModel>(context); final uiNotifiersModel = Provider.of<UINotifiersModel>(context); final mapModel = Provider.of<MapModel>(context); return Container( decoration: BoxDecoration( color: Colors.transparent, borderRadius: ShapeUtils.borderRadiusGeometry, ), child: Column( children: <Widget>[ Container( color: Colors.transparent, height: 100, child: Center( child: SizedBox( width: 100, height: 15, child: Card( elevation: 5, shape: ShapeUtils.rounderCard, color: ConstantColors.PrimaryColor, ), ), ), ), Material( child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Padding( padding: const EdgeInsets.all(16.0), child: Text( "Choose the type of Ride : ", style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold), ), ), CarouselSlider( enableInfiniteScroll: false, initialPage: 1, enlargeCenterPage: true, scrollDirection: Axis.horizontal, onPageChanged: currentRideCreationModel.carTypeChanged, items: DemoData.typesOfCar.map((i) { return Builder( builder: (BuildContext context) { return CarSelectionCard(carTypeMenu: i); }, ); }).toList(), ), ], ), Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Padding( padding: const EdgeInsets.all(16.0), child: Text( "Estimate of Ride : ", style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold), ), ), Padding( padding: const EdgeInsets.all(16.0), child: Container( width: double.infinity, color: Colors.black54, child: Padding( padding: const EdgeInsets.all(8.0), child: Text( mapModel.checkDestinationOriginForNull() ? "Etimated amount : ${currentRideCreationModel .getEstimationFromOriginDestination()} Rupees" : "Pin the Destination and Origin", style: TextStyle( color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold), ), ), ), ) ], ), InkResponse( onTap: () { uiNotifiersModel.searchingRideNotify(); Future.delayed(Duration(seconds: 5), () { uiNotifiersModel.searchingRideNotify(); navigatorKey.currentState .pushReplacementNamed(OnGoingRideScreen.route); }); }, child: Container( height: 100, width: double.infinity, color: ConstantColors.PrimaryColor, child: Center( child: Text( "Book ${currentRideCreationModel.selectedRideType}", style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 20), )), ), ) ], ), ) ], ), ); } }
0
mirrored_repositories/fu_uber/lib/UI
mirrored_repositories/fu_uber/lib/UI/widgets/DriverDetailsWithPin.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:fu_uber/Core/ProviderModels/RideBookedModel.dart'; import 'package:fu_uber/UI/views/MainScreen.dart'; import 'package:provider/provider.dart'; class DriverDetailsWithPin extends StatelessWidget { @override Widget build(BuildContext context) { final rideBookedModel = Provider.of<RideBookedModel>(context); return Container( decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(24.0)), boxShadow: [ BoxShadow( blurRadius: 20.0, color: Colors.grey, ), ]), margin: const EdgeInsets.all(8.0), width: double.infinity, child: Stack( children: <Widget>[ Align( alignment: Alignment.topRight, child: Padding( padding: const EdgeInsets.all(8.0), child: InkResponse( onTap: () { //_showCancelDialog(); Navigator.of(context).pushReplacementNamed(MainScreen.route); }, child: Icon( Icons.close, color: Colors.black, ), ), ), ), Padding( padding: const EdgeInsets.all(15.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, mainAxisSize: MainAxisSize.max, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Padding( padding: const EdgeInsets.all(10.0), child: Stack( children: <Widget>[ SizedBox( width: 70, height: 80, child: ClipOval( child: FadeInImage( placeholder: AssetImage("images/destinationIcon.png"), image: NetworkImage( rideBookedModel.currentDriver.driverImage), fit: BoxFit.fill, ), ), ), Align( alignment: Alignment.bottomRight, child: CircleAvatar( backgroundColor: Colors.black, child: Icon( Icons.call, color: Colors.white, ), ), ) ], ), ), Expanded( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 10.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceEvenly, mainAxisSize: MainAxisSize.max, children: <Widget>[ Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Text( rideBookedModel.currentDriver.driverName + " ", style: TextStyle( color: Colors.black, fontSize: 15, fontWeight: FontWeight.bold), ), Text( rideBookedModel.currentDriver.driverRating .toString() + " \u2605", style: TextStyle( color: Colors.black, fontSize: 15, fontWeight: FontWeight.bold), ), ], ), Text( rideBookedModel .currentDriver.carDetail.carCompanyName, style: TextStyle( color: Colors.grey, fontSize: 15, fontWeight: FontWeight.bold), ), ], ), ), ), Padding( padding: const EdgeInsets.all(6.0), child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceEvenly, mainAxisSize: MainAxisSize.max, children: <Widget>[ Text( "Pin : " + "1234", style: TextStyle( color: Colors.black, fontSize: 15, fontWeight: FontWeight.bold), ), Container( padding: EdgeInsets.all(2), decoration: BoxDecoration( border: Border.all(color: Colors.black)), child: Text( rideBookedModel.currentDriver.carDetail.carNumber, style: TextStyle( color: Colors.black, fontSize: 15, fontWeight: FontWeight.bold), ), ), ], ), ) ], ), ), ], ), ); } }
0
mirrored_repositories/fu_uber/lib/UI
mirrored_repositories/fu_uber/lib/UI/widgets/PredictionItemView.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:google_maps_webservice/places.dart'; class PredictionItemView extends StatelessWidget { final Prediction prediction; const PredictionItemView({Key key, this.prediction}) : super(key: key); @override Widget build(BuildContext context) { return Card( child: ListTile( title: Text( prediction.description, ), trailing: Icon(Icons.arrow_forward), ), ); } }
0
mirrored_repositories/fu_uber/lib/UI
mirrored_repositories/fu_uber/lib/UI/widgets/DriverReachedWidget.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:fu_uber/Core/ProviderModels/RideBookedModel.dart'; import 'package:fu_uber/UI/views/MainScreen.dart'; import 'package:provider/provider.dart'; class DriverReachedWidget extends StatelessWidget { @override Widget build(BuildContext context) { final rideBookedModel = Provider.of<RideBookedModel>(context); return Container( decoration: BoxDecoration( color: Colors.blueGrey, borderRadius: BorderRadius.all(Radius.circular(24.0)), boxShadow: [ BoxShadow( blurRadius: 20.0, color: Colors.grey, ), ]), margin: const EdgeInsets.all(8.0), width: double.infinity, child: Stack( children: <Widget>[ Align( alignment: Alignment.topRight, child: Padding( padding: const EdgeInsets.all(8.0), child: InkResponse( onTap: () { //_showCancelDialog(); Navigator.of(context).pushReplacementNamed(MainScreen.route); }, child: Icon( Icons.close, color: Colors.black, ), ), ), ), Padding( padding: const EdgeInsets.all(15.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, mainAxisSize: MainAxisSize.max, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Padding( padding: const EdgeInsets.all(10.0), child: Stack( children: <Widget>[ SizedBox( width: 70, height: 80, child: ClipOval( child: Image.asset( "images/reached.png", fit: BoxFit.fitHeight, ), ), ), Align( alignment: Alignment.bottomRight, child: CircleAvatar( backgroundColor: Colors.black, child: Icon( Icons.call, color: Colors.white, ), ), ) ], ), ), Expanded( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 10.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceEvenly, mainAxisSize: MainAxisSize.max, children: <Widget>[ Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Text( rideBookedModel.currentDriver.driverName + " ", style: TextStyle( color: Colors.black, fontSize: 15, fontWeight: FontWeight.bold), ), Text( rideBookedModel.currentDriver.driverRating .toString() + " \u2605", style: TextStyle( color: Colors.black, fontSize: 15, fontWeight: FontWeight.bold), ), ], ), Text( rideBookedModel .currentDriver.carDetail.carCompanyName, style: TextStyle( color: Colors.grey, fontSize: 15, fontWeight: FontWeight.bold), ), ], ), ), ), Padding( padding: const EdgeInsets.all(6.0), child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceEvenly, mainAxisSize: MainAxisSize.max, children: <Widget>[ Text( "Pin : " + "1234", style: TextStyle( color: Colors.black, fontSize: 15, fontWeight: FontWeight.bold), ), Container( padding: EdgeInsets.all(2), decoration: BoxDecoration( border: Border.all(color: Colors.black)), child: Text( rideBookedModel.currentDriver.carDetail.carNumber, style: TextStyle( color: Colors.black, fontSize: 15, fontWeight: FontWeight.bold), ), ), ], ), ) ], ), ), ], ), ); } }
0
mirrored_repositories/fu_uber/lib/UI
mirrored_repositories/fu_uber/lib/UI/widgets/OtpBottomSheet.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:fu_uber/Core/ProviderModels/VerificationModel.dart'; import 'package:fu_uber/UI/shared/ErrorDialogue.dart'; import 'package:fu_uber/UI/views/LocationPermissionScreen.dart'; import 'package:pin_code_text_field/pin_code_text_field.dart'; import 'package:provider/provider.dart'; class OtpBottomSheet extends StatelessWidget { @override Widget build(BuildContext context) { final verificationModel = Provider.of<VerificationModel>(context); return Column( children: <Widget>[ Padding( padding: const EdgeInsets.all(25), child: Text( 'Enter OTP Here', style: TextStyle(fontSize: 30), ), ), Padding( padding: const EdgeInsets.all(25), child: PinCodeTextField( autofocus: false, controller: verificationModel.oTPTextController, hideCharacter: true, highlight: true, highlightColor: Colors.black, defaultBorderColor: Colors.black, hasTextBorderColor: Colors.green, maxLength: 4, hasError: verificationModel.ifOtpHasError, maskCharacter: "*", pinCodeTextFieldLayoutType: PinCodeTextFieldLayoutType.AUTO_ADJUST_WIDTH, wrapAlignment: WrapAlignment.start, pinBoxDecoration: ProvidedPinBoxDecoration.underlinedPinBoxDecoration, pinTextStyle: TextStyle(fontSize: 30.0), pinTextAnimatedSwitcherTransition: ProvidedPinBoxTextAnimation.scalingTransition, pinTextAnimatedSwitcherDuration: Duration(milliseconds: 200), ), ), Padding( padding: const EdgeInsets.all(15), child: RaisedButton( disabledColor: Colors.black87, color: Colors.black87, onPressed: () { verificationModel .setOtp(verificationModel.oTPTextController.text); verificationModel.updateCircularLoadingOtp(true); Future.delayed(Duration(seconds: 5)).then((_) { verificationModel.oTPVerification().then((response) { verificationModel.updateCircularLoadingOtp(true); if (response == 1) { Navigator.pushReplacementNamed( context, LocationPermissionScreen.route); } else { verificationModel.updateCircularLoadingOtp(false); showDialog( context: context, builder: (BuildContext ctx) { return ErrorDialogue( errorTitle: "Wrong OTP", errorMessage: "The OTP you entered is wrong please recheck and try again.", ); }); } }); }); }, child: Text( 'Verify', style: TextStyle(fontSize: 25, color: Colors.white), ), ), ), Padding( padding: EdgeInsets.all(8.0), child: verificationModel.shopCircularLoaderOTP ? CircularProgressIndicator() : SizedBox( width: 0, height: 0, ), ) ], ); } }
0