repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/flutter_banana_challenge/lib
mirrored_repositories/flutter_banana_challenge/lib/views/views.dart
export 'package:flutter_banana_challenge/views/widgets/home/product_detail.dart'; export 'package:flutter_banana_challenge/views/auth_wrapper_screen.dart'; export 'package:flutter_banana_challenge/views/home_screen.dart'; export 'package:flutter_banana_challenge/views/login_screen.dart';
0
mirrored_repositories/flutter_banana_challenge/lib
mirrored_repositories/flutter_banana_challenge/lib/views/home_screen.dart
import 'package:flutter/material.dart'; import 'package:flutter_banana_challenge/viewModels/auth_view_model.dart'; import 'package:flutter_banana_challenge/viewModels/product_view_model.dart'; import 'package:flutter_banana_challenge/views/widgets/widgets.dart'; import 'package:provider/provider.dart'; import '../models/product_model.dart'; class HomeScreen extends StatelessWidget { const HomeScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final AuthViewModel authViewModel = context.read<AuthViewModel>(); context.read<ProductViewModel>().getProducts(); return Scaffold( appBar: AppBar( title: const Text('Flutter Challenge 2023'), leading: IconButton( onPressed: () { authViewModel.logout(); }, icon: const Icon(Icons.logout), ), actions: [ IconButton( onPressed: () { showSearch(context: context, delegate: ProductsSearchDelegate()); }, icon: const Icon(Icons.search), ), ], ), body: Center( child: Consumer<ProductViewModel>( builder: (context, state, child) { if (state.loading) { return Image.asset('assets/images/loading.gif', width: 150); } return ListView.builder( itemCount: state.products.length, shrinkWrap: true, itemBuilder: (context, index) { final ProductModel product = state.products[index]; return ProductWidget(product: product); }, ); }, ), ), ); } }
0
mirrored_repositories/flutter_banana_challenge/lib
mirrored_repositories/flutter_banana_challenge/lib/views/auth_wrapper_screen.dart
import 'package:flutter/material.dart'; import 'package:flutter_banana_challenge/viewModels/auth_view_model.dart'; import 'package:flutter_banana_challenge/views/views.dart'; import 'package:provider/provider.dart'; class AuthWrapperScreen extends StatefulWidget { const AuthWrapperScreen({Key? key}) : super(key: key); @override State<AuthWrapperScreen> createState() => _AuthWrapperScreenState(); } class _AuthWrapperScreenState extends State<AuthWrapperScreen> { @override Widget build(BuildContext context) { return Consumer<AuthViewModel>( builder: (context, authViewModel, child) { authViewModel.checkAuthStatus(); if (authViewModel.token == '') { return const LoginScreen(); } //If user is logged in, return HomeScreen return const HomeScreen(); }, ); } }
0
mirrored_repositories/flutter_banana_challenge/lib
mirrored_repositories/flutter_banana_challenge/lib/views/login_screen.dart
import 'package:flutter/material.dart'; import 'package:flutter_banana_challenge/viewModels/auth_view_model.dart'; import 'package:flutter_banana_challenge/views/widgets/widgets.dart'; import 'package:provider/provider.dart'; class LoginScreen extends StatefulWidget { const LoginScreen({Key? key}) : super(key: key); @override State<LoginScreen> createState() => _LoginScreenState(); } class _LoginScreenState extends State<LoginScreen> { final TextEditingController emailController = TextEditingController(); final TextEditingController passwordController = TextEditingController(); final _formKey = GlobalKey<FormState>(); void handleLogin(BuildContext context) async { if (_formKey.currentState!.validate()) { final authViewModel = context.read<AuthViewModel>(); final login = await authViewModel.login( emailController.text.trim(), passwordController.text.trim(), ); if (!login && mounted) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('Usuario o contraseña incorrectos'), backgroundColor: Colors.red, ), ); } } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Login'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text( '¡Bienvenido al challenge para Banana!', textAlign: TextAlign.center, style: TextStyle( fontSize: 28, fontWeight: FontWeight.w600, ), ), const SizedBox(height: 20), const Image( image: AssetImage('assets/images/banana.png'), width: 200, ), SizedBox( width: MediaQuery.of(context).size.width * 0.8, child: Form( key: _formKey, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ TextFormLogin( emailController: emailController, hinText: 'Usuario', ), TextFormLogin( emailController: passwordController, hinText: 'Contraseña', obscure: true, ), const SizedBox( height: 20, ), ElevatedButton( style: ElevatedButton.styleFrom( minimumSize: const Size.fromHeight(40), ), onPressed: () => handleLogin(context), child: const Text('Ingresar'), ), ], ), ), ), ], ), ), ); } }
0
mirrored_repositories/flutter_banana_challenge/lib/views
mirrored_repositories/flutter_banana_challenge/lib/views/widgets/widgets.dart
export 'package:flutter_banana_challenge/views/widgets/search/product_search_widget.dart'; export 'package:flutter_banana_challenge/views/widgets/search/products_search_delegate.dart'; export 'package:flutter_banana_challenge/views/widgets/home/product_widget.dart'; export 'package:flutter_banana_challenge/views/widgets/login/text_form_login.dart';
0
mirrored_repositories/flutter_banana_challenge/lib/views/widgets
mirrored_repositories/flutter_banana_challenge/lib/views/widgets/login/text_form_login.dart
import 'package:flutter/material.dart'; class TextFormLogin extends StatelessWidget { const TextFormLogin({ super.key, required this.emailController, required this.hinText, this.obscure = false, }); final TextEditingController emailController; final String hinText; final bool obscure; @override Widget build(BuildContext context) { return TextFormField( controller: emailController, obscureText: obscure, decoration: InputDecoration(hintText: hinText), validator: (value) => value!.isEmpty ? 'El campo no debe estar vacío' : null, ); } }
0
mirrored_repositories/flutter_banana_challenge/lib/views/widgets
mirrored_repositories/flutter_banana_challenge/lib/views/widgets/home/product_widget.dart
import 'package:flutter/material.dart'; import 'package:flutter_banana_challenge/models/product_model.dart'; import 'package:intl/intl.dart'; class ProductWidget extends StatelessWidget { const ProductWidget({super.key, required this.product}); final ProductModel product; @override Widget build(BuildContext context) { //Format the price to show the currency symbol and 2 decimal places. final formattedPrice = NumberFormat.currency( decimalDigits: 2, symbol: '\$', ).format(product.price); return Hero( tag: product.id, //Material is to solve the problem of the hero animation with red texts. child: Material( child: GestureDetector( onTap: () => Navigator.pushNamed(context, 'product-detail', arguments: product), child: Container( margin: const EdgeInsets.symmetric(vertical: 5, horizontal: 10), padding: const EdgeInsets.all(10), decoration: BoxDecoration( borderRadius: BorderRadius.circular(10), color: Colors.white, boxShadow: [ BoxShadow( color: Colors.black.withOpacity(0.2), blurRadius: 5, offset: const Offset(0, 2), ), ], ), child: Row( crossAxisAlignment: CrossAxisAlignment.center, children: [ ClipRRect( borderRadius: BorderRadius.circular(10), child: Image( image: NetworkImage(product.thumbnail), width: 120, height: 120, fit: BoxFit.cover, ), ), const SizedBox(width: 10), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( product.title, overflow: TextOverflow.ellipsis, maxLines: 1, style: const TextStyle( fontSize: 18, ), ), const SizedBox(height: 2), Text( product.brand, style: const TextStyle( fontSize: 13, fontWeight: FontWeight.w500, color: Colors.grey, ), ), const SizedBox(height: 8), Text( 'USD$formattedPrice', style: const TextStyle( fontSize: 14, fontWeight: FontWeight.w800, ), ), const SizedBox(height: 8), Text( product.description, maxLines: 4, overflow: TextOverflow.ellipsis, style: const TextStyle( fontSize: 13, ), ), const SizedBox(height: 8), Text( "Stock: ${product.stock.toString()}", style: const TextStyle( fontSize: 13, ), ), ], ), ) ], ), ), ), ), ); } }
0
mirrored_repositories/flutter_banana_challenge/lib/views/widgets
mirrored_repositories/flutter_banana_challenge/lib/views/widgets/home/product_detail.dart
import 'package:carousel_slider/carousel_slider.dart'; import 'package:flutter/material.dart'; import 'package:flutter_banana_challenge/constants/constants.dart'; import 'package:intl/intl.dart'; import '../../../models/product_model.dart'; class ProductDetailScreen extends StatelessWidget { const ProductDetailScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { //The endpoint /products/{id} does not have additional information. //So I am using the same product to display the product detail. final ProductModel product = ModalRoute.of(context)!.settings.arguments as ProductModel; return Scaffold( body: CustomScrollView( slivers: [ _ProductAppBar(product: product), SliverList( delegate: SliverChildListDelegate([_ProductBody(product: product)])), ], ), ); } } class _ProductAppBar extends StatelessWidget { const _ProductAppBar({ required this.product, }); final ProductModel product; @override Widget build(BuildContext context) { return SliverAppBar( expandedHeight: 200, pinned: true, flexibleSpace: FlexibleSpaceBar( centerTitle: true, title: Text(product.title, style: const TextStyle(fontSize: 15)), background: Hero( tag: product.id, //Material is to solve the problem of the hero animation with red texts. child: Material( child: Stack( fit: StackFit.expand, children: [ FadeInImage( placeholder: const AssetImage('assets/images/loading.gif'), image: NetworkImage(product.thumbnail), fit: BoxFit.cover, ), Container( decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [ Colors.transparent, Colors.black.withOpacity(0.5), ], ), ), ), ], ), ), ), ), ); } } class _ProductBody extends StatelessWidget { const _ProductBody({ required this.product, }); final ProductModel product; @override Widget build(BuildContext context) { //Format the price to show the currency symbol and 2 decimal places. final formattedPrice = NumberFormat.currency( decimalDigits: 2, symbol: '\$', ).format(product.price); final size = MediaQuery.of(context).size; return Container( padding: const EdgeInsets.all(20), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( product.title, overflow: TextOverflow.ellipsis, maxLines: 1, style: const TextStyle( fontSize: 18, ), ), Text( "USD$formattedPrice", style: const TextStyle( color: primaryColor, fontWeight: FontWeight.bold), ), ], ), const SizedBox(height: 2), Text( product.brand, style: const TextStyle( fontSize: 13, fontWeight: FontWeight.w500, color: Colors.grey, ), ), CarouselSlider( options: CarouselOptions(height: 200.0), items: product.images.map((image) { return Builder( builder: (BuildContext context) { return Container( margin: const EdgeInsets.only(top: 10, left: 5, right: 5), child: FadeInImage( fit: BoxFit.cover, placeholder: const AssetImage('assets/images/loading.gif'), image: NetworkImage(image), ), ); }, ); }).toList(), ), //This is just to show the banner ProdDescription(size: size, product: product), ProdDescription(size: size, product: product), ProdDescription(size: size, product: product), ProdDescription(size: size, product: product), ], ), ); } } class ProdDescription extends StatelessWidget { const ProdDescription({ super.key, required this.size, required this.product, }); final Size size; final ProductModel product; @override Widget build(BuildContext context) { return Align( alignment: Alignment.topCenter, child: Container( decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(10), boxShadow: [ BoxShadow( color: Colors.grey.withOpacity(0.5), spreadRadius: 1, blurRadius: 3, offset: const Offset(0, 3), // changes position of shadow ), ], ), margin: const EdgeInsets.only(top: 20), padding: const EdgeInsets.all(20), width: size.width * 0.85, child: Column( children: [ Text( product.description, ), const SizedBox(height: 10), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Row( children: [ Icon(Icons.star, color: Colors.yellow[700]), Text(product.rating.toString()) ], ), Text("Stock: ${product.stock}") ], ) ], ), ), ); } }
0
mirrored_repositories/flutter_banana_challenge/lib/views/widgets
mirrored_repositories/flutter_banana_challenge/lib/views/widgets/search/product_search_widget.dart
import 'package:flutter/material.dart'; import '../../../models/product_model.dart'; class ProductSearchWidget extends StatelessWidget { const ProductSearchWidget({ super.key, required this.product, }); final ProductModel product; @override Widget build(BuildContext context) { return Container( margin: const EdgeInsets.only(top: 20), child: ListTile( onTap: () => Navigator.pushNamed( context, 'product-detail', arguments: product, ), leading: ClipRRect( borderRadius: BorderRadius.circular(10), child: Hero( tag: product.id, child: FadeInImage( width: 60, height: 60, fit: BoxFit.cover, placeholder: const AssetImage('assets/images/loading.gif'), image: NetworkImage(product.thumbnail), ), ), ), title: Text(product.title), subtitle: Text( product.description, maxLines: 3, overflow: TextOverflow.clip, ), ), ); } }
0
mirrored_repositories/flutter_banana_challenge/lib/views/widgets
mirrored_repositories/flutter_banana_challenge/lib/views/widgets/search/products_search_delegate.dart
import 'package:flutter/material.dart'; import 'package:flutter_banana_challenge/viewModels/product_view_model.dart'; import 'package:flutter_banana_challenge/views/widgets/widgets.dart'; import 'package:provider/provider.dart'; class ProductsSearchDelegate extends SearchDelegate { @override List<Widget> buildActions(BuildContext context) { return <Widget>[ IconButton( icon: const Icon(Icons.clear), onPressed: () { query = ''; }, ), ]; } @override String get searchFieldLabel => 'Buscar Productos'; @override Widget buildLeading(BuildContext context) { return IconButton( icon: const Icon(Icons.arrow_back), onPressed: () { close(context, ''); }, ); } @override Widget buildResults(BuildContext context) { return Consumer<ProductViewModel>( builder: (context, state, child) { if (state.searchResults.isEmpty) { return const Center( child: Text('No se encontraron resultados'), ); } return ListView.builder( itemCount: state.searchResults.length, shrinkWrap: true, itemBuilder: (context, index) { final product = state.searchResults[index]; return ProductSearchWidget(product: product); }, ); }, ); } @override Widget buildSuggestions(BuildContext context) { if (query.isEmpty) { return const Center( child: Icon(Icons.search, size: 100, color: Colors.grey), ); } final productsProvider = context.read<ProductViewModel>(); return Consumer<ProductViewModel>( builder: (context, state, child) { productsProvider.searchProducts(query); if (state.searchResults.isEmpty) { return const Center( child: Text('No se encontraron resultados'), ); } return ListView.builder( itemCount: state.searchResults.length, shrinkWrap: true, itemBuilder: (context, index) { final product = state.searchResults[index]; return ProductSearchWidget(product: product); }, ); }, ); } }
0
mirrored_repositories/flutter_banana_challenge/lib/views
mirrored_repositories/flutter_banana_challenge/lib/views/routes/routes.dart
import 'package:flutter/material.dart'; import 'package:flutter_banana_challenge/views/views.dart'; Map<String, Widget Function(BuildContext)> routes = { //Product detail screen 'product-detail': (BuildContext context) => const ProductDetailScreen(), };
0
mirrored_repositories/flutter_banana_challenge/lib
mirrored_repositories/flutter_banana_challenge/lib/models/product_model.dart
import 'dart:convert'; class ProductModel { ProductModel({ required this.id, required this.title, required this.description, required this.price, required this.discountPercentage, required this.rating, required this.stock, required this.brand, required this.category, required this.thumbnail, required this.images, }); final int id; final String title; final String description; final int price; final double discountPercentage; final double rating; final int stock; final String brand; final String category; final String thumbnail; final List<String> images; factory ProductModel.fromRawJson(String str) => ProductModel.fromJson(json.decode(str)); String toRawJson() => json.encode(toJson()); factory ProductModel.fromJson(Map<String, dynamic> json) => ProductModel( id: json["id"], title: json["title"], description: json["description"], price: json["price"], discountPercentage: json["discountPercentage"]?.toDouble(), rating: json["rating"]?.toDouble(), stock: json["stock"], brand: json["brand"], category: json["category"], thumbnail: json["thumbnail"], images: List<String>.from(json["images"].map((x) => x)), ); Map<String, dynamic> toJson() => { "id": id, "title": title, "description": description, "price": price, "discountPercentage": discountPercentage, "rating": rating, "stock": stock, "brand": brand, "category": category, "thumbnail": thumbnail, "images": List<dynamic>.from(images.map((x) => x)), }; }
0
mirrored_repositories/flutter_banana_challenge/lib
mirrored_repositories/flutter_banana_challenge/lib/models/user_model.dart
import 'dart:convert'; class UserModel { UserModel({ required this.id, required this.username, required this.email, required this.firstName, required this.lastName, required this.gender, required this.image, required this.token, }); final int id; final String username; final String email; final String firstName; final String lastName; final String gender; final String image; final String token; factory UserModel.fromRawJson(String str) => UserModel.fromJson(json.decode(str)); String toRawJson() => json.encode(toJson()); factory UserModel.fromJson(Map<String, dynamic> json) => UserModel( id: json["id"], username: json["username"], email: json["email"], firstName: json["firstName"], lastName: json["lastName"], gender: json["gender"], image: json["image"], token: json["token"], ); Map<String, dynamic> toJson() => { "id": id, "username": username, "email": email, "firstName": firstName, "lastName": lastName, "gender": gender, "image": image, "token": token, }; //Create empty user static final empty = UserModel( id: 0, username: '', email: '', firstName: '', lastName: '', gender: '', image: '', token: ''); }
0
mirrored_repositories/flutter_banana_challenge/lib
mirrored_repositories/flutter_banana_challenge/lib/services/auth_service.dart
import 'package:flutter_banana_challenge/models/user_model.dart'; import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import '../constants/constants.dart'; class AuthService { final storage = const FlutterSecureStorage(); Future<String> getToken() async { return await storage.read(key: 'auth_token') ?? ''; } Future<UserModel> login(String email, String password) async { // authenticate user using email and password UserModel user = await _authenticateUser(email, password); // store authentication token await storage.write(key: 'auth_token', value: user.token); return user; } Future<void> logout() async { // delete authentication token await storage.delete(key: 'auth_token'); } Future<String> isAuthenticated() async { // check if authentication token exists return await storage.read(key: 'auth_token') ?? ''; } Future<UserModel> _authenticateUser(String userName, String password) async { try { //Call the api to authenticate user final response = await dio.post( '$url/auth/login', data: {'username': userName, 'password': password}, ); final user = UserModel.fromJson(response.data); return user; } catch (e) { //Return empty model return UserModel.empty; } } }
0
mirrored_repositories/flutter_banana_challenge/lib
mirrored_repositories/flutter_banana_challenge/lib/services/product_service.dart
import 'dart:developer'; import 'package:flutter_banana_challenge/constants/constants.dart'; import '../models/product_model.dart'; class ProductService { Future<List<ProductModel>> getProducts() async { try { final response = await dio.get('$url/products'); final List products = response.data['products'] as List; final List<ProductModel> prods = products.map((prod) => ProductModel.fromJson(prod)).toList(); return prods; } catch (e) { log(e.toString()); return []; } } Future<List<ProductModel>> searchProducts(String query) async { try { final response = await dio.get('$url/products/search?q=$query'); final List products = response.data['products'] as List; final List<ProductModel> prods = products.map((prod) => ProductModel.fromJson(prod)).toList(); return prods; } catch (e) { log(e.toString()); return []; } } }
0
mirrored_repositories/TaskList
mirrored_repositories/TaskList/lib/task.dart
class Task { // Class properties // Underscore makes them private String _name; String _description; bool _completed; DateTime _dateTime; // Default constructor // this syntax means that it will accept a value and set it to this.name //Task(this._name, this._description); Task(this._name); // Getter and setter for name getName() => this._name; setName(name) => this._name = name; // Getter and setter for description getDescription() => this._description; setDescription(description) => this._description = description; // Getter and setter for completed isCompleted() => this._completed; setCompleted(completed) => this._completed = completed; getDateTime() => this._dateTime; setDateTime() => this._dateTime; }
0
mirrored_repositories/TaskList
mirrored_repositories/TaskList/lib/auth.dart
import 'package:firebase_auth/firebase_auth.dart'; class Authentication { final _firebaseAuth = FirebaseAuth.instance; Future<FirebaseUser> login(String email, String password) async { try { AuthResult result = await _firebaseAuth.signInWithEmailAndPassword( email: email, password: password); return result.user; } catch (e) { return null; } } }
0
mirrored_repositories/TaskList
mirrored_repositories/TaskList/lib/edit.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:vibration/vibration.dart'; import 'package:intl/intl.dart'; class TaskEdit extends StatefulWidget { final docID; final bCompleted; TaskEdit({@required this.docID, @required this.bCompleted}); @override State<StatefulWidget> createState() { return TaskEditState(docID, bCompleted); } } class TaskEditState extends State<TaskEdit> { DateTime dateTimeLocal; DateTime dateTime; var formatter = new DateFormat('dd.MM.yyyy'); final docID; var bCompleted; TaskEditState(this.docID, this.bCompleted); final collection = Firestore.instance.document('tasks'); final TextEditingController taskdescriptioncontroller = TextEditingController(); final TextEditingController tasknamecontroller = TextEditingController(); TextEditingController dateCtl = TextEditingController(); @override Widget build(BuildContext context) { strGetNameAndDescription(); return Container( decoration: new BoxDecoration( image: new DecorationImage( image: new AssetImage("./img/loginbackground.png"), fit: BoxFit.fill, ), ), child: Scaffold( backgroundColor: Colors.transparent, appBar: AppBar(title: Text('edit task')), body: Padding( padding: EdgeInsets.all(16), child: Column( children: <Widget>[ Padding( padding: EdgeInsets.only(bottom: 16), child: TextFormField( controller: tasknamecontroller, maxLines: null, autofocus: false, decoration: InputDecoration(labelText: 'Task Name'), )), Padding( padding: EdgeInsets.only(bottom: 16), child: TextFormField( maxLines: null, autofocus: false, controller: taskdescriptioncontroller, decoration: InputDecoration(labelText: 'Task description'))), Padding( padding: EdgeInsets.only(bottom: 16), child: TextFormField( readOnly: true, decoration: InputDecoration(labelText: 'Due date'), textAlign: TextAlign.center, controller: dateCtl, onTap: () async { dateTime = await showDatePicker( helpText: 'Select Due Date', context: context, initialDate: dateTimeLocal, firstDate: DateTime.now().subtract(Duration(days: 2)), lastDate: DateTime.now().add(Duration(days: 365))); if (dateTime == null) { print('test1'); dateTime = DateTime.now(); } else { print('test'); dateCtl.text = formatter.format(dateTime); } }), ), CheckboxListTile( controlAffinity: ListTileControlAffinity.leading, title: Text('Task completed'), value: bCompleted, onChanged: (bool value) { setState(() { bCompleted = value; }); }, activeColor: Colors.blue[500], checkColor: Colors.white, ), ], mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.end, )), floatingActionButton: FloatingActionButton.extended( //child: Icon(Icons.done), onPressed: () async { if (dateTime != null) { await Firestore.instance .collection('tasks') .document(docID) .updateData({ 'name': tasknamecontroller.text, 'description': taskdescriptioncontroller.text, 'completed': bCompleted, 'date': dateTime, }); } else { print('test3'); Firestore.instance .collection('tasks') .document(docID) .updateData({ 'name': tasknamecontroller.text, 'description': taskdescriptioncontroller.text, 'completed': bCompleted, 'date': dateTimeLocal, }); } Vibration.vibrate(duration: 200); //rNavigator.pushNamed(context, '/list'); Navigator.of(context).pop(); }, label: Text('Save'), icon: Icon(Icons.save_alt_sharp), backgroundColor: Colors.green, ), floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked, )); } void strGetNameAndDescription() async { DocumentSnapshot documentSnapshot; try { documentSnapshot = await Firestore.instance.collection('tasks').document(docID).get(); tasknamecontroller.text = documentSnapshot['name'].toString(); taskdescriptioncontroller.text = documentSnapshot['description'].toString(); //print('getData'); //print(documentSnapshot['date']); Timestamp timestamp = documentSnapshot['date']; if (documentSnapshot['date'] == null) { dateTimeLocal = DateTime.now(); } else { dateTimeLocal = timestamp.toDate(); dateCtl.text = formatter.format(dateTimeLocal); } //print('timestamp: ' + timestamp.toString()); //print('date: ' + timestamp.toDate().toString()); //print('getdata ' + '$datelocal'); //print(formatter.format(timestamp.toDate())); //print('getdata ' + '$dateTimeLocal'); } catch (e) {} } }
0
mirrored_repositories/TaskList
mirrored_repositories/TaskList/lib/list.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:vibration/vibration.dart'; import 'package:task_list/edit.dart'; import 'package:intl/intl.dart'; class TaskList extends StatelessWidget { // Setting reference to 'tasks' collection @override Widget build(BuildContext context) { var formatter = new DateFormat('dd.MM.yyyy'); final collection = Firestore.instance.collection('tasks'); return Scaffold( appBar: AppBar( title: Text('DailyTask'), backgroundColor: Colors.blue, ), backgroundColor: Colors.blue[300], // Making a StreamBuilder to listen to changes in real time body: Container( child: StreamBuilder<QuerySnapshot>( stream: collection.snapshots(), builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) { // Handling errors from firebase if (snapshot.hasError) return Text('Error: ${snapshot.error}'); switch (snapshot.connectionState) { // Display if still loading data case ConnectionState.waiting: return Text('Loading...'); default: return ListView( children: snapshot.data.documents .map((DocumentSnapshot document) { return Card( color: Colors.white, shadowColor: Colors.blue[400], child: Dismissible( //direction: DismissDirection.startToEnd, key: ObjectKey(document.data.keys), // ignore: missing_return confirmDismiss: (direction) async { if (direction == DismissDirection.endToStart) { final bool res = await showDialog( context: context, builder: (BuildContext context) { return AlertDialog( content: Text( "Are you sure you want to delete ${document['name']}?"), actions: <Widget>[ FlatButton( child: Text( "Cancel", style: TextStyle( color: Colors.black), ), onPressed: () { Navigator.of(context).pop(); }, ), FlatButton( child: Text( "Delete", style: TextStyle(color: Colors.red), ), onPressed: () { collection .document(document.documentID) .delete(); Vibration.vibrate(duration: 200); Navigator.of(context).pop(); }, ), ], ); }); return res; } else { var docID = document.documentID; var bCompleted = document['completed']; //var dateTime = DateTime.parse(document['date']); //print('$dateTime'); //document.documentID; Navigator.push( context, MaterialPageRoute( builder: (context) => TaskEdit( docID: docID, bCompleted: bCompleted, ))); //Navigator.pushNamed(context, '/edit'); } }, child: ExpansionTile( title: Text(document['name']), children: <Widget>[ Padding( padding: EdgeInsets.all(16), child: TextFormField( readOnly: true, maxLines: null, autofocus: false, initialValue: document['description'], decoration: InputDecoration( labelText: 'Description'))), Padding( padding: EdgeInsets.all(16), child: TextFormField( readOnly: true, maxLines: null, autofocus: false, initialValue: formatter .format(document['date'].toDate()), decoration: InputDecoration( labelText: 'Date'))), Checkbox( value: document['completed'], // Updating the database on task completion onChanged: (newValue) => collection .document(document.documentID) .updateData({'completed': newValue}), activeColor: Colors.blue[500], checkColor: Colors.white, ), ], ), secondaryBackground: Container( color: Colors.red, padding: EdgeInsets.symmetric(horizontal: 20), alignment: AlignmentDirectional.centerEnd, child: Icon( Icons.delete, color: Colors.white, ), ), background: Container( color: Colors.green, padding: EdgeInsets.symmetric(horizontal: 20), alignment: AlignmentDirectional.centerStart, child: Icon( Icons.archive, color: Colors.white, ), ), )); }).toList()); } }), ), floatingActionButton: FloatingActionButton.extended( label: Text('ADD'), onPressed: () => Navigator.pushNamed(context, '/create'), icon: Icon(Icons.add_box_outlined), backgroundColor: Colors.blue, ), floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked, bottomNavigationBar: BottomAppBar(child: Container(height: 50.0, color: Colors.blue))); } }
0
mirrored_repositories/TaskList
mirrored_repositories/TaskList/lib/login.dart
import 'package:flutter/material.dart'; import 'package:task_list/auth.dart'; class TaskLogin extends StatefulWidget { // Callback function that will be called on pressing the login button final onLogin; TaskLogin({@required this.onLogin}); @override State<StatefulWidget> createState() { return LoginState(); } } class LoginState extends State<TaskLogin> { final TextEditingController emailController = TextEditingController(); final TextEditingController passwordController = TextEditingController(); // Authentication helper final auth = Authentication(); // Function to authenticate, call callback to save the user and navigate to next page void doLogin() async { final user = await auth.login(emailController.text, passwordController.text); if (user != null) { // Calling callback in TODOState widget.onLogin(user); Navigator.pushReplacementNamed(context, '/list'); } else { _showAuthFailedDialog(); } } // Show error if login unsuccessfull void _showAuthFailedDialog() { // flutter defined function showDialog( context: context, builder: (BuildContext context) { // return object of type Dialog return AlertDialog( title: new Text('Fehler beim einloggen'), content: new Text('Überprüfen sie Ihre Email und ihr Passwort'), actions: <Widget>[ // usually buttons at the bottom of the dialog new FlatButton( child: new Text('Close'), onPressed: () { Navigator.of(context).pop(); }, ), ], ); }, ); } @override Widget build(BuildContext context) { return Container( decoration: new BoxDecoration( image: new DecorationImage( image: new AssetImage("./img/loginbackground.png"), fit: BoxFit.fill, ), ), child: Scaffold( appBar: AppBar(title: Text('Login')), backgroundColor: Colors.transparent, body: Padding( padding: EdgeInsets.all(16), child: Column( children: <Widget>[ Padding( padding: EdgeInsets.only(bottom: 16), child: TextField( controller: emailController, decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Email'), )), Padding( padding: EdgeInsets.only(bottom: 16), child: TextField( controller: passwordController, obscureText: true, decoration: InputDecoration( border: OutlineInputBorder(), labelText: 'Password'), )), RaisedButton( // Calling the doLogin function on press onPressed: doLogin, child: Text('LOGIN'), color: ThemeData().primaryColor, ) ], mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.end, )))); } }
0
mirrored_repositories/TaskList
mirrored_repositories/TaskList/lib/create.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:vibration/vibration.dart'; import 'package:intl/intl.dart'; class TaskCreate extends StatefulWidget { @override State<StatefulWidget> createState() { return TaskCreateState(); } } class TaskCreateState extends State<TaskCreate> { final collection = Firestore.instance.collection('tasks'); final TextEditingController taskdescriptioncontroller = TextEditingController(); final TextEditingController tasknamecontroller = TextEditingController(); TextEditingController dateCtl = TextEditingController(); String operad = "Operador"; var formatter = new DateFormat('dd.MM.yyyy'); DateTime dateTime = DateTime.now(); bool bCheckBoxTicked = false; @override Widget build(BuildContext context) { return Container( decoration: new BoxDecoration( image: new DecorationImage( image: new AssetImage("./img/loginbackground.png"), fit: BoxFit.fill, ), ), child: Scaffold( appBar: AppBar(title: Text('New Task')), backgroundColor: Colors.transparent, body: Padding( padding: EdgeInsets.all(16), child: Column( children: <Widget>[ Padding( padding: EdgeInsets.only(bottom: 16), child: TextField( controller: tasknamecontroller, maxLines: null, autofocus: false, decoration: InputDecoration(labelText: 'Task Name'), )), Padding( padding: EdgeInsets.only(bottom: 16), child: TextField( maxLines: null, autofocus: false, controller: taskdescriptioncontroller, decoration: InputDecoration(labelText: 'Task description'))), Padding( padding: EdgeInsets.only(bottom: 16), child: TextFormField( readOnly: true, decoration: InputDecoration(labelText: 'Due date'), textAlign: TextAlign.center, controller: dateCtl, onTap: () async { dateTime = await showDatePicker( helpText: 'Select Due Date', context: context, initialDate: DateTime.now(), firstDate: DateTime.now().subtract(Duration(days: 2)), lastDate: DateTime.now().add(Duration(days: 365))); if (dateTime == null) { dateTime = DateTime.now(); } else { dateCtl.text = formatter.format(dateTime); } }), ), ], mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.end, )), floatingActionButton: FloatingActionButton.extended( //child: Icon(Icons.done), onPressed: () async { // Creating a new document if (dateTime != null) { await collection.add({ 'name': tasknamecontroller.text, 'description': taskdescriptioncontroller.text, 'completed': bCheckBoxTicked, 'date': dateTime, }); } else await collection.add({ 'name': tasknamecontroller.text, 'description': taskdescriptioncontroller.text, 'completed': bCheckBoxTicked, 'date': DateTime.now(), }); Vibration.vibrate(duration: 200); Navigator.of(context).pop(); }, label: Text('Save'), icon: Icon(Icons.save_alt_sharp), backgroundColor: Colors.blue, ), floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked, )); } }
0
mirrored_repositories/TaskList
mirrored_repositories/TaskList/lib/main.dart
import 'package:flutter/material.dart'; import 'package:task_list/create.dart'; import 'package:task_list/list.dart'; import 'package:task_list/task.dart'; import 'package:task_list/login.dart'; import 'package:task_list/auth.dart'; import 'package:task_list/edit.dart'; import 'package:firebase_auth/firebase_auth.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return TASK(); } } class TASK extends StatefulWidget { @override State<StatefulWidget> createState() { return TaskState(); } } class TaskState extends State<TASK> { final List<Task> tasks = []; final Authentication auth = new Authentication(); FirebaseUser user; var docID; var bCompleted; var dateTime; void onTaskCreated(String name) { setState(() { tasks.add(Task(name)); }); } void onTaskToggled(Task task) { setState(() { task.setCompleted(!task.isCompleted()); }); } void onLogin(FirebaseUser user) { setState(() { this.user = user; }); } @override Widget build(BuildContext context) { return MaterialApp( title: 'DailyTask', initialRoute: '/', routes: { '/': (context) => TaskLogin(onLogin: onLogin), '/list': (context) => TaskList(), '/create': (context) => TaskCreate(), '/edit': (context) => TaskEdit( docID: docID, bCompleted: bCompleted, ), }, ); } }
0
mirrored_repositories/modern_smart_home_UI
mirrored_repositories/modern_smart_home_UI/lib/main.dart
import 'package:flutter/material.dart'; import 'pages/home_page.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: HomePage(), ); } }
0
mirrored_repositories/modern_smart_home_UI/lib
mirrored_repositories/modern_smart_home_UI/lib/pages/home_page.dart
import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:smarthomeui/util/smart_device_box.dart'; class HomePage extends StatefulWidget { const HomePage({super.key}); @override State<HomePage> createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { // padding constants final double horizontalPadding = 40; final double verticalPadding = 25; // list of smart devices List mySmartDevices = [ // [ smartDeviceName, iconPath , powerStatus ] ["Smart Light", "lib/icons/light-bulb.png", true], ["Smart AC", "lib/icons/air-conditioner.png", false], ["Smart TV", "lib/icons/smart-tv.png", false], ["Smart Fan", "lib/icons/fan.png", false], ]; // power button switched void powerSwitchChanged(bool value, int index) { setState(() { mySmartDevices[index][2] = value; }); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.grey[300], body: SafeArea( child: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // app bar Padding( padding: EdgeInsets.symmetric( horizontal: horizontalPadding, vertical: verticalPadding, ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ // menu icon Image.asset( 'lib/icons/menu.png', height: 45, color: Colors.grey[800], ), // account icon Icon( Icons.person, size: 45, color: Colors.grey[800], ) ], ), ), // welcome home Padding( padding: EdgeInsets.symmetric(horizontal: horizontalPadding), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( "Welcome Home,", style: TextStyle(fontSize: 20, color: Colors.grey.shade800), ), Text( 'Tasbeat', style: GoogleFonts.bebasNeue(fontSize: 72), ), ], ), ), const SizedBox(height: 5), const Padding( padding: EdgeInsets.symmetric(horizontal: 40.0), child: Divider( thickness: 1, color: Color.fromARGB(255, 204, 204, 204), ), ), const SizedBox(height: 25), // smart devices grid Padding( padding: EdgeInsets.symmetric(horizontal: horizontalPadding), child: Text( "Smart Devices", style: TextStyle( fontWeight: FontWeight.bold, fontSize: 24, color: Colors.grey.shade800, ), ), ), const SizedBox(height: 10), // grid SizedBox( height: 430.0, child: GridView.builder( itemCount: 4, physics: const NeverScrollableScrollPhysics(), padding: const EdgeInsets.symmetric(horizontal: 25), gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, childAspectRatio: 1 / 1.3, ), itemBuilder: (context, index) { return SmartDeviceBox( smartDeviceName: mySmartDevices[index][0], iconPath: mySmartDevices[index][1], powerOn: mySmartDevices[index][2], onChanged: (value) => powerSwitchChanged(value, index), ); }, ), ) ], ), ), ), ); } }
0
mirrored_repositories/modern_smart_home_UI/lib
mirrored_repositories/modern_smart_home_UI/lib/util/smart_device_box.dart
import 'dart:math'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; class SmartDeviceBox extends StatelessWidget { final String smartDeviceName; final String iconPath; final bool powerOn; void Function(bool)? onChanged; SmartDeviceBox({ super.key, required this.smartDeviceName, required this.iconPath, required this.powerOn, required this.onChanged, }); @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(4.0), child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(24), color: powerOn ? Colors.grey[900] : Color.fromARGB(44, 164, 167, 189), ), child: Padding( padding: const EdgeInsets.symmetric(vertical: 25.0), child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ // icon Image.asset( iconPath, height: 65, color: powerOn ? Colors.white : Colors.grey.shade700, ), // smart device name + switch Row( children: [ Expanded( child: Padding( padding: const EdgeInsets.only(left: 25.0), child: Text( smartDeviceName, style: TextStyle( fontWeight: FontWeight.bold, fontSize: 20, color: powerOn ? Colors.white : Colors.black, ), ), ), ), Transform.rotate( angle: pi / 2, child: CupertinoSwitch( value: powerOn, onChanged: onChanged, ), ), ], ) ], ), ), ), ); } }
0
mirrored_repositories/modern_smart_home_UI
mirrored_repositories/modern_smart_home_UI/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility in the flutter_test package. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:smarthomeui/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/Utility-Watch
mirrored_repositories/Utility-Watch/lib/main.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:utility_watch/globals/colors.dart'; import 'package:utility_watch/pages/SignUpSignIn/signup_page.dart'; final navigatorKey = GlobalKey<NavigatorState>(); void main() { WidgetsFlutterBinding.ensureInitialized(); SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle( systemNavigationBarColor: MyColors.backgroundColor, )); SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( navigatorKey: navigatorKey, debugShowCheckedModeBanner: false, title: 'Utility-Watch', theme: ThemeData(), home: SignUpPage(), ); } }
0
mirrored_repositories/Utility-Watch/lib
mirrored_repositories/Utility-Watch/lib/widgets/rounded_text_feilds.dart
import 'package:flutter/material.dart'; class RoundedTextField extends StatelessWidget { final String hintText; final String imagePath; final TextEditingController controller; const RoundedTextField({ Key? key, required this.hintText, required this.imagePath, required this.controller, }) : super(key: key); @override Widget build(BuildContext context) { // Get the screen size Size screenSize = MediaQuery.of(context).size; // Calculate the width and height based on screen size double width = screenSize.width * 0.6; // 60% of the screen width double height = screenSize.height * 0.05; // 6% of the screen height return Container( margin: const EdgeInsets.only(bottom: 15), width: width, height: height, decoration: BoxDecoration( borderRadius: BorderRadius.circular(25), border: Border.all( color: Color.fromRGBO(143, 143, 143, 1), width: 1, ), ), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 5), child: Row( children: [ Container( width: height - 14, height: height - 14, decoration: BoxDecoration( image: DecorationImage( image: AssetImage(imagePath), fit: BoxFit.fitHeight, ), ), ), const SizedBox(width: 30), Expanded( child: SingleChildScrollView( scrollDirection: Axis.horizontal, child: IntrinsicWidth( stepWidth: width, child: Container( height: height, child: TextFormField( controller: controller, decoration: InputDecoration( hintText: hintText, border: InputBorder.none, ), style: TextStyle( color: Color.fromRGBO(114, 114, 127, 1), fontFamily: 'SF Pro Text', fontSize: 14, letterSpacing: 0, fontWeight: FontWeight.normal, ), ), ), ), ), ), ], ), ), ); } }
0
mirrored_repositories/Utility-Watch/lib
mirrored_repositories/Utility-Watch/lib/widgets/circular_progress_container.dart
import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:percent_indicator/circular_percent_indicator.dart'; import 'package:utility_watch/globals/colors.dart'; class MyPercentageContainer extends StatefulWidget { final String heading; String percentage; MyPercentageContainer({ Key? key, required this.heading, required this.percentage, }) : super(key: key); @override State<MyPercentageContainer> createState() => _MyPercentageContainerState(); } class _MyPercentageContainerState extends State<MyPercentageContainer> { final GlobalKey<FormState> _formKey = GlobalKey<FormState>(); void _updateConsumption(String value) { setState(() { widget.percentage = value; }); } @override Widget build(BuildContext context) { return GestureDetector( onTap: () { print("Data Modified on ${DateTime.now()}"); showDialog( context: context, builder: (context) { return AlertDialog( title: Text('Enter Consumption'), content: Form( key: _formKey, child: TextFormField( decoration: InputDecoration(hintText: 'Enter value'), onSaved: (value) { if (value != null) { _updateConsumption(value); } }, ), ), actions: [ TextButton( onPressed: () { Navigator.of(context).pop(); }, child: Text('Cancel'), ), TextButton( onPressed: () { if (_formKey.currentState?.validate() ?? false) { _formKey.currentState?.save(); Navigator.of(context).pop(); } }, child: Text('Submit'), ), ], ); }, ); }, child: Container( margin: EdgeInsets.symmetric(horizontal: 10, vertical: 10), width: (MediaQuery.of(context).size.width - 80) / 2, padding: EdgeInsets.all(16), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(20), boxShadow: [ BoxShadow( color: Colors.grey.withOpacity(0.5), spreadRadius: 2, blurRadius: 5, offset: Offset(0, 3), ), ], ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Center( child: Text( widget.heading, style: GoogleFonts.nunitoSans( fontSize: 21, fontWeight: FontWeight.bold, color: MyColors.greyColor, ), ), ), SizedBox(height: 10), Center( child: CircularPercentIndicator( radius: 50.0, lineWidth: 13.0, animation: true, percent: widget.percentage != 'Goal not Set' ? double.parse(widget.percentage) / 100 : 0.0, center: SizedBox( width: 60, child: Center( child: Text( textAlign: TextAlign.center, widget.percentage != 'Goal not Set' ? widget.percentage + '%' : widget.percentage, style: TextStyle( fontWeight: widget.percentage != 'Goal not Set' ? FontWeight.bold : FontWeight.normal, fontSize: widget.percentage == 'Goal not Set' ? 15.0 : 20.0, color: widget.percentage == 'Goal not Set' ? MyColors.greyColor : Colors.black, ), ), ), ), circularStrokeCap: CircularStrokeCap.round, progressColor: MyColors.blueColor, ), ), SizedBox(height: 10), ], ), ), ); } }
0
mirrored_repositories/Utility-Watch/lib
mirrored_repositories/Utility-Watch/lib/widgets/objective_page_tile.dart
import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:utility_watch/globals/colors.dart'; class MyRoundedContainer extends StatelessWidget { final String heading; final String val; final String unit; const MyRoundedContainer({ Key? key, required this.heading, required this.val, required this.unit, }) : super(key: key); @override Widget build(BuildContext context) { return Container( width: (MediaQuery.of(context).size.width - 60) / 2, padding: EdgeInsets.all(16), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(20), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Center( child: Text( heading, style: GoogleFonts.nunitoSans( fontSize: 21, fontWeight: FontWeight.bold, color: MyColors.greyColor, ), ), ), SizedBox(height: 10), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( val, style: GoogleFonts.nunitoSans( fontSize: 26, color: MyColors.greyColor, ), ), SizedBox( width: 10, ), val != '--' ? Text( unit, style: GoogleFonts.nunitoSans( fontSize: 18, color: MyColors.greyColor, ), ) : Container() ], ), SizedBox(height: 10), ], ), ); } }
0
mirrored_repositories/Utility-Watch/lib/widgets
mirrored_repositories/Utility-Watch/lib/widgets/reading_tab/reading_tile.dart
import 'package:flutter/material.dart'; import 'package:utility_watch/globals/colors.dart'; import 'package:utility_watch/globals/months.dart'; import 'package:utility_watch/globals/styles.dart'; import 'package:utility_watch/pages/readings/month_readings.dart'; class ReadingsTile extends StatelessWidget { final String title; final String month; final int? reading; final int? previousReading; final String scale; const ReadingsTile({ super.key, required this.month, this.reading = 0, this.previousReading = 0, required this.scale, required this.title, }); @override Widget build(BuildContext context) { final increased = reading! > previousReading!; final change = reading! - previousReading!; final sign = increased ? "+" : ""; final isFilled = month != months[DateTime.now().month]; return GestureDetector( onTap: () { if (!isFilled) { Navigator.of(context).push( MaterialPageRoute( builder: (context) => MonthReadingScreen( title: title, month: month, previousReading: previousReading ?? 0, scale: scale, ), ), ); } }, child: Container( padding: const EdgeInsets.all(16), margin: const EdgeInsets.all(10), constraints: BoxConstraints( minWidth: MediaQuery.of(context).size.width * 0.33, ), decoration: BoxDecoration( color: !isFilled ? MyColors.lightGreyColor : MyColors.whiteColor, borderRadius: BorderRadius.circular(24), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: [ Text( month, style: MyStyles.heading, ), const SizedBox(height: 10), Text( isFilled ? "$sign$change" : "", style: MyStyles.subHeading.copyWith( color: increased ? MyColors.blueColor : Colors.greenAccent, ), ), isFilled ? Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.end, children: [ Text( "$reading ", style: MyStyles.normalTextStyle.copyWith(fontSize: 26), ), Text( scale, style: MyStyles.normalTextStyle.copyWith(fontSize: 18), ) ], ) : Text( ". . . .", style: MyStyles.heading.copyWith(fontWeight: FontWeight.w900), ), ], ), ), ); } }
0
mirrored_repositories/Utility-Watch/lib/widgets
mirrored_repositories/Utility-Watch/lib/widgets/reading_tab/reading_summary.dart
import 'package:flutter/material.dart'; import 'package:utility_watch/globals/colors.dart'; import 'package:utility_watch/globals/styles.dart'; import 'package:utility_watch/utils/number_format.dart'; class ReadingSummary extends StatelessWidget { final int lastReading; final double avgReading; final String scale; const ReadingSummary( {super.key, required this.lastReading, required this.avgReading, required this.scale}); @override Widget build(BuildContext context) { final formattedreading = formatNumberWithSpaces(lastReading); final formattedAvgReading = formatNumberWithSpaces(avgReading.floor()); return Container( width: double.infinity, padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10), decoration: BoxDecoration( color: MyColors.lightGreyColor, borderRadius: BorderRadius.circular(12), ), child: Row( children: [ Icon( Icons.info_outline_rounded, size: 40, color: MyStyles.subHeading.color, ), const SizedBox(width: 10), Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ Text( "Last Month - $formattedreading $scale", style: MyStyles.subHeading, ), Text( "Average per month - $formattedAvgReading${(avgReading % 1).toStringAsFixed(2).substring(1)} $scale", style: MyStyles.subHeading, ), ], ), ], ), ); } }
0
mirrored_repositories/Utility-Watch/lib/widgets
mirrored_repositories/Utility-Watch/lib/widgets/reading_tab/reading_change_tile.dart
import 'package:flutter/material.dart'; import 'package:utility_watch/globals/colors.dart'; import 'package:utility_watch/globals/styles.dart'; import 'package:utility_watch/utils/number_format.dart'; class ReadingChangeTile extends StatelessWidget { final int reading; final int increment; final bool highlight; const ReadingChangeTile({ super.key, required this.reading, required this.increment, required this.highlight, }); @override Widget build(BuildContext context) { final possitive = increment > 0; final formattedReading = formatNumberWithSpaces(reading + increment); final formattedIncrement = formatNumberWithSpaces(increment); return Container( margin: const EdgeInsets.symmetric(horizontal: 20), decoration: BoxDecoration( color: highlight ? Colors.transparent : Colors.transparent), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( formattedReading, style: MyStyles.heading.copyWith( fontSize: highlight ? 32 : 28, ), ), const SizedBox(width: 40), Text( possitive ? "+ $formattedIncrement" : formattedIncrement, style: MyStyles.subHeading.copyWith( fontSize: highlight ? 26 : 18, color: possitive ? MyColors.blueColor : Colors.green, ), ), ], ), ); } }
0
mirrored_repositories/Utility-Watch/lib
mirrored_repositories/Utility-Watch/lib/globals/assets.dart
class Assets { static const String icons = "assets/icons/"; static const String readingsIcon = "${icons}readings.svg"; static const String insightsIcon = "${icons}insights.svg"; static const String objectiveIcon = "${icons}objective.png"; static const String accountIcon = "${icons}account.png"; static const String infoIcon = "${icons}i.svg"; }
0
mirrored_repositories/Utility-Watch/lib
mirrored_repositories/Utility-Watch/lib/globals/styles.dart
import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:utility_watch/globals/colors.dart'; class MyStyles { static var heading = GoogleFonts.nunitoSans( fontSize: 21, fontWeight: FontWeight.bold, color: MyColors.greyColor, ); static var subHeading = GoogleFonts.nunitoSans( fontSize: 17, fontWeight: FontWeight.bold, color: MyColors.greyColor, ); static var normalTextStyle = GoogleFonts.nunitoSans( fontSize: 14, fontWeight: FontWeight.normal, color: MyColors.greyColor, ); }
0
mirrored_repositories/Utility-Watch/lib
mirrored_repositories/Utility-Watch/lib/globals/months.dart
Map<int, String> months = { 1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'July', 8: 'August', 9: 'September', 10: 'October', 11: 'November', 12: 'December', };
0
mirrored_repositories/Utility-Watch/lib
mirrored_repositories/Utility-Watch/lib/globals/colors.dart
import 'package:flutter/material.dart'; class MyColors { static const backgroundColor = Color.fromRGBO(238, 233, 233, 1); static const whiteColor = Color.fromRGBO(255, 255, 255, 1); static const blueColor = Color.fromRGBO(0, 122, 255, 1); static const greyColor = Color.fromRGBO(108, 108, 108, 1); static const lightGreyColor = Color(0xffE6E6E6); }
0
mirrored_repositories/Utility-Watch/lib/pages
mirrored_repositories/Utility-Watch/lib/pages/insights/insights_tab.dart
import 'dart:math'; import 'package:flutter/material.dart'; import 'package:fl_chart/fl_chart.dart'; import 'package:utility_watch/globals/colors.dart'; import 'package:utility_watch/globals/months.dart'; class InsightsPage extends StatefulWidget { const InsightsPage({super.key}); @override State<InsightsPage> createState() => _InsightsPageState(); } class _InsightsPageState extends State<InsightsPage> { String? selectedValue = "Electricity"; bool bill = true; String heading1 = "Monthly use of electricity in Kwh" ; String heading2 = "Weekly use of electricity in Kwh" ; SideTitles get _bottomTitles2 => SideTitles( showTitles: true, getTitlesWidget: (value, meta) { String text = ''; switch (value.toInt()) { case 0: text = 'Mon'; break; case 2: text = 'Tue'; break; case 4: text = 'Wed'; break; case 6: text = 'Thu'; break; case 8: text = 'Fri'; break; case 10: text = 'Sat'; break; } return Text(text); }, ); final List<FlSpot> dummyData1 = [ FlSpot(0, 10), FlSpot(2, 2), FlSpot(4, 8), FlSpot(6, 4), FlSpot(8, 5), FlSpot(10, 1), ]; List<BarChartGroupData> _chartGroups() { return dummyData1 .map((point) => BarChartGroupData( x: point.x.toInt(), barRods: [BarChartRodData(toY: point.y)])) .toList(); } SideTitles get _bottomTitles => SideTitles( showTitles: true, getTitlesWidget: (value, meta) { String text = ''; switch (value.toInt()) { case 0: text = 'Jan'; break; case 2: text = 'Mar'; break; case 4: text = 'May'; break; case 6: text = 'Jul'; break; case 8: text = 'Sep'; break; case 10: text = 'Nov'; break; } return Text( text, style: TextStyle(color: Colors.black), ); }, ); SideTitles get _leftTitles => SideTitles( showTitles: true, getTitlesWidget: (value, meta) { String text = ''; switch (value.toInt()) { case 2: text = '1'; break; case 4: text = '2'; break; case 6: text = '3'; break; case 8: text = '4'; break; case 10: text = '5'; break; } return Container( margin: EdgeInsets.only(left: 10), child: Text( text, style: TextStyle(color: Colors.black), ), ); }, ); Widget LINECHART() { return Container( padding: EdgeInsets.all(20), child: LineChart(LineChartData( borderData: FlBorderData(border: Border(bottom: BorderSide())), gridData: FlGridData(show: false), titlesData: FlTitlesData( bottomTitles: AxisTitles(sideTitles: _bottomTitles), leftTitles: AxisTitles(sideTitles: _leftTitles), topTitles: AxisTitles(sideTitles: SideTitles(showTitles: false)), rightTitles: AxisTitles(sideTitles: SideTitles(showTitles: false)), ), lineBarsData: [ LineChartBarData( spots: dummyData1, isCurved: true, color: Colors.blue, barWidth: 3, isStrokeCapRound: false, dotData: FlDotData(show: false), belowBarData: BarAreaData(show: false), ), ], )), ); } Widget BarGraph() { return AspectRatio( aspectRatio: 1, child: BarChart( BarChartData( barGroups: _chartGroups(), borderData: FlBorderData( border: const Border( bottom: BorderSide(), )), gridData: FlGridData(show: false), titlesData: FlTitlesData( bottomTitles: AxisTitles(sideTitles: _bottomTitles2), leftTitles: AxisTitles(sideTitles: _leftTitles,), topTitles: AxisTitles( sideTitles: SideTitles( getTitlesWidget: (value, meta) => Container(), showTitles: true, reservedSize: 20, ), ), rightTitles: AxisTitles(sideTitles: SideTitles(showTitles: false)), ), ), ), ); } Widget Electricity() { return Column( children: [ Text(heading1,style: TextStyle(color:Colors.black,fontWeight: FontWeight.w500,fontSize: 20),), Padding(padding: EdgeInsets.only(top: 10)), Container( decoration: BoxDecoration( color: MyColors.whiteColor, borderRadius: BorderRadius.all(Radius.circular(20))), child: AspectRatio(aspectRatio: 1, child: LINECHART()), ), Padding(padding: EdgeInsets.only(top: 40)), Text(heading2,style: TextStyle(color:Colors.black,fontWeight: FontWeight.w500,fontSize: 20),), Padding(padding: EdgeInsets.only(top: 10)), Container( decoration: BoxDecoration( color: MyColors.whiteColor, borderRadius: BorderRadius.all(Radius.circular(20))), child: BarGraph(), ), ], ); } Widget Water() { return Column( children: [ Text(heading1,style: TextStyle(color:Colors.black,fontWeight: FontWeight.w500,fontSize: 20),), Padding(padding: EdgeInsets.only(top: 10)), Container( decoration: BoxDecoration( color: MyColors.whiteColor, borderRadius: BorderRadius.all(Radius.circular(20))), child: AspectRatio(aspectRatio: 1, child: LINECHART()), ), Padding(padding: EdgeInsets.only(top: 40)), Text(heading2,style: TextStyle(color:Colors.black,fontWeight: FontWeight.w500,fontSize: 20),), Padding(padding: EdgeInsets.only(top: 10)), Container( decoration: BoxDecoration( color: MyColors.whiteColor, borderRadius: BorderRadius.all(Radius.circular(20))), child: BarGraph(), ), ], ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( automaticallyImplyLeading: false, title: Text( "Insights", style: TextStyle(color: MyColors.blueColor), ), backgroundColor: MyColors.backgroundColor, elevation: 0, centerTitle: true, ), body: SingleChildScrollView( child: Container( color: MyColors.backgroundColor, child: Column(children: [ Row( children: [ Expanded( child: SizedBox(), ), Container( height: 30, padding: EdgeInsets.only(left: 10, right: 10), margin: EdgeInsets.only(right: 5), decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(20)), border: Border.all(color: MyColors.greyColor)), child: DropdownButton<String>( value: selectedValue, onChanged: (newValue) { setState(() { selectedValue = newValue; bill = newValue == 'Electricity'; heading1 = bill ? "Monthly use of electricity in Kwh" : "Monthly use of water in L"; heading2 = bill ? "Weekly use of electricity in Kwh" : "Weekly use of water in L"; }); }, underline: Container(), items: <String>['Electricity', 'Water'] .map<DropdownMenuItem<String>>((String value) { return DropdownMenuItem<String>( value: value, child: Text( value, style: TextStyle(color: MyColors.blueColor), ), ); }).toList(), ), ) ], ), Padding(padding: EdgeInsets.only(top: 10)), Container( margin: EdgeInsets.all(20), child: bill ? Electricity() : Water(), ) ]), ), ), ); } }
0
mirrored_repositories/Utility-Watch/lib/pages
mirrored_repositories/Utility-Watch/lib/pages/account/account_tab.dart
import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:utility_watch/globals/colors.dart'; class AccountPage extends StatelessWidget { const AccountPage({super.key}); @override Widget build(BuildContext context) { return SingleChildScrollView( child: Container( margin: EdgeInsets.all(10), padding: EdgeInsets.only(top: 40), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.center, children: [ CircleAvatar( radius: 29, backgroundColor: MyColors.greyColor, child: Text( "AK", style: TextStyle( color: Colors.white, fontSize: 24, fontWeight: FontWeight.bold, ), ), ), SizedBox(width: 20), Text( "Ashutosh Kumar", style: GoogleFonts.nunitoSans( fontSize: 26, fontWeight: FontWeight.bold, color: MyColors.greyColor, ), ), ], ), SizedBox(width: 20), Divider(color: MyColors.greyColor), SizedBox(height: 20), // Increase space between menu items _buildMenuItem(Icons.notifications_outlined, "Notification"), _buildMenuItem(Icons.leaderboard, "Leaderboard"), _buildMenuItem(Icons.analytics, "Report and Analytics"), _buildMenuItem(Icons.help_outline, "Help"), _buildMenuItem(Icons.person_add, "Invite a friend"), ], ), ), ); } ListTile _buildMenuItem(IconData icon, String title) { return ListTile( leading: Icon(icon, color: MyColors.greyColor), title: Text( title, style: GoogleFonts.nunitoSans( fontSize: 21, fontWeight: FontWeight.bold, color: Colors.black87, ), ), onTap: () { // Handle menu item tap }, ); } }
0
mirrored_repositories/Utility-Watch/lib/pages
mirrored_repositories/Utility-Watch/lib/pages/SignUpSignIn/signup_page.dart
import 'package:flutter/material.dart'; import 'package:utility_watch/globals/colors.dart'; import 'package:utility_watch/pages/home/home.dart'; import 'package:utility_watch/widgets/rounded_text_feilds.dart'; class SignUpPage extends StatefulWidget { const SignUpPage({super.key}); @override State<SignUpPage> createState() => SignUpPageState(); } class SignUpPageState extends State<SignUpPage> { bool isSignUp = false; final emailController = TextEditingController(); final passwordController = TextEditingController(); final emailControllerSignIn = TextEditingController(); final passwordControllerSignIn = TextEditingController(); final userNameController = TextEditingController(); final phoneController = TextEditingController(); @override Widget build(BuildContext context) { var screenSize = MediaQuery.of(context).size; return SafeArea( child: Scaffold( body: SingleChildScrollView( child: Container( margin: EdgeInsets.only(top: 50, left: 20, right: 20), child: Center( child: Column( children: [ CircleAvatar( radius: 30, child: Image.asset( "assets/icons/app_logo.png", ), ), SizedBox(height: 20), Stack( children: [ Container( decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(30), boxShadow: [ BoxShadow( color: Colors.black.withOpacity(0.5), spreadRadius: 5, blurRadius: 7, offset: Offset(0, 2), ), ], ), margin: EdgeInsets.only(right: 40, left: 40, bottom: 25), padding: EdgeInsets.only(top: 10), height: screenSize.height / 1.8, width: double.maxFinite - 150, child: Center( child: Column( // mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.center, children: [ Container( width: 188, decoration: BoxDecoration( color: MyColors.lightGreyColor, borderRadius: BorderRadius.circular(25)), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ GestureDetector( onTap: () { setState(() { isSignUp = false; }); }, child: Container( width: 94, height: 32, decoration: BoxDecoration( borderRadius: BorderRadius.circular(25), color: isSignUp ? MyColors.lightGreyColor : MyColors.blueColor, ), child: Center( child: Text( 'Sign In', textAlign: TextAlign.center, style: TextStyle( color: isSignUp ? MyColors.greyColor : Colors.white, fontFamily: 'SF Pro Text', fontSize: 14, letterSpacing: 0, fontWeight: FontWeight.normal), ), )), ), GestureDetector( onTap: () { setState(() { isSignUp = true; }); }, child: Container( width: 94, height: 32, decoration: BoxDecoration( borderRadius: BorderRadius.circular(25), color: isSignUp ? MyColors.blueColor : MyColors.lightGreyColor, ), child: Center( child: Text( 'Sign Up', textAlign: TextAlign.center, style: TextStyle( color: isSignUp ? Colors.white : MyColors.greyColor, fontFamily: 'SF Pro Text', fontSize: 14, letterSpacing: 0, fontWeight: FontWeight.normal), ), )), ), ], ), ), Container( height: screenSize.height / 1.8 - 60, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ ...isSignUp ? SignUpWidget( userNameController, phoneController, emailController, passwordController) : SignInWidget(emailControllerSignIn, passwordControllerSignIn), ], ), ), // ...isSignUp // ? SignUpWidget( // userNameController, // phoneController, // emailController, // passwordController) // : SignInWidget(emailControllerSignIn, // passwordControllerSignIn), ], ), ), ), Positioned( bottom: 0, right: screenSize.width / 2 - 80, child: SizedBox( width: 120, child: ElevatedButton( onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (context) => const HomePage()), ); }, child: isSignUp ? Text("SIGN UP") : Text("SIGN IN"), style: ElevatedButton.styleFrom( backgroundColor: MyColors.blueColor, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20), ), ), ), ), ), ], ), ], ), ), ), ), ), ); } } List<Widget> SignUpWidget( TextEditingController userNameController, TextEditingController phoneController, TextEditingController emailController, TextEditingController passwordController) { return [ RoundedTextField( hintText: "UserName", imagePath: "assets/icons/person.png", controller: userNameController), RoundedTextField( hintText: "Phone", imagePath: "assets/icons/phone.png", controller: phoneController), RoundedTextField( hintText: "Email", imagePath: "assets/icons/email.png", controller: emailController), RoundedTextField( hintText: "Password", imagePath: "assets/icons/lock.png", controller: passwordController), ]; } List<Widget> SignInWidget(TextEditingController emailController, TextEditingController passwordController) { return [ RoundedTextField( hintText: "Email", imagePath: "assets/icons/email.png", controller: emailController), RoundedTextField( hintText: "Password", imagePath: "assets/icons/lock.png", controller: passwordController), ]; }
0
mirrored_repositories/Utility-Watch/lib/pages
mirrored_repositories/Utility-Watch/lib/pages/home/home.dart
import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:utility_watch/globals/assets.dart'; import 'package:utility_watch/globals/colors.dart'; import 'package:utility_watch/globals/styles.dart'; import 'package:utility_watch/pages/account/account_tab.dart'; import 'package:utility_watch/pages/insights/insights_tab.dart'; import 'package:utility_watch/pages/objective/objective_tab.dart'; import 'package:utility_watch/pages/readings/readings_tab.dart'; class HomePage extends StatefulWidget { const HomePage({super.key}); @override State<HomePage> createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { int selectedIndex = 0; List<Widget> tabs = [ ReadingPage(), const InsightsPage(), ObjectivePage(), const AccountPage(), ]; List<String> labels = [ "Reading", "Insights", "Objective", "Account", ]; List<String> titles = ["Your Readings", "", "Goal Settings", ""]; void updateTab(int index) { setState(() { selectedIndex = index; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: titles[selectedIndex] != "" ? AppBar( elevation: 0, backgroundColor: MyColors.backgroundColor, title: Text( titles[selectedIndex], style: MyStyles.heading.copyWith(color: MyColors.blueColor), ), centerTitle: true, ) : null, backgroundColor: MyColors.backgroundColor, body: tabs[selectedIndex], bottomNavigationBar: _bottomNavigationBar(), ); } BottomNavigationBar _bottomNavigationBar() { return BottomNavigationBar( currentIndex: selectedIndex, backgroundColor: MyColors.backgroundColor, showUnselectedLabels: true, selectedFontSize: 11, unselectedFontSize: 11, selectedLabelStyle: const TextStyle(fontWeight: FontWeight.bold), selectedIconTheme: const IconThemeData(size: 30), fixedColor: MyColors.blueColor, onTap: (value) => updateTab(value), type: BottomNavigationBarType.fixed, items: [ BottomNavigationBarItem( icon: SvgPicture.asset( Assets.readingsIcon, color: labels[selectedIndex] == "Reading" ? MyColors.blueColor : MyColors.greyColor, height: 24, ), label: "Reading", ), BottomNavigationBarItem( icon: SvgPicture.asset( Assets.insightsIcon, color: labels[selectedIndex] == "Insights" ? MyColors.blueColor : MyColors.greyColor, height: 24, ), label: "Insights", ), BottomNavigationBarItem( icon: Image.asset( Assets.objectiveIcon, color: labels[selectedIndex] == "Objective" ? MyColors.blueColor : MyColors.greyColor, height: 26, ), label: "Objective", ), BottomNavigationBarItem( icon: Image.asset( Assets.accountIcon, color: labels[selectedIndex] == "Account" ? MyColors.blueColor : MyColors.greyColor, height: 26, ), label: "Account", ), ], ); } }
0
mirrored_repositories/Utility-Watch/lib/pages
mirrored_repositories/Utility-Watch/lib/pages/objective/objective_tab.dart
import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:utility_watch/globals/colors.dart'; import 'package:utility_watch/widgets/circular_progress_container.dart'; import 'package:utility_watch/widgets/objective_page_tile.dart'; class ObjectivePage extends StatefulWidget { ObjectivePage({super.key}); @override State<ObjectivePage> createState() => _ObjectivePageState(); } class _ObjectivePageState extends State<ObjectivePage> { final GlobalKey<FormState> _formKey = GlobalKey<FormState>(); String electricityConsumption = '--'; String waterConsumption = '--'; String monthlyElectricityGoal = '--'; String monthlyWaterGoal = '--'; void _updateConsumption(String type, String value) { setState(() { if (type == 'electricity') { electricityConsumption = value; } else if (type == 'water') { waterConsumption = value; } else if (type == 'monthlyElectricity') { monthlyElectricityGoal = value; } else if (type == 'monthlyWater') { monthlyWaterGoal = value; } }); } @override Widget build(BuildContext context) { return SingleChildScrollView( child: Expanded( child: Container( margin: EdgeInsets.only(top: 20, left: 20, right: 20), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( "Today's Consumption", style: GoogleFonts.nunitoSans( fontSize: 24, color: MyColors.greyColor, ), ), SizedBox(height: 10), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ _buildRoundedContainer( type: 'electricity', heading: 'Electricity', value: electricityConsumption), SizedBox(width: 20), _buildRoundedContainer( type: 'water', heading: 'Water', value: waterConsumption), ], ), SizedBox(height: 20), Text( "Monthly Goals", style: GoogleFonts.nunitoSans( fontSize: 24, color: MyColors.greyColor, ), ), SizedBox(height: 10), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ _buildRoundedContainer( type: 'monthlyElectricity', heading: 'Electricity', value: monthlyElectricityGoal), SizedBox(width: 20), _buildRoundedContainer( type: 'monthlyWater', heading: 'Water', value: monthlyWaterGoal), ], ), SizedBox(height: 20), Text( "Track Your Goals", style: GoogleFonts.nunitoSans( fontSize: 24, color: MyColors.greyColor, ), ), SizedBox(height: 10), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ MyPercentageContainer( heading: "Electricity", percentage: "Goal not Set"), // SizedBox(width: 10), MyPercentageContainer(heading: "Water", percentage: "Goal not Set"), ], ), ], ), ), ), ); } Widget _buildRoundedContainer( {required String type, required String heading, required String value}) { return GestureDetector( onTap: () { print("Data Modified on ${DateTime.now()}"); showDialog( context: context, builder: (context) { return AlertDialog( title: Text('Enter $heading Consumption'), content: Form( key: _formKey, child: TextFormField( decoration: InputDecoration(hintText: 'Enter value'), onSaved: (value) { if (value != null) { _updateConsumption(type, value); } }, ), ), actions: [ TextButton( onPressed: () { Navigator.of(context).pop(); }, child: Text('Cancel'), ), TextButton( onPressed: () { if (_formKey.currentState?.validate() ?? false) { _formKey.currentState?.save(); Navigator.of(context).pop(); } }, child: Text('Submit'), ), ], ); }, ); }, child: MyRoundedContainer( heading: heading, val: value, unit: heading == 'Electricity' ? "kWh" : 'L', ), ); } }
0
mirrored_repositories/Utility-Watch/lib/pages
mirrored_repositories/Utility-Watch/lib/pages/readings/dummy_data.dart
List<Map<String, dynamic>> energyReadings = [ {"month": "January", "reading": 300, "previous_reading": 0}, {"month": "February", "reading": 400, "previous_reading": 300}, {"month": "March", "reading": 350, "previous_reading": 400}, {"month": "April", "reading": 370, "previous_reading": 350}, {"month": "May", "reading": 400, "previous_reading": 370}, {"month": "June", "reading": 420, "previous_reading": 400}, {"month": "July", "reading": 390, "previous_reading": 420}, {"month": "August", "reading": 400, "previous_reading": 390}, {"month": "September", "reading": 410, "previous_reading": 400}, ];
0
mirrored_repositories/Utility-Watch/lib/pages
mirrored_repositories/Utility-Watch/lib/pages/readings/readings_tab.dart
import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:utility_watch/globals/assets.dart'; import 'package:utility_watch/globals/colors.dart'; import 'package:utility_watch/globals/months.dart'; import 'package:utility_watch/globals/styles.dart'; import 'package:utility_watch/pages/readings/dummy_data.dart'; import 'package:utility_watch/widgets/reading_tab/reading_tile.dart'; class ReadingPage extends StatelessWidget { ReadingPage({super.key}); List<Widget> readingTiles = energyReadings .map((map) => ReadingsTile( month: map["month"]!, scale: 'kWh', reading: map["reading"], previousReading: map['previous_reading'], title: "Electricity Readings", )) .toList() ..add( ReadingsTile( month: months[DateTime.now().month]!, scale: 'kWh', previousReading: energyReadings .where((element) => element['month'] == months[DateTime.now().month - 1]) .last['reading'], title: "Electricity Readings", ), ); List<Widget> waterReadings = energyReadings .map((map) => ReadingsTile( month: map["month"]!, scale: 'L', reading: map["reading"], previousReading: map['previous_reading'], title: "Water Readings", )) .toList() ..add(ReadingsTile( month: months[DateTime.now().month]!, scale: 'L', previousReading: energyReadings .where( (element) => element['month'] == months[DateTime.now().month - 1]) .last['reading'], title: "Water Readings", )); @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(vertical: 16), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ const SizedBox(height: 10), Padding( padding: const EdgeInsets.symmetric(horizontal: 16.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( "Energy Consumption", style: MyStyles.heading, ), infoButton(onTap: () {}) ], ), ), const SizedBox(height: 20), SingleChildScrollView( scrollDirection: Axis.horizontal, child: Row( children: readingTiles, ), ), const SizedBox(height: 40), Padding( padding: const EdgeInsets.symmetric(horizontal: 16.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text( "Water Consumption", style: MyStyles.heading, ), infoButton(onTap: () {}) ], ), ), const SizedBox(height: 20), SingleChildScrollView( scrollDirection: Axis.horizontal, child: Row( children: waterReadings, ), ), ], ), ); } Widget infoButton({required VoidCallback onTap}) { return GestureDetector( onTap: onTap, child: Container( padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 5), decoration: BoxDecoration( color: MyColors.lightGreyColor, borderRadius: BorderRadius.circular(20), ), child: SvgPicture.asset( Assets.infoIcon, color: MyColors.greyColor, ), ), ); } }
0
mirrored_repositories/Utility-Watch/lib/pages
mirrored_repositories/Utility-Watch/lib/pages/readings/month_readings.dart
import 'package:flutter/material.dart'; import 'package:utility_watch/globals/colors.dart'; import 'package:utility_watch/globals/styles.dart'; import 'package:utility_watch/pages/readings/dummy_data.dart'; import 'package:utility_watch/utils/back_button.dart'; import 'package:utility_watch/widgets/reading_tab/reading_change_tile.dart'; import 'package:utility_watch/widgets/reading_tab/reading_summary.dart'; class MonthReadingScreen extends StatefulWidget { final String title; final String month; final int previousReading; final String scale; const MonthReadingScreen({ super.key, required this.title, required this.month, required this.previousReading, required this.scale, }); @override State<MonthReadingScreen> createState() => _MonthReadingScreenState(); } class _MonthReadingScreenState extends State<MonthReadingScreen> { int noOfTiles = 0; int selectedIndex = 0; double avgReading = 0; int finalReading = 0; @override void initState() { noOfTiles = (widget.previousReading / 10).floor() * 2; int total = 0; for (var map in energyReadings) { total += map['reading'] as int; } avgReading = total / energyReadings.length; super.initState(); } @override Widget build(BuildContext context) { final size = MediaQuery.of(context).size; return SafeArea( top: false, child: Scaffold( backgroundColor: MyColors.backgroundColor, appBar: AppBar( backgroundColor: MyColors.backgroundColor, elevation: 0, leading: backButton, ), body: Stack( children: [ Positioned( top: 0, right: 0, left: 0, child: Column( children: [ const SizedBox(height: 30), Center( child: Text( widget.title, style: MyStyles.heading.copyWith(color: MyColors.blueColor), ), ), const SizedBox(height: 40), Text( widget.month, style: MyStyles.heading, ), ], ), ), Transform.translate( offset: const Offset(0, -30), child: Align( alignment: const Alignment(0, 0), child: Container( height: 50, width: double.infinity, padding: const EdgeInsets.only(right: 20), decoration: const BoxDecoration( color: MyColors.lightGreyColor, border: Border.symmetric( horizontal: BorderSide(color: MyColors.greyColor), ), ), child: const Row( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.center, children: [ Text( "Approximate\nchange", textAlign: TextAlign.center, style: TextStyle( color: MyColors.blueColor, fontSize: 12, ), ), ], ), ), ), ), Transform.translate( offset: const Offset(0, -30), child: Align( alignment: const Alignment(0, 0), child: SizedBox( height: size.height / 2, child: ListWheelScrollView.useDelegate( squeeze: 1, diameterRatio: 2.5, itemExtent: 60, perspective: 0.01, physics: const FixedExtentScrollPhysics(), controller: FixedExtentScrollController( initialItem: (noOfTiles / 2).floor(), ), onSelectedItemChanged: (int index) { setState(() { selectedIndex = index; finalReading = selectedIndex * 10; if (index >= noOfTiles - 5) { noOfTiles += 10; } }); }, childDelegate: ListWheelChildBuilderDelegate( childCount: noOfTiles, builder: (context, index) { return ReadingChangeTile( reading: widget.previousReading, increment: index * 10 - widget.previousReading, highlight: index == selectedIndex || (index == (noOfTiles / 2).floor() && selectedIndex == 0), ); }, ), ), ), ), ), Align( alignment: const Alignment(0, 1), child: Padding( padding: const EdgeInsets.symmetric(vertical: 30, horizontal: 20), child: ReadingSummary( lastReading: widget.previousReading, avgReading: avgReading, scale: widget.scale, ), ), ), ], ), ), ); } }
0
mirrored_repositories/Utility-Watch/lib
mirrored_repositories/Utility-Watch/lib/utils/number_format.dart
String formatNumberWithSpaces(int number) { String numberString = number.toString(); String formattedString = ''; int counter = 0; for (int i = numberString.length - 1; i >= 0; i--) { formattedString = numberString[i] + formattedString; counter++; if (i == numberString.length - 2) { counter++; continue; } if (counter % 2 == 0 && i != 0) { formattedString = ' $formattedString'; } } return formattedString; }
0
mirrored_repositories/Utility-Watch/lib
mirrored_repositories/Utility-Watch/lib/utils/back_button.dart
import 'package:flutter/material.dart'; import 'package:utility_watch/globals/colors.dart'; import 'package:utility_watch/main.dart'; final backButton = IconButton( onPressed: () => navigatorKey.currentState!.pop(), icon: const Icon( Icons.arrow_back_ios_new_rounded, color: MyColors.blueColor, ), );
0
mirrored_repositories/Utility-Watch
mirrored_repositories/Utility-Watch/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility in the flutter_test package. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:utility_watch/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/calmly
mirrored_repositories/calmly/lib/main.dart
import 'dart:io'; import 'package:flutter/material.dart'; import 'package:calmly/src/app.dart'; import 'src/bloc/breathe/breathe_bloc.dart'; import 'src/bloc/breathe/breathe_counter_bloc.dart'; import 'src/bloc/calm_box/calm_box_bloc.dart'; import 'src/config/app_state.dart'; import 'src/utils/local_db.dart'; import 'package:path_provider/path_provider.dart'; import 'package:provider/provider.dart'; import 'package:hive/hive.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); Directory directory = await getApplicationDocumentsDirectory(); var path = directory.path; Hive.init(path); await LocalDB().init(); runApp( MultiProvider( providers: [ Provider<CalmBoxBloc>(create: (_) => CalmBoxBloc()), Provider<BreatheBloc>(create: (_) => BreatheBloc()), Provider<BreatheCounterBloc>(create: (_) => BreatheCounterBloc()), ChangeNotifierProvider<AppState>(create: (_) => AppState()), ], child: App(), ), ); }
0
mirrored_repositories/calmly/lib
mirrored_repositories/calmly/lib/src/app.dart
import 'package:calmly/src/config/theme_config.dart'; import 'package:calmly/src/screens/home_screen.dart'; import 'package:calmly/src/utils/system_theme.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'config/app_state.dart'; class App extends StatelessWidget { @override Widget build(BuildContext context) { return Consumer<AppState>( builder: (_, appState, __) { //change statusbar cxolor SystemTheme.changeStatusBarColor(appState); return MaterialApp( title: 'Flutter Demo', theme: SystemTheme.isDark(appState) ? ThemeConfig.darkTheme : ThemeConfig.lightTheme, home: HomeScreen(), ); }, ); } }
0
mirrored_repositories/calmly/lib/src
mirrored_repositories/calmly/lib/src/constants/custom_icons_icons.dart
/// Flutter icons CustomIcons /// Copyright (C) 2021 by original authors @ fluttericon.com, fontello.com /// This font was generated by FlutterIcon.com, which is derived from Fontello. /// /// To use this font, place it in your fonts/ directory and include the /// following in your pubspec.yaml /// /// flutter: /// fonts: /// - family: CustomIcons /// fonts: /// - asset: fonts/CustomIcons.ttf /// /// /// * Entypo, Copyright (C) 2012 by Daniel Bruce /// Author: Daniel Bruce /// License: SIL (http://scripts.sil.org/OFL) /// Homepage: http://www.entypo.com /// import 'package:flutter/widgets.dart'; class CustomIcons { CustomIcons._(); static const _kFontFam = 'CustomIcons'; static const String _kFontPkg = null; static const IconData dot_3 = IconData(0xe800, fontFamily: _kFontFam, fontPackage: _kFontPkg); }
0
mirrored_repositories/calmly/lib/src
mirrored_repositories/calmly/lib/src/constants/color_constants.dart
import 'package:flutter/material.dart'; import 'dart:ui'; Color hexToColor(String hex) { assert(RegExp(r'^#([0-9a-fA-F]{6})|([0-9a-fA-F]{8})$').hasMatch(hex), 'hex color must be #rrggbb or #rrggbbaa'); return Color( int.parse(hex.substring(1), radix: 16) + (hex.length == 7 ? 0xff000000 : 0x00000000), ); } class ColorConstants { static Color lightScaffoldBackgroundColor = hexToColor('#F9F9F9'); static Color darkScaffoldBackgroundColor = hexToColor('#2F2E2E'); static Color secondaryAppColor = hexToColor('#5E92F3'); static Color secondaryDarkAppColor = Colors.white; }
0
mirrored_repositories/calmly/lib/src
mirrored_repositories/calmly/lib/src/constants/constants.dart
enum ThemeSetting { system, dark, light } enum Breathe { inhale, holdBreathe, exhale, idle, } enum CalmBox { expand, shrink, busy, completedExpand, completedShrink, cancel, stop, }
0
mirrored_repositories/calmly/lib/src
mirrored_repositories/calmly/lib/src/components/white_line.dart
import 'package:flutter/material.dart'; class DividerLine extends StatelessWidget { const DividerLine({ Key key, @required this.height, @required this.width, this.isDark, }) : super(key: key); final double height; final double width; final bool isDark; @override Widget build(BuildContext context) { return Container( color: isDark ? const Color(0xFF000000) : const Color(0xFFFFFFFF), height: height, width: width, ); } }
0
mirrored_repositories/calmly/lib/src
mirrored_repositories/calmly/lib/src/components/count_down.dart
import 'dart:async'; import 'package:flutter/material.dart'; class CountDown extends StatefulWidget { const CountDown({ Key key, this.countDownTime, }) : super(key: key); final int countDownTime; @override _CountDownState createState() => _CountDownState(); } class _CountDownState extends State<CountDown> { Timer _timer; int _time; void startTimer() { _time = widget.countDownTime; var _interval = const Duration(seconds: 1); _timer = Timer.periodic(_interval, (_) { print('Time : $_time'); if (_time <= 0) { _timer.cancel(); } else { if (mounted) { setState(() { _time--; }); } } }); } @override void initState() { super.initState(); startTimer(); } cancelCount() { _timer.cancel(); } @override Widget build(BuildContext context) { return Text( '0${_time ?? 0}', style: const TextStyle( fontSize: 50, fontWeight: FontWeight.bold, ), ); } @override void dispose() { super.dispose(); _timer.cancel(); } }
0
mirrored_repositories/calmly/lib/src
mirrored_repositories/calmly/lib/src/components/home_widget.dart
import 'package:flutter/material.dart'; import 'package:calmly/src/constants/custom_icons_icons.dart'; import 'package:calmly/src/components/settings_bottom_sheet.dart'; import 'package:calmly/src/bloc/breathe/breathe_bloc.dart'; import 'package:calmly/src/bloc/breathe/breathe_counter_bloc.dart'; import 'package:calmly/src/bloc/breathe/breathe_counter_event.dart'; import 'package:calmly/src/components/count_down.dart'; import 'package:calmly/src/config/app_state.dart'; import 'package:calmly/src/utils/system_theme.dart'; import 'package:calmly/src/config/device_config.dart'; import 'package:calmly/src/constants/constants.dart'; import 'package:provider/provider.dart'; class HomeWidget extends StatefulWidget { @override _HomeWidgetState createState() => _HomeWidgetState(); } class _HomeWidgetState extends State<HomeWidget> { BreatheBloc _breatheBloc; BreatheCounterBloc _breatheCounterBloc; bool isDark; CountDown countDown; bool isCancelled = false; @override void initState() { super.initState(); } @override void didChangeDependencies() { super.didChangeDependencies(); _breatheBloc = Provider.of<BreatheBloc>(context); _breatheCounterBloc = Provider.of<BreatheCounterBloc>(context); AppState _appState = Provider.of<AppState>(context); isDark = SystemTheme.isDark(_appState); } @override Widget build(BuildContext context) { return Consumer<AppState>(builder: (_, appState, __) { isDark = SystemTheme.isDark(appState); return Container( margin: EdgeInsets.only( left: width * 0.05, right: width * 0.05, // top: height * 0.1, bottom: height * 0.05, ), child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, // crossAxisAlignment: CrossAxisAlignment.baseline, // textBaseline: TextBaseline.alphabetic, children: [ Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( "Focus /\nBreathe /\nRelax /\n", style: const TextStyle( fontSize: 26, fontWeight: FontWeight.bold), ), IconButton( icon: Icon( CustomIcons.dot_3, size: width * 0.1, color: isDark ? const Color(0xFFFFFFFF) : const Color(0xFF000000), ), onPressed: () { showModalBottomSheet( builder: (context) { return SettingsBottomSheet(); }, context: context); }, ), ], ), StreamBuilder( initialData: 04, stream: _breatheCounterBloc.outBreatheCounter, builder: (BuildContext context, AsyncSnapshot snapshot) { int breatheCount = snapshot.data; if (breatheCount == 0 || breatheCount == -1) { breatheCount = 4; } return Text( '$breatheCount', style: const TextStyle( fontSize: 100, fontWeight: FontWeight.bold), ); }, ), ], ), //upper widgets StreamBuilder( stream: _breatheBloc.outBreathe, initialData: Breathe.idle, builder: (BuildContext context, AsyncSnapshot<Breathe> snapshot) { Breathe breathe = snapshot.data; return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.end, children: [ Text( mapBreathingInfo(breathe), style: const TextStyle( fontSize: 20, fontWeight: FontWeight.bold), ), Visibility( visible: breathe != Breathe.idle, child: GestureDetector( onTap: () { _breatheCounterBloc.inBreatheCounterEvent .add(EndBreatheCounterEvent()); // WidgetsBinding.instance.addPostFrameCallback((_) { // setState(() { // isCancelled = true; // }); // }); // isCancelled = true; }, child: Text( 'End now', style: const TextStyle( fontSize: 20, fontWeight: FontWeight.bold), ), ), ), mapCountDown(breathe), ], ); }, ), //borrom widgets ], ), ); }); } CountDown mapCountDown(Breathe breathe) { CountDown countDown; if (breathe == Breathe.inhale) { countDown = CountDown(countDownTime: 4, key: UniqueKey()); } else if (breathe == Breathe.holdBreathe) { countDown = CountDown(countDownTime: 7, key: UniqueKey()); } else if (breathe == Breathe.exhale) { countDown = CountDown(countDownTime: 8); } else if (breathe == Breathe.idle) { countDown = CountDown(countDownTime: 0, key: UniqueKey()); } return countDown; } } String mapBreathingInfo(Breathe breathe) { String breatheInfo; if (breathe == Breathe.inhale) { breatheInfo = 'Inhale\nfrom your\nnose'; } else if (breathe == Breathe.holdBreathe) { breatheInfo = 'Hold\nyour\nbreathe'; } else if (breathe == Breathe.exhale) { breatheInfo = 'Exhale\nfrom your\nmouth'; } if (breathe == Breathe.idle) { breatheInfo = 'Tap\nCircle to\nstart'; } return breatheInfo; }
0
mirrored_repositories/calmly/lib/src
mirrored_repositories/calmly/lib/src/components/gradient_background.dart
import 'package:flutter/material.dart'; class GradientBackground extends StatelessWidget { final bool isCircle; final List<Color> colors; const GradientBackground({ Key key, this.isCircle = false, this.colors, }) : super(key: key); @override Widget build(BuildContext context) { return Container( child: Container( // margin: const EdgeInsets.all(10), decoration: ShapeDecoration( shape: isCircle ? CircleBorder() : RoundedRectangleBorder(), gradient: LinearGradient( transform: GradientRotation(1.5), // stops: [0.1, 0.3, 0.5, 0.6, 0.7, 0.8, 0.9, 0.95, 1.0], colors: colors ?? finalColor, ), ), ), ); } } var finalColor = [ const Color(0xFFFBFA00), const Color(0xFFFFCC00), const Color(0xFFFFBF00), // const Color(0xFFFF8519), const Color(0xFFFF4C51), const Color(0xFFFF1D65), const Color(0xFFFF1D65), ]; List<Color> smallGradient = [ const Color(0xFFFBFA00), const Color(0xFFFEEF00), const Color(0xFFFFCC00), // const Color(0xFFFFBF00), // const Color(0xFFFF8519), const Color(0xFFFF4C51), const Color(0xFFFF1D65), const Color(0xFFFD0081), ]; List<Color> largeGradient = [ const Color(0xFFFEF800), const Color(0xFFFCE800), const Color(0xFFFFD100), const Color(0xFFFFA800), // const Color(0xFFFF7B2A), // const Color(0xFFFF5F43), const Color(0xFFFF3F58), const Color(0xFFFD007A), const Color(0xFFFB0086), const Color(0xFFFB0085), ];
0
mirrored_repositories/calmly/lib/src
mirrored_repositories/calmly/lib/src/components/settings_bottom_sheet.dart
import 'package:calmly/src/utils/system_theme.dart'; import 'package:flutter/material.dart'; import 'package:calmly/src/config/app_state.dart'; import 'package:calmly/src/constants/constants.dart'; import 'package:calmly/src/config/device_config.dart'; import 'package:provider/provider.dart'; class SettingsBottomSheet extends StatefulWidget { const SettingsBottomSheet({ Key key, }) : super(key: key); @override _SettingsBottomSheetState createState() => _SettingsBottomSheetState(); } class _SettingsBottomSheetState extends State<SettingsBottomSheet> { AppState _appState; ThemeSetting _theme; bool isDark; @override void didChangeDependencies() { super.didChangeDependencies(); _appState = Provider.of<AppState>(context); _theme = _appState.themeSetting; isDark = SystemTheme.isDark(_appState); } @override Widget build(BuildContext context) { return Container( padding: EdgeInsets.symmetric( vertical: height * 0.025, horizontal: width * 0.05), width: width, height: height * 0.3, child: DefaultTextStyle( style: TextStyle( fontSize: 18, color: isDark ? const Color(0xFFFFFFFF) : const Color(0xFF000000), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Expanded( child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text('Rock the 80s theme'), Switch( value: !_appState.isModernBox, onChanged: (value) { setState(() { _appState.updateBox(!_appState.isModernBox); }); }, ), ], ), ), Expanded( child: InkWell( onTap: () { showDialog( context: context, builder: (context) { return StatefulBuilder( builder: (context, setState) { return Dialog( child: Container( height: height * 0.275, child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Container( padding: EdgeInsets.only( right: width * 0.075, left: width * 0.075, bottom: height * 0.0075, top: height * 0.025, ), child: Text( 'Select Theme', style: const TextStyle( fontSize: 18, fontWeight: FontWeight.bold, ), ), ), RadioListTile<ThemeSetting>( onChanged: (ThemeSetting theme) { setState(() { _theme = theme; _appState .updateTheme(ThemeSetting.system); }); }, value: ThemeSetting.system, groupValue: _theme, title: Text('System Default'), ), RadioListTile<ThemeSetting>( onChanged: (ThemeSetting theme) { setState(() { _appState .updateTheme(ThemeSetting.dark); _theme = theme; }); }, value: ThemeSetting.dark, groupValue: _theme, title: Text('Dark'), ), RadioListTile<ThemeSetting>( onChanged: (ThemeSetting theme) { setState(() { _theme = theme; _appState .updateTheme(ThemeSetting.light); }); }, value: ThemeSetting.light, groupValue: _theme, title: Text('Light'), ), ], ), ), ); }, ); }); }, child: Builder( builder: (_) { ThemeSetting themeSetting = _appState.themeSetting; return Container( height: height * 0.05, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ if (themeSetting == ThemeSetting.system) Text('System') else if (themeSetting == ThemeSetting.dark) Text('Dark') else if (themeSetting == ThemeSetting.light) Text('Light') ], ), ); }, ), ), ), Expanded( child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text('Vibration'), Switch( value: _appState.isVibrationOn, onChanged: (value) { setState(() { _appState.updateVibration(!_appState.isVibrationOn); }); }, ), ], ), ), Expanded( child: Align( alignment: Alignment.centerLeft, child: Text('About'))), ], ), ), ); } }
0
mirrored_repositories/calmly/lib/src/components
mirrored_repositories/calmly/lib/src/components/calm_box/traditional_calm_box.dart
import 'dart:async'; import 'dart:developer' as developer; import 'package:calmly/src/config/app_state.dart'; import 'package:calmly/src/utils/system_theme.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:vibration/vibration.dart'; import 'package:provider/provider.dart'; import 'package:calmly/src/bloc/breathe/breathe_bloc.dart'; import 'package:calmly/src/bloc/breathe/breathe_counter_bloc.dart'; import 'package:calmly/src/bloc/breathe/breathe_counter_event.dart'; import 'package:calmly/src/bloc/breathe/breathe_event.dart'; import 'package:calmly/src/components/gradient_background.dart'; import 'package:calmly/src/components/white_line.dart'; import 'package:calmly/src/bloc/calm_box/calm_box_bloc.dart'; import 'package:calmly/src/bloc/calm_box/calm_box_event.dart'; import 'package:calmly/src/screens/congrats_screen.dart'; import 'package:calmly/src/utils/local_db.dart'; import 'package:calmly/src/constants/constants.dart'; import 'package:calmly/src/config/device_config.dart'; class TraditionalCalmBox extends StatefulWidget { @override _TraditionalCalmBoxState createState() => _TraditionalCalmBoxState(); } class _TraditionalCalmBoxState extends State<TraditionalCalmBox> with SingleTickerProviderStateMixin { StreamSubscription _breatheCounterSubscription; StreamSubscription _calmBoxSubscription; CalmBoxBloc _calmBoxBloc; AnimationController _animationController; double radius = 0.55; BreatheBloc _breatheBloc; BreatheCounterBloc _breatheCounterBloc; int lastBreatheCount; var lastCalmBoxEvent; bool hasStarted = false; AppState _appState; bool isDark; bool isCancel = false; @override void initState() { super.initState(); initController(); } @override void didChangeDependencies() { super.didChangeDependencies(); _calmBoxBloc = Provider.of<CalmBoxBloc>(context); _breatheBloc = Provider.of<BreatheBloc>(context); _breatheCounterBloc = Provider.of<BreatheCounterBloc>(context); _appState = Provider.of<AppState>(context); isDark = SystemTheme.isDark(_appState); } void initController() { _animationController = AnimationController( duration: const Duration(milliseconds: 4000), vsync: this, lowerBound: 0.55, upperBound: 0.95) ..addStatusListener((AnimationStatus animationStatus) { print('Animation Status : $animationStatus'); if (animationStatus == AnimationStatus.forward || animationStatus == AnimationStatus.reverse) { _calmBoxBloc.calmBoxEventSink.add(BusyCalmBoxEvent()); // _breatheBloc.inBreatheEvent.add(HoldBreatheEvent()); } else if (animationStatus == AnimationStatus.completed) { _calmBoxBloc.calmBoxEventSink.add(CompletedExpandCalmBoxEvent()); _breatheBloc.inBreatheEvent.add(IdleEvent()); } else if (animationStatus == AnimationStatus.dismissed) { print('Last CalmBoxEvent : $lastCalmBoxEvent'); if (lastCalmBoxEvent == CalmBox.completedExpand) { _breatheBloc.inBreatheEvent.add(IdleEvent()); } else { _calmBoxBloc.calmBoxEventSink.add(CompletedShrinkCalmBoxEvent()); _breatheBloc.inBreatheEvent.add(IdleEvent()); } } }); } @override Widget build(BuildContext context) { return Stack( children: [ Positioned( top: height * 0.24, child: Container( width: width, height: height * 0.47, child: Stack( children: [ GradientBackground(), Positioned( top: height * 0.24, child: DividerLine( height: height * 0.0039, width: width, isDark: isDark, ), ), Positioned( top: height * 0.2755, //28 child: DividerLine( height: height * 0.01, width: width, isDark: isDark, ), ), Positioned( top: height * 0.31, //32 child: DividerLine( height: height * 0.017, width: width, isDark: isDark, ), ), Positioned( top: height * 0.345, child: DividerLine( height: height * 0.018, width: width, isDark: isDark, ), ), Positioned( top: height * 0.38, child: DividerLine( height: height * 0.028, width: width, isDark: isDark, ), ), Positioned( top: height * 0.42, child: DividerLine( height: height * 0.03, width: width, isDark: isDark, ), ), ], ), ), ), StreamBuilder( initialData: CalmBox.shrink, stream: _calmBoxBloc.outCalmBox, builder: (BuildContext context, AsyncSnapshot snapshot) { CalmBox calmBox = snapshot.data; if (calmBox == CalmBox.stop) { _animationController.duration = const Duration(milliseconds: 250); _animationController.stop(); } return GestureDetector( onTap: () => handleTap(calmBox), child: ColorFiltered( colorFilter: ColorFilter.mode( isDark ? const Color(0xFF000000) : const Color(0xFFFFFFFF), BlendMode.srcOut, ), // This one will create the magic child: Stack( fit: StackFit.expand, children: [ Container( decoration: BoxDecoration( color: Colors.black, backgroundBlendMode: BlendMode.dstOut, ), // This one will handle background + difference out ), Align( alignment: Alignment.center, child: AnimatedBuilder( animation: _animationController, builder: (_, __) { return Container( height: width * _animationController.value, width: width * _animationController.value, decoration: BoxDecoration( color: Colors.red, borderRadius: BorderRadius.circular(width * 0.5), ), ); }, ), ), ], ), ), ); }, ), ], ); } void handleTap(CalmBox calmBox) { if (calmBox != CalmBox.busy) { HapticFeedback.heavyImpact(); startCalmly(); hasStarted = true; } } vibrate() async { if (await Vibration.hasVibrator()) { Vibration.vibrate(duration: 70); } } exhale() { developer.log('Exhale'); if (_appState.isVibrationOn) { vibrate(); } _calmBoxBloc.calmBoxEventSink.add(ShrinkCalmBoxEvent()); _breatheBloc.inBreatheEvent.add(ExhaleEvent()); _animationController.duration = const Duration(milliseconds: 8000); //8000 _animationController.reverse(); } inhale() { developer.log('Inhale'); if (_appState.isVibrationOn) { vibrate(); } _calmBoxBloc.calmBoxEventSink.add(ExpandCalmBoxEvent()); _breatheBloc.inBreatheEvent.add(InhaleEvent()); _animationController.duration = const Duration(milliseconds: 4000); //4000 _animationController.forward(); } startCalmly() { inhale(); if (!hasStarted) { // don't listen if we are already listening _breatheCounterSubscription = _breatheCounterBloc.outBreatheCounter.listen(mapBreatheCount); _calmBoxSubscription = _calmBoxBloc.outCalmBox.listen(mapCalmBoxEvent); } } mapCalmBoxEvent(calmBoxValue) { lastCalmBoxEvent = calmBoxValue; if (calmBoxValue == CalmBox.cancel) { _animationController.duration = const Duration(milliseconds: 200); _animationController.animateTo(_animationController.lowerBound); // Future.delayed(Duration(milliseconds: 100), () { // isCancel = false; // }); print('Animation Controller value: ${_animationController.value}'); } else if (calmBoxValue == CalmBox.completedExpand) { _breatheBloc.inBreatheEvent.add(HoldBreatheEvent()); Future.delayed(const Duration(milliseconds: 7000), () { // 7000 exhale(); }); } else if (calmBoxValue == CalmBox.completedShrink) { _breatheCounterBloc.inBreatheCounterEvent.add(OneBreatheCounterEvent()); } } mapBreatheCount(breatheCount) { lastBreatheCount = breatheCount; if (breatheCount == 0) { stopCalmly(); } else if (breatheCount == -1) { cancelCalmly(); } else { Future.delayed(const Duration(milliseconds: 700), () { inhale(); }); } } stopCalmly() { _calmBoxBloc.calmBoxEventSink.add(StopCalmBoxEvent()); _breatheCounterBloc.inBreatheCounterEvent .add(CompletedBreatheCounterEvent()); _breatheBloc.inBreatheEvent.add(IdleEvent()); WidgetsBinding.instance.addPostFrameCallback((_) { showCongratsScreen(); }); } cancelCalmly() { isCancel = true; _calmBoxBloc.calmBoxEventSink.add(CancelCalmBoxEvent()); _breatheCounterBloc.inBreatheCounterEvent .add(CompletedBreatheCounterEvent()); _breatheBloc.inBreatheEvent.add(IdleEvent()); } @override void dispose() { // _calmBoxBloc.dispose(); // _breatheBloc.dispose(); // _breatheCounterBloc.dispose(); _breatheCounterSubscription.cancel(); _calmBoxSubscription.cancel(); super.dispose(); } showCongratsScreen() { LocalDB localDB = LocalDB(); int count = localDB.getTotalCalmly ?? 0; localDB.saveTotalCalmly(++count); Navigator.push( context, MaterialPageRoute( builder: (context) => CongratsScreen(), ), ); } }
0
mirrored_repositories/calmly/lib/src/components
mirrored_repositories/calmly/lib/src/components/calm_box/modern_calm_box.dart
import 'dart:async'; import 'dart:ui'; import 'dart:developer' as developer; import 'package:calmly/src/config/app_state.dart'; import 'package:calmly/src/utils/system_theme.dart'; import 'package:flutter/material.dart'; import 'package:calmly/src/bloc/calm_box/calm_box_bloc.dart'; import 'package:calmly/src/components/gradient_background.dart'; import 'package:calmly/src/bloc/breathe/breathe_event.dart'; import 'package:calmly/src/bloc/breathe/breathe_bloc.dart'; import 'package:calmly/src/bloc/calm_box/calm_box_event.dart'; import 'package:calmly/src/bloc/breathe/breathe_counter_bloc.dart'; import 'package:calmly/src/bloc/breathe/breathe_counter_event.dart'; import 'package:calmly/src/screens/congrats_screen.dart'; import 'package:calmly/src/utils/local_db.dart'; import 'package:calmly/src/config/device_config.dart'; import 'package:calmly/src/constants/constants.dart'; import 'package:vibration/vibration.dart'; import 'package:provider/provider.dart'; class ModernCalmBox extends StatefulWidget { @override _ModernCalmBoxState createState() => _ModernCalmBoxState(); } class _ModernCalmBoxState extends State<ModernCalmBox> with SingleTickerProviderStateMixin { AnimationController _animationController; Animation<double> _opacityTween; Animation<double> _sigmaXTween; Animation<double> _sigmaYTween; // bool isExpanded = false; StreamSubscription _breatheCounterSubscription; StreamSubscription _calmBoxSubscription; CalmBoxBloc _calmBoxBloc; BreatheBloc _breatheBloc; BreatheCounterBloc _breatheCounterBloc; int lastBreatheCount; CalmBox lastCalmBoxEvent; bool hasStarted = false; AppState _appState; bool isDark; @override void initState() { super.initState(); _animationController = AnimationController( vsync: this, duration: const Duration(milliseconds: 4000), lowerBound: 0.55, upperBound: 0.95, )..addStatusListener((AnimationStatus animationStatus) { print('Animation Status : $animationStatus'); if (animationStatus == AnimationStatus.forward || animationStatus == AnimationStatus.reverse) { _calmBoxBloc.calmBoxEventSink.add(BusyCalmBoxEvent()); // _breatheBloc.inBreatheEvent.add(HoldBreatheEvent()); } else if (animationStatus == AnimationStatus.completed) { _calmBoxBloc.calmBoxEventSink.add(CompletedExpandCalmBoxEvent()); _breatheBloc.inBreatheEvent.add(IdleEvent()); } else if (animationStatus == AnimationStatus.dismissed) { print('Last CalmBoxEvent : $lastCalmBoxEvent'); if (lastCalmBoxEvent == CalmBox.completedExpand) { _breatheBloc.inBreatheEvent.add(IdleEvent()); } else { _calmBoxBloc.calmBoxEventSink.add(CompletedShrinkCalmBoxEvent()); _breatheBloc.inBreatheEvent.add(IdleEvent()); } } }); _opacityTween = Tween<double>(begin: 0.0, end: 0.35).animate(_animationController); _sigmaXTween = Tween<double>(begin: 0.03, end: 0.1).animate(_animationController); _sigmaYTween = Tween<double>(begin: 0.13, end: 0.18).animate(_animationController); } @override void didChangeDependencies() { super.didChangeDependencies(); _calmBoxBloc = Provider.of<CalmBoxBloc>(context); _breatheBloc = Provider.of<BreatheBloc>(context); _breatheCounterBloc = Provider.of<BreatheCounterBloc>(context); _appState = Provider.of<AppState>(context); isDark = SystemTheme.isDark(_appState); } @override Widget build(BuildContext context) { return Container( color: isDark ? const Color(0xFF000000) : const Color(0xFFFFFFFF), child: Stack( children: [ Positioned( top: height * 0.265, child: StreamBuilder( initialData: CalmBox.shrink, stream: _calmBoxBloc.outCalmBox, builder: (BuildContext context, AsyncSnapshot<CalmBox> snapshot) { CalmBox calmBox = snapshot.data; if (calmBox == CalmBox.stop) { _animationController.duration = const Duration(milliseconds: 250); _animationController.stop(); } return GestureDetector( behavior: HitTestBehavior.translucent, onTap: () => handleTap(calmBox), child: Container( alignment: Alignment.center, width: width, height: height * 0.5, // child: Container( // width: width * _animationController.value, // height: width * _animationController.value, // child: GradientBackground( // isCircle: true, // colors: <Color>[ // const Color(0xFFFCE800), // const Color(0xFFFFD100), // const Color(0xFFFFA800), // const Color(0xFFFF7B2A), // const Color(0xFFFD007A), // const Color(0xFFFB0086), // const Color(0xFFFB0085), // ], // ), // ), child: AnimatedBuilder( builder: (_, __) { return Container( width: width * _animationController.value, height: width * _animationController.value, child: GradientBackground( isCircle: true, colors: <Color>[ const Color(0xFFFCE800), const Color(0xFFFFD100), const Color(0xFFFFA800), const Color(0xFFFF7B2A), const Color(0xFFFD007A), const Color(0xFFFB0086), const Color(0xFFFB0085), ], ), ); }, animation: _animationController, ), ), ); }, ), ), Positioned( top: height * 0.51, child: IgnorePointer( child: ClipRect( child: BackdropFilter( filter: ImageFilter.blur( sigmaX: height * _sigmaXTween.value, sigmaY: width * _sigmaYTween.value, ), //sigmaX = 0 (expanded) child: Container( height: height * 0.5, width: width, color: (isDark ? const Color(0xFF020202) : const Color(0xFFF3F6F6)) .withOpacity(_opacityTween.value), ), ), ), ), ), ], ), ); } void handleTap(CalmBox calmBox) { if (calmBox != CalmBox.busy) { startCalmly(); hasStarted = true; } } vibrate() async { if (await Vibration.hasVibrator()) { Vibration.vibrate(duration: 70); } } exhale() { developer.log('Exhale'); if (_appState.isVibrationOn) { vibrate(); } _calmBoxBloc.calmBoxEventSink.add(ShrinkCalmBoxEvent()); _breatheBloc.inBreatheEvent.add(ExhaleEvent()); _animationController.duration = const Duration(milliseconds: 8000); //8000 _animationController.reverse(); } inhale() async { developer.log('Inhale'); if (_appState.isVibrationOn) { vibrate(); } _calmBoxBloc.calmBoxEventSink.add(ExpandCalmBoxEvent()); _breatheBloc.inBreatheEvent.add(InhaleEvent()); _animationController.duration = const Duration(milliseconds: 4000); //4000 _animationController.forward(); } startCalmly() { inhale(); if (!hasStarted) { // don't listen if we are already listening _breatheCounterSubscription = _breatheCounterBloc.outBreatheCounter.listen(mapBreatheCount); _calmBoxSubscription = _calmBoxBloc.outCalmBox.listen(mapCalmBoxEvent); } } mapCalmBoxEvent(calmBoxValue) { lastCalmBoxEvent = calmBoxValue; if (calmBoxValue == CalmBox.cancel) { // setState(() { // _animationController.value = _animationController.lowerBound; // }); // _animationController.stop(canceled: true); _animationController.duration = const Duration(milliseconds: 200); _animationController.animateTo(_animationController.lowerBound); print('Animation Controller value: ${_animationController.value}'); } else if (calmBoxValue == CalmBox.completedExpand) { _breatheBloc.inBreatheEvent.add(HoldBreatheEvent()); Future.delayed(const Duration(milliseconds: 7000), () { // 7000 exhale(); }); } else if (calmBoxValue == CalmBox.completedShrink) { _breatheCounterBloc.inBreatheCounterEvent.add(OneBreatheCounterEvent()); } } mapBreatheCount(breatheCount) { lastBreatheCount = breatheCount; if (breatheCount == 0) { stopCalmly(); } else if (breatheCount == -1) { cancelCalmly(); } else { Future.delayed(const Duration(milliseconds: 700), () { inhale(); }); } } stopCalmly() { _calmBoxBloc.calmBoxEventSink.add(StopCalmBoxEvent()); _breatheCounterBloc.inBreatheCounterEvent .add(CompletedBreatheCounterEvent()); _breatheBloc.inBreatheEvent.add(IdleEvent()); WidgetsBinding.instance.addPostFrameCallback((_) { showCongratsScreen(); }); } cancelCalmly() { _calmBoxBloc.calmBoxEventSink.add(CancelCalmBoxEvent()); _breatheCounterBloc.inBreatheCounterEvent .add(CompletedBreatheCounterEvent()); _breatheBloc.inBreatheEvent.add(IdleEvent()); } @override void dispose() { // _calmBoxBloc.dispose(); // _breatheBloc.dispose(); // _breatheCounterBloc.dispose(); _breatheCounterSubscription.cancel(); _calmBoxSubscription.cancel(); super.dispose(); } showCongratsScreen() { LocalDB localDB = LocalDB(); int count = localDB.getTotalCalmly ?? 0; localDB.saveTotalCalmly(++count); Navigator.push( context, MaterialPageRoute( builder: (context) => CongratsScreen(), ), ); } }
0
mirrored_repositories/calmly/lib/src
mirrored_repositories/calmly/lib/src/config/theme_config.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:calmly/src/constants/color_constants.dart'; class ThemeConfig { static ThemeData createTheme({ Brightness brightness, Color background, Color primaryText, Color secondaryText, Color accentColor, Color divider, Color buttonBackground, Color buttonText, Color cardBackground, Color disabled, Color error, }) { final baseTextTheme = brightness == Brightness.dark ? Typography.blackMountainView : Typography.whiteMountainView; return ThemeData( brightness: brightness, buttonColor: buttonBackground, canvasColor: background, cardColor: background, dividerColor: divider, dividerTheme: DividerThemeData( color: divider, space: 1, thickness: 1, ), cardTheme: CardTheme( color: cardBackground, margin: EdgeInsets.zero, clipBehavior: Clip.antiAliasWithSaveLayer, ), backgroundColor: background, primaryColor: accentColor, accentColor: accentColor, textSelectionColor: accentColor, textSelectionHandleColor: accentColor, cursorColor: accentColor, toggleableActiveColor: accentColor, appBarTheme: AppBarTheme( brightness: brightness, color: cardBackground, textTheme: TextTheme( bodyText1: baseTextTheme.bodyText1.copyWith( color: secondaryText, fontSize: 18, ), ), iconTheme: IconThemeData( color: secondaryText, ), ), iconTheme: IconThemeData( color: secondaryText, size: 16.0, ), errorColor: error, buttonTheme: ButtonThemeData( textTheme: ButtonTextTheme.primary, colorScheme: ColorScheme( brightness: brightness, primary: accentColor, primaryVariant: accentColor, secondary: accentColor, secondaryVariant: accentColor, surface: background, background: background, error: error, onPrimary: buttonText, onSecondary: buttonText, onSurface: buttonText, onBackground: buttonText, onError: buttonText, ), padding: const EdgeInsets.all(16.0), ), cupertinoOverrideTheme: CupertinoThemeData( brightness: brightness, primaryColor: accentColor, ), inputDecorationTheme: InputDecorationTheme( errorStyle: TextStyle(color: error), labelStyle: TextStyle( fontFamily: '', fontWeight: FontWeight.w600, fontSize: 16.0, color: primaryText.withOpacity(0.5), ), hintStyle: TextStyle( color: secondaryText, fontSize: 13.0, fontWeight: FontWeight.w300, ), ), fontFamily: '', textTheme: TextTheme( headline1: baseTextTheme.headline1.copyWith( color: primaryText, fontSize: 34.0, fontWeight: FontWeight.bold, ), headline2: baseTextTheme.headline2.copyWith( color: primaryText, fontSize: 22, fontWeight: FontWeight.bold, ), headline3: baseTextTheme.headline3.copyWith( color: secondaryText, fontSize: 20, fontWeight: FontWeight.w600, ), headline4: baseTextTheme.headline4.copyWith( color: primaryText, fontSize: 18, fontWeight: FontWeight.w600, ), headline5: baseTextTheme.headline5.copyWith( color: primaryText, fontSize: 16, fontWeight: FontWeight.w700, ), headline6: baseTextTheme.headline6.copyWith( color: primaryText, fontSize: 14, fontWeight: FontWeight.w700, ), bodyText1: baseTextTheme.bodyText1.copyWith( color: secondaryText, fontSize: 15, ), bodyText2: baseTextTheme.bodyText2.copyWith( color: primaryText, fontSize: 12, fontWeight: FontWeight.w400, ), button: baseTextTheme.button.copyWith( color: primaryText, fontSize: 12.0, fontWeight: FontWeight.w700, ), caption: baseTextTheme.caption.copyWith( color: primaryText, fontSize: 11.0, fontWeight: FontWeight.w300, ), overline: baseTextTheme.overline.copyWith( color: secondaryText, fontSize: 11.0, fontWeight: FontWeight.w500, ), subtitle1: baseTextTheme.subtitle1.copyWith( color: primaryText, fontSize: 16.0, fontWeight: FontWeight.w700, ), subtitle2: baseTextTheme.subtitle2.copyWith( color: secondaryText, fontSize: 11.0, fontWeight: FontWeight.w500, ), ), ); } static ThemeData get lightTheme => createTheme( brightness: Brightness.light, background: ColorConstants.lightScaffoldBackgroundColor, cardBackground: ColorConstants.secondaryAppColor, primaryText: Colors.black, secondaryText: Colors.white, accentColor: ColorConstants.secondaryAppColor, divider: ColorConstants.secondaryAppColor, buttonBackground: Colors.black38, buttonText: ColorConstants.secondaryAppColor, disabled: ColorConstants.secondaryAppColor, error: Colors.red, ); static ThemeData get darkTheme => createTheme( brightness: Brightness.dark, background: ColorConstants.darkScaffoldBackgroundColor, cardBackground: ColorConstants.secondaryDarkAppColor, primaryText: Colors.white, secondaryText: Colors.black, accentColor: ColorConstants.secondaryDarkAppColor, divider: Colors.black45, buttonBackground: Colors.white, buttonText: ColorConstants.secondaryDarkAppColor, disabled: ColorConstants.secondaryDarkAppColor, error: Colors.red, ); }
0
mirrored_repositories/calmly/lib/src
mirrored_repositories/calmly/lib/src/config/app_state.dart
import 'package:flutter/material.dart'; import 'package:calmly/src/constants/constants.dart'; import 'package:calmly/src/utils/local_db.dart'; class AppState extends ChangeNotifier { bool _isModernBox = true; bool _isVibrateOn; ThemeSetting _themeSetting; LocalDB _localDB; AppState() { _localDB = LocalDB(); _isVibrateOn = _localDB.getVibrationSettings ?? true; _isModernBox = _localDB.getBoxTypeSettings ?? true; _themeSetting = _localDB.getThemeSettings ?? ThemeSetting.light; } updateTheme(ThemeSetting themeSetting) { this._themeSetting = themeSetting; _localDB.saveThemeSettings(themeSetting); notifyListeners(); } updateBox(bool isModernBox) { this._isModernBox = isModernBox; _localDB.saveBoxTypeSettings(isModernBox); notifyListeners(); } updateVibration(bool isVibrationOn) { this._isVibrateOn = isVibrationOn; _localDB.saveVibrationSettings(isVibrationOn); notifyListeners(); } get themeSetting => _themeSetting; get isModernBox => _isModernBox; get isVibrationOn => _isVibrateOn; }
0
mirrored_repositories/calmly/lib/src
mirrored_repositories/calmly/lib/src/config/device_config.dart
double width; double height;
0
mirrored_repositories/calmly/lib/src/bloc
mirrored_repositories/calmly/lib/src/bloc/breathe/breathe_event.dart
abstract class BreatheEvent {} class InhaleEvent extends BreatheEvent {} class HoldBreatheEvent extends BreatheEvent {} class ExhaleEvent extends BreatheEvent {} class IdleEvent extends BreatheEvent {}
0
mirrored_repositories/calmly/lib/src/bloc
mirrored_repositories/calmly/lib/src/bloc/breathe/breathe_counter_event.dart
abstract class BreatheCounterEvent {} class OneBreatheCounterEvent extends BreatheCounterEvent {} class CompletedBreatheCounterEvent extends BreatheCounterEvent {} class EndBreatheCounterEvent extends BreatheCounterEvent {}
0
mirrored_repositories/calmly/lib/src/bloc
mirrored_repositories/calmly/lib/src/bloc/breathe/breathe_bloc.dart
import 'dart:async'; import 'package:calmly/src/bloc/breathe/breathe_event.dart'; import 'package:calmly/src/constants/constants.dart'; class BreatheBloc { Breathe _breathe; StreamController<Breathe> _breatheController = StreamController<Breathe>.broadcast(); StreamSink<Breathe> get _inBreathe => _breatheController.sink; Stream<Breathe> get outBreathe => _breatheController.stream.asBroadcastStream(); StreamController<BreatheEvent> _breatheEventController = StreamController<BreatheEvent>(); StreamSink<BreatheEvent> get inBreatheEvent => _breatheEventController.sink; Stream<BreatheEvent> get _outBreatheEvent => _breatheEventController.stream; BreatheBloc() { _outBreatheEvent.listen(_mapEventToState); } void _mapEventToState(BreatheEvent breatheEvent) { if (breatheEvent is InhaleEvent) { _breathe = Breathe.inhale; } else if (breatheEvent is HoldBreatheEvent) { _breathe = Breathe.holdBreathe; } else if (breatheEvent is ExhaleEvent) { _breathe = Breathe.exhale; } else if (breatheEvent is IdleEvent) { _breathe = Breathe.idle; } _inBreathe.add(_breathe); } void dispose() { _breatheController.close(); _breatheEventController.close(); } }
0
mirrored_repositories/calmly/lib/src/bloc
mirrored_repositories/calmly/lib/src/bloc/breathe/breathe_counter_bloc.dart
import 'dart:async'; import 'package:calmly/src/bloc/breathe/breathe_counter_event.dart'; class BreatheCounterBloc { int _breatheCounter = 4; StreamController<int> _breatheCounterStreamController = StreamController.broadcast(); StreamSink<int> get _inBreatheCounter => _breatheCounterStreamController.sink; Stream<int> get outBreatheCounter => _breatheCounterStreamController.stream.asBroadcastStream(); StreamController<BreatheCounterEvent> _breatheCounterEventController = StreamController(); StreamSink<BreatheCounterEvent> get inBreatheCounterEvent => _breatheCounterEventController.sink; BreatheCounterBloc() { _breatheCounterEventController.stream.listen(_mapEventToState); } _mapEventToState(breatheCounterEvent) { if (breatheCounterEvent is OneBreatheCounterEvent) { _breatheCounter -= 1; _inBreatheCounter.add(_breatheCounter); } else if (breatheCounterEvent is CompletedBreatheCounterEvent) { _breatheCounter = 4; // _inBreatheCounter.add(_breatheCounter); } else if (breatheCounterEvent is EndBreatheCounterEvent) { _breatheCounter = -1; _inBreatheCounter.add(_breatheCounter); _breatheCounter = 4; } print('Breathe Count : $_breatheCounter'); } void dispose() { _breatheCounterStreamController.close(); _breatheCounterEventController.close(); } }
0
mirrored_repositories/calmly/lib/src/bloc
mirrored_repositories/calmly/lib/src/bloc/calm_box/calm_box_event.dart
abstract class CalmBoxEvent {} class ExpandCalmBoxEvent extends CalmBoxEvent {} class ShrinkCalmBoxEvent extends CalmBoxEvent {} class BusyCalmBoxEvent extends CalmBoxEvent {} class CompletedExpandCalmBoxEvent extends CalmBoxEvent {} class CompletedShrinkCalmBoxEvent extends CalmBoxEvent {} class CancelCalmBoxEvent extends CalmBoxEvent {} class StopCalmBoxEvent extends CalmBoxEvent {}
0
mirrored_repositories/calmly/lib/src/bloc
mirrored_repositories/calmly/lib/src/bloc/calm_box/calm_box_bloc.dart
import 'dart:async'; import 'package:calmly/src/bloc/calm_box/calm_box_event.dart'; import 'package:calmly/src/constants/constants.dart'; class CalmBoxBloc { CalmBox _calmBox; StreamController<CalmBox> _expandStreamController = StreamController<CalmBox>.broadcast(); StreamSink<CalmBox> get _inCalmBox => _expandStreamController.sink; Stream<CalmBox> get outCalmBox => _expandStreamController.stream.asBroadcastStream(); StreamController<CalmBoxEvent> _calmBoxEventController = StreamController<CalmBoxEvent>(); StreamSink<CalmBoxEvent> get calmBoxEventSink => _calmBoxEventController.sink; CalmBoxBloc() { _calmBoxEventController.stream.listen(_mapEventToState); } _mapEventToState(CalmBoxEvent calmBoxEvent) { if (calmBoxEvent is ExpandCalmBoxEvent) { _calmBox = CalmBox.expand; } else if (calmBoxEvent is ShrinkCalmBoxEvent) { _calmBox = CalmBox.shrink; } else if (calmBoxEvent is BusyCalmBoxEvent) { _calmBox = CalmBox.busy; } else if (calmBoxEvent is CompletedExpandCalmBoxEvent) { _calmBox = CalmBox.completedExpand; } else if (calmBoxEvent is CompletedShrinkCalmBoxEvent) { _calmBox = CalmBox.completedShrink; } else if (calmBoxEvent is CancelCalmBoxEvent) { _calmBox = CalmBox.cancel; } else if (calmBoxEvent is StopCalmBoxEvent) { _calmBox = CalmBox.stop; } print('CalmBoxState = $_calmBox'); _inCalmBox.add(_calmBox); } void dispose() { _expandStreamController.close(); _calmBoxEventController.close(); } }
0
mirrored_repositories/calmly/lib/src
mirrored_repositories/calmly/lib/src/utils/local_db.dart
import 'package:calmly/src/constants/constants.dart'; import 'package:calmly/src/utils/system_theme.dart'; import 'package:hive/hive.dart'; class LocalDB { var box; LocalDB._internal(); static final LocalDB _localDB = LocalDB._internal(); factory LocalDB() { return _localDB; } init() async { box = await Hive.openBox('calmly'); } saveThemeSettings(ThemeSetting themeSetting) { box.put('themeSetting', SystemTheme.themeToString(themeSetting)); } saveVibrationSettings(bool isVibrationOn) { box.put('isVibrationOn', isVibrationOn); } saveBoxTypeSettings(bool isTraditional) { box.put('isTraditional', isTraditional); } saveTotalCalmly(int count) { box.put('totalCalmly', count); } get getVibrationSettings => box.get('isVibrationOn'); get getBoxTypeSettings => box.get('isTraditional'); get getThemeSettings { return SystemTheme.stringToTheme(box.get('themeSetting')); } get getTotalCalmly => box.get('totalCalmly'); }
0
mirrored_repositories/calmly/lib/src
mirrored_repositories/calmly/lib/src/utils/system_theme.dart
import 'dart:ui'; import 'package:calmly/src/config/app_state.dart'; import 'package:calmly/src/constants/constants.dart'; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter/services.dart'; class SystemTheme { static check(AppState appState) { var brightness = SchedulerBinding.instance.window.platformBrightness; bool darkModeOn = brightness == Brightness.dark; if (darkModeOn) { return ThemeSetting.dark; } else { return ThemeSetting.light; } } static isDark(_appState) { bool isDark; ThemeSetting themeSetting = _appState.themeSetting; if (themeSetting == ThemeSetting.system) { isDark = SystemTheme.check(_appState) == ThemeSetting.dark; } else if (themeSetting == ThemeSetting.light) { isDark = false; } else if (themeSetting == ThemeSetting.dark) { isDark = true; } return isDark; } static themeToString(themeSetting) { var selectedTheme; if (themeSetting == ThemeSetting.system) { selectedTheme = 'system'; } else if (themeSetting == ThemeSetting.light) { selectedTheme = 'light'; } else if (themeSetting == ThemeSetting.dark) { selectedTheme = 'dark'; } return selectedTheme; } static stringToTheme(theme) { var selectedTheme; if (theme == 'system') { selectedTheme = ThemeSetting.system; } else if (theme == 'light') { selectedTheme = ThemeSetting.light; } else if (theme == 'dark') { selectedTheme = ThemeSetting.dark; } return selectedTheme; } static changeStatusBarColor(appState) { if (isDark(appState)) { SystemChrome.setSystemUIOverlayStyle( SystemUiOverlayStyle( statusBarColor: Colors.black, statusBarIconBrightness: Brightness.light, ), ); } else { SystemChrome.setSystemUIOverlayStyle( SystemUiOverlayStyle( statusBarColor: Colors.white, statusBarIconBrightness: Brightness.dark, ), ); } } }
0
mirrored_repositories/calmly/lib/src
mirrored_repositories/calmly/lib/src/screens/home_screen.dart
import 'package:flutter/material.dart'; import 'package:calmly/src/components/calm_box/modern_calm_box.dart'; import 'package:calmly/src/components/calm_box/traditional_calm_box.dart'; import 'package:calmly/src/components/home_widget.dart'; import 'package:calmly/src/config/app_state.dart'; import 'package:calmly/src/config/device_config.dart'; import 'package:provider/provider.dart'; class HomeScreen extends StatefulWidget { @override _HomeScreenState createState() => _HomeScreenState(); } class _HomeScreenState extends State<HomeScreen> { @override Widget build(BuildContext context) { //initialize width and height width = MediaQuery.of(context).size.width; height = MediaQuery.of(context).size.height; return Consumer<AppState>( builder: (_, appState, __) { return Scaffold( body: SafeArea( child: Stack( children: [ appState.isModernBox ? ModernCalmBox() : TraditionalCalmBox(), HomeWidget(), ], ), ), ); }, ); } }
0
mirrored_repositories/calmly/lib/src
mirrored_repositories/calmly/lib/src/screens/congrats_screen.dart
import 'package:flutter/material.dart'; import 'package:confetti/confetti.dart'; import 'package:provider/provider.dart'; import 'package:calmly/src/config/app_state.dart'; import 'package:calmly/src/utils/system_theme.dart'; import 'package:calmly/src/utils/local_db.dart'; import 'package:calmly/src/config/device_config.dart'; class CongratsScreen extends StatefulWidget { @override _CongratsScreenState createState() => _CongratsScreenState(); } class _CongratsScreenState extends State<CongratsScreen> { ConfettiController _controller; AppState _appState; bool isDark; int totalCalmlyCount; @override void initState() { super.initState(); _controller = new ConfettiController( duration: new Duration(seconds: 2), ); totalCalmlyCount = LocalDB().getTotalCalmly ?? 0; } @override void didChangeDependencies() { super.didChangeDependencies(); _appState = Provider.of<AppState>(context); isDark = SystemTheme.isDark(_appState); } @override Widget build(BuildContext context) { WidgetsBinding.instance.addPostFrameCallback((_) { _controller.play(); }); return Scaffold( backgroundColor: isDark ? const Color(0xFF000000) : const Color(0xFFFFFFFF), body: Stack( children: [ ConfettiWidget( blastDirectionality: BlastDirectionality.explosive, confettiController: _controller, particleDrag: 0.05, emissionFrequency: 0.05, numberOfParticles: 25, gravity: 0.05, shouldLoop: false, colors: [ Colors.green, Colors.red, Colors.yellow, Colors.blue, Colors.lime ], child: Padding( padding: EdgeInsets.symmetric( vertical: height * 0.075, horizontal: width * 0.03), child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Container( padding: const EdgeInsets.symmetric(horizontal: 10), alignment: Alignment.centerLeft, child: Text( '$totalCalmlyCount', style: const TextStyle( fontSize: 56, fontWeight: FontWeight.bold, ), ), ), Text( 'Congratulations', style: const TextStyle( fontSize: 46, fontWeight: FontWeight.bold, ), ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.end, children: [ Container( width: width * 0.35, padding: EdgeInsets.symmetric(horizontal: width * 0.025), child: Text( 'Breathing Session Completed', style: const TextStyle( fontSize: 22, fontWeight: FontWeight.bold, ), ), ), GestureDetector( onTap: () { Navigator.of(context).pop(); }, child: Container( padding: EdgeInsets.symmetric(horizontal: width * 0.025), alignment: Alignment.bottomRight, child: Text( 'Close', style: const TextStyle( fontSize: 22, fontWeight: FontWeight.bold, ), ), ), ), ], ) ], ), ), ), ], ), ); } }
0
mirrored_repositories/calmly
mirrored_repositories/calmly/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:calmly/src/app.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(App()); // 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/food_app_ui
mirrored_repositories/food_app_ui/lib/main.dart
import 'package:flutter/material.dart'; import './screens/category.dart'; void main() { runApp( MaterialApp( title: 'Food app', debugShowCheckedModeBanner: false, home: CategoryScreen(), ), ); }
0
mirrored_repositories/food_app_ui/lib
mirrored_repositories/food_app_ui/lib/model/product_model.dart
class ProductModel { String companyImage; String productImage; String productName; String description; double kCal; double fat; double carbs; double protein; }
0
mirrored_repositories/food_app_ui/lib
mirrored_repositories/food_app_ui/lib/model/category_model.dart
class CategoryModel { String categoryImage; String categoryName; }
0
mirrored_repositories/food_app_ui/lib
mirrored_repositories/food_app_ui/lib/utils/product_data.dart
import '../model/product_model.dart'; List<ProductModel> getProduct(){ String mcDonalUrl = "https://www.freepnglogos.com/uploads/mcdonalds-png-logo/mcdonalds-png-logo-simple-m-1.png"; String burgerKingUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/7/79/Burger_King_logo.svg/1012px-Burger_King_logo.svg.png"; String kfcUrl = "https://i.pinimg.com/originals/23/e6/64/23e664116abe4788c7d8750ab9379b5f.png"; String desc= "A cheeseburger is a hamburger topped with cheese. Traditionally, the slice of cheese is placed on top of the meat patty, " "but the burger can include variations in structure, ingredients and composition. The cheese is usually added to the cooking " "hamburger patty shortly before serving, which allows the cheese to melt."; List<ProductModel> productList = List<ProductModel>(); ProductModel productModel; //cheese burgers productModel = new ProductModel(); productModel.productName = "Cheese Burger"; productModel.productImage = "https://i.pinimg.com/originals/22/d2/c1/22d2c1d2227f8e31025bfa101a8340df.png"; productModel.companyImage = mcDonalUrl; productModel.description = desc; productModel.kCal=486; productModel.fat=13; productModel.carbs=51; productModel.protein=22; productList.add(productModel); //longer productModel = new ProductModel(); productModel.productName = "Longer"; productModel.productImage = "https://bk-latam-prod.s3.amazonaws.com/sites/burgerking.bs/files/xlCheeseburger-thumb.png"; productModel.companyImage = kfcUrl; productModel.description = desc; productModel.kCal=456; productModel.fat=16; productModel.carbs=61; productModel.protein=19; productList.add(productModel); //beef Burger productModel = new ProductModel(); productModel.productName = "Beef Burger"; productModel.productImage = "https://crispychicken.rest/wp-content/uploads/2018/07/Beef-Burger-.png"; productModel.companyImage = kfcUrl; productModel.description = desc; productModel.kCal=524; productModel.fat=19; productModel.carbs=61; productModel.protein=35; productList.add(productModel); //maharaja mac productModel = new ProductModel(); productModel.productName = "Maharaja Mac"; productModel.productImage = "https://i.pinimg.com/originals/b4/7d/cc/b47dcc449a889067e6beb6f40908e5a9.png"; productModel.companyImage = mcDonalUrl; productModel.description = desc; productModel.kCal=462; productModel.fat=16; productModel.carbs=31; productModel.protein=19; productList.add(productModel); //whooper sandwich productModel = new ProductModel(); productModel.productName = "WHOPPER Sandwich"; productModel.productImage = "https://www.hungryjacks.com.au/Upload/HJ/Media/Menu/product/Main/1000_Whopper_1.png"; productModel.companyImage = burgerKingUrl; productModel.description = desc; productModel.kCal=464; productModel.fat=12; productModel.carbs=56; productModel.protein=23; productList.add(productModel); return productList; }
0
mirrored_repositories/food_app_ui/lib
mirrored_repositories/food_app_ui/lib/utils/category_data.dart
import '../model/category_model.dart'; List<CategoryModel> getCategories(){ List<CategoryModel> categories = List<CategoryModel>(); CategoryModel categoryModel; //burgers categoryModel = new CategoryModel(); categoryModel.categoryName = "Burgers"; categoryModel.categoryImage = "https://www.mcdonalds.co.za/sites/default/files/productThumbnail/mcd-salads-and-vegetarian-veggie-burger.png"; categories.add(categoryModel); //drinks categoryModel = new CategoryModel(); categoryModel.categoryName = "Drinks"; categoryModel.categoryImage = "https://www.dynamicgreens.com/app/uploads/2015/09/low-fat-smoothies.png"; categories.add(categoryModel); //wraps categoryModel = new CategoryModel(); categoryModel.categoryName = "Wraps"; categoryModel.categoryImage = "https://app.hungryjacks.com.au/Upload/HJ/Media/Menu/Product/Main/3522_Tendercrisp_Avocado_BLT_Wrap_WEB_1.png"; categories.add(categoryModel); //vegan categoryModel = new CategoryModel(); categoryModel.categoryName = "Vegan"; categoryModel.categoryImage = "https://www.catermefit.com/wp-content/uploads/2015/12/veg.png"; categories.add(categoryModel); //beer categoryModel = new CategoryModel(); categoryModel.categoryName = "Beer"; categoryModel.categoryImage = "https://www.horiba.com/fileadmin/_processed_/csm_01_02-2019_Beer_Brewing_53ef2818e5.png"; categories.add(categoryModel); return categories; }
0
mirrored_repositories/food_app_ui/lib
mirrored_repositories/food_app_ui/lib/screens/product_list.dart
import 'package:flutter/material.dart'; import '../utils/product_data.dart'; import './widgets/product_card.dart'; import '../model/product_model.dart'; class ProductScreen extends StatefulWidget { @override _ProductScreenState createState() => _ProductScreenState(); } class _ProductScreenState extends State<ProductScreen> { List<ProductModel> productList = getProduct(); @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, appBar: AppBar( iconTheme: IconThemeData( color: Colors.black, ), elevation: 0, backgroundColor: Colors.white, title: Text( "List of products", softWrap: true, style: TextStyle( fontWeight: FontWeight.w500, color: Colors.black, ), ), centerTitle: true, ), body: GridView.builder( padding: EdgeInsets.all(30), shrinkWrap: true, scrollDirection: Axis.vertical, itemCount: productList.length, gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, mainAxisSpacing: 10, crossAxisSpacing: 10, childAspectRatio: 0.7, ), itemBuilder: (context, index) { return ProductCard( imageUrl: productList[index].productImage, companyUrl: productList[index].companyImage, productName: productList[index].productName, productDetails: productList[index], ); }, ), ); } }
0
mirrored_repositories/food_app_ui/lib
mirrored_repositories/food_app_ui/lib/screens/category.dart
import 'package:flutter/material.dart'; import './widgets/category_card.dart'; import '../utils/category_data.dart'; import '../model/category_model.dart'; class CategoryScreen extends StatefulWidget { @override _CategoryScreenState createState() => _CategoryScreenState(); } class _CategoryScreenState extends State<CategoryScreen> { List<CategoryModel> categoryList = getCategories(); @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( backgroundColor: Colors.yellow[600], body: SingleChildScrollView( child: Column( children: <Widget>[ Container( padding: EdgeInsets.fromLTRB(30, 50, 30, 20), color: Colors.transparent, width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height*0.25, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text('Hello',softWrap: true,style: TextStyle(fontSize: 20,color: Colors.black,fontWeight: FontWeight.w500),), Text('Find your meal!',softWrap: true,style: TextStyle(fontSize: 25,color: Colors.black,fontWeight: FontWeight.w900),), ], ), ), Container( decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.vertical( top: Radius.circular(35), ), ), child: GridView.builder( padding: EdgeInsets.all(30), shrinkWrap: true, scrollDirection: Axis.vertical, itemCount: categoryList.length, gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, mainAxisSpacing: 10, crossAxisSpacing: 10, childAspectRatio: 0.7, ), itemBuilder: (context, index) { return CategoryCard( imageUrl: categoryList[index].categoryImage, categoryName: categoryList[index].categoryName,); }, ), ), ], ), ), ), ); } }
0
mirrored_repositories/food_app_ui/lib
mirrored_repositories/food_app_ui/lib/screens/item.dart
import 'package:flutter/material.dart'; import './widgets/product_info_card.dart'; import '../model/product_model.dart'; class ItemScreen extends StatefulWidget { final ProductModel productDetails; ItemScreen({@required this.productDetails}); @override _ItemScreenState createState() => _ItemScreenState(); } class _ItemScreenState extends State<ItemScreen> { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, appBar: AppBar( elevation: 0, backgroundColor: Colors.white, iconTheme: IconThemeData( color: Colors.black, ), actions: <Widget>[ IconButton(icon: Icon(Icons.favorite_border,color: Colors.black,), onPressed: null,padding: EdgeInsets.only(right: 10),), ], ), body: SingleChildScrollView( scrollDirection: Axis.vertical, child: Column( children: <Widget>[ Container( margin: EdgeInsets.only(bottom: 10,top: 10), color: Colors.transparent, child: Text( widget.productDetails.productName, textAlign: TextAlign.center, softWrap: true, style: TextStyle( color: Colors.black, fontSize: 22, fontWeight: FontWeight.w700 ), ), ), Image( image: NetworkImage(widget.productDetails.companyImage), height: MediaQuery.of(context).size.height*0.1, width: MediaQuery.of(context).size.width*0.12, fit: BoxFit.contain, ), Image( image: NetworkImage(widget.productDetails.productImage), height: MediaQuery.of(context).size.height*0.25, width: MediaQuery.of(context).size.width*0.5, fit: BoxFit.cover, ), SizedBox(height: 40,), Container( child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ ProductInfoCard(infoType: "KCal" , infoNumber: widget.productDetails.kCal.toString()), ProductInfoCard(infoType: "Fats" , infoNumber: widget.productDetails.fat.toString()), ProductInfoCard(infoType: "Carbs" , infoNumber: widget.productDetails.carbs.toString()), ProductInfoCard(infoType: "Protein" , infoNumber: widget.productDetails.protein.toString()), ], ), ), Container( margin: EdgeInsets.fromLTRB(20, 20, 20, 50), child: Text( widget.productDetails.description, textAlign: TextAlign.center, style: TextStyle( fontWeight: FontWeight.w300, fontSize: 15, color: Colors.black87, wordSpacing: 2, letterSpacing: 1.2 ), ), ), ], ), ), ); } } // // child: Stack( // children: <Widget>[ // Align( // alignment: Alignment.topCenter, // child: Container( // margin: EdgeInsets.only(bottom: 10,top: 10), // color: Colors.transparent, // child: Text( // widget.productDetails.productName, // textAlign: TextAlign.center, // softWrap: true, // style: TextStyle( // color: Colors.black, // fontSize: 22, // fontWeight: FontWeight.w700 // ), // ), // ), // ), // // Positioned( // left: MediaQuery.of(context).size.width*0.45, // top: MediaQuery.of(context).size.height*0.06, // child: Image( // image: NetworkImage(widget.productDetails.companyImage), // height: MediaQuery.of(context).size.height*0.1, // width: MediaQuery.of(context).size.width*0.1, // fit: BoxFit.contain, // ), // ), // // // Align( // alignment: Alignment.center, // child: Image( // image: NetworkImage(widget.productDetails.productImage), // height: MediaQuery.of(context).size.height*0.6, // width: MediaQuery.of(context).size.width*0.6, // fit: BoxFit.contain, // ), // ), // // // Positioned( // top: MediaQuery.of(context).size.height*0.5, // child: Container( // child: Row( // mainAxisAlignment: MainAxisAlignment.spaceEvenly, // children: <Widget>[ // ProductInfoCard(infoType: "KCal" , infoNumber: widget.productDetails.kCal.toString()), // ProductInfoCard(infoType: "Fats" , infoNumber: widget.productDetails.fat.toString()), // ProductInfoCard(infoType: "Carbs" , infoNumber: widget.productDetails.carbs.toString()), // ProductInfoCard(infoType: "Protein" , infoNumber: widget.productDetails.protein.toString()), // ], // ), // ) // ), // // // // Positioned( // top: MediaQuery.of(context).size.height*0.58, // child: Container( // child: Text( // widget.productDetails.description, // overflow: TextOverflow.ellipsis, // softWrap: true, // textAlign: TextAlign.center, // style: TextStyle( // fontWeight: FontWeight.w500, // fontSize: 10, // color: Colors.black54, // ), // ), // ), // ), // // // // // // // ], // ),
0
mirrored_repositories/food_app_ui/lib/screens
mirrored_repositories/food_app_ui/lib/screens/widgets/category_card.dart
import 'package:flutter/material.dart'; import '../product_list.dart'; class CategoryCard extends StatelessWidget { final String imageUrl ; final String categoryName ; CategoryCard({@required this. imageUrl, @required this.categoryName}); @override Widget build(BuildContext context) { return GestureDetector( onTap: (){ Navigator.push(context, MaterialPageRoute( builder: (context) => ProductScreen(), )); }, child: Container( width: MediaQuery.of(context).size.width*0.4, height: MediaQuery.of(context).size.height*0.45, padding: EdgeInsets.all(10), decoration: BoxDecoration( color: Colors.yellow[600], borderRadius: BorderRadius.all( Radius.circular(5.0) ), ), child: Column( children: <Widget>[ Image( image: NetworkImage(imageUrl), height: MediaQuery.of(context).size.height*0.25, width: MediaQuery.of(context).size.width*0.32, fit: BoxFit.contain, ), Container( color: Colors.transparent, child: Text( categoryName, softWrap: true, style: TextStyle( color: Colors.black, fontSize: 20, ), ), ), ], ), ), ); } }
0
mirrored_repositories/food_app_ui/lib/screens
mirrored_repositories/food_app_ui/lib/screens/widgets/product_card.dart
import 'package:flutter/material.dart'; import '../item.dart'; import '../../model/product_model.dart'; class ProductCard extends StatelessWidget { final String imageUrl ; final String companyUrl; final String productName ; final ProductModel productDetails; ProductCard({@required this. imageUrl,@required this.companyUrl, @required this.productName, @required this.productDetails}); @override Widget build(BuildContext context) { return GestureDetector( onTap: (){ Navigator.push(context, MaterialPageRoute( builder: (context) => ItemScreen(productDetails: this.productDetails,), )); }, child: Container( width: MediaQuery.of(context).size.width*0.4, height: MediaQuery.of(context).size.height*0.45, padding: EdgeInsets.all(10), decoration: BoxDecoration( color: Colors.white, boxShadow: [ BoxShadow( color: Colors.black12, spreadRadius: 2, offset: Offset(2,2),blurRadius: 10, ), ], borderRadius: BorderRadius.all( Radius.circular(5.0) ), ), child: Stack( children: <Widget>[ Positioned( top: 8, left: 8, height: 20, width: 20, child: Image( image: NetworkImage(companyUrl), fit: BoxFit.fill, ), ), Positioned( left: MediaQuery.of(context).size.width*0.01, top: MediaQuery.of(context).size.height*0.02, child: Image( image: NetworkImage(imageUrl), height: MediaQuery.of(context).size.height*0.25, width: MediaQuery.of(context).size.width*0.32, fit: BoxFit.contain, ), ), Align( alignment: Alignment.bottomCenter, child: Container( margin: EdgeInsets.only(bottom: 10), color: Colors.transparent, child: Text( productName, textAlign: TextAlign.center, softWrap: true, style: TextStyle( color: Colors.black, fontSize: 15, fontWeight: FontWeight.bold ), ), ), ), ], ), ), ); } } // child: Container( // width: MediaQuery.of(context).size.width*0.4, // height: MediaQuery.of(context).size.height*0.45, // padding: EdgeInsets.all(10), // decoration: BoxDecoration( // color: Colors.white, // boxShadow: [ // BoxShadow( // color: Colors.black12, // spreadRadius: 2, // offset: Offset(2,2),blurRadius: 10, // ), // ], // borderRadius: BorderRadius.all( // Radius.circular(5.0) // ), // ), // child: Column( // children: <Widget>[ //// Image( //// alignment: Alignment(-1, -1), //// image: NetworkImage(companyUrl), //// height: MediaQuery.of(context).size.height*0.05, //// width: MediaQuery.of(context).size.width*0.05, //// fit: BoxFit.contain, //// ), // Image( // image: NetworkImage(imageUrl), // height: MediaQuery.of(context).size.height*0.25, // width: MediaQuery.of(context).size.width*0.32, // fit: BoxFit.contain, // ), // Container( // color: Colors.transparent, // child: Text( // productName, // softWrap: true, // style: TextStyle( // color: Colors.black, // fontSize: 15, // fontWeight: FontWeight.bold // ), // ), // ), // ], // ), // // ),
0
mirrored_repositories/food_app_ui/lib/screens
mirrored_repositories/food_app_ui/lib/screens/widgets/product_info_card.dart
import 'package:flutter/material.dart'; class ProductInfoCard extends StatelessWidget { final String infoType; final String infoNumber; ProductInfoCard({@required this.infoType,@required this.infoNumber}); @override Widget build(BuildContext context) { return Container( //decoration: BoxDecoration(color: Colors.red), margin: EdgeInsets.all(0), padding: EdgeInsets.all(10), child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ Container( padding: EdgeInsets.only(top: 10,bottom: 15), child: Text(infoType,textAlign: TextAlign.center,softWrap: true,style: TextStyle(fontWeight: FontWeight.w400,fontSize: 15),), ), Container( padding: EdgeInsets.only(bottom: 15), child: Text(infoNumber,textAlign: TextAlign.center,softWrap: true,style: TextStyle(fontWeight: FontWeight.w800,fontSize: 20),), ), ], ), ); } }
0
mirrored_repositories/food_app_ui
mirrored_repositories/food_app_ui/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:foodapp/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/flutter_proyects_in_2020/peliculas
mirrored_repositories/flutter_proyects_in_2020/peliculas/lib/main.dart
import 'package:flutter/material.dart'; import 'package:peliculas/src/pages/home_page.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Películas', initialRoute: '/', routes:{ '/': (BuildContext context) => HomePage(), } ); } }
0
mirrored_repositories/flutter_proyects_in_2020/peliculas/lib/src
mirrored_repositories/flutter_proyects_in_2020/peliculas/lib/src/widgets/card_swiper_widget.dart
import 'package:flutter/material.dart'; import 'package:flutter_swiper/flutter_swiper.dart'; import 'package:peliculas/src/models/pelicula_model.dart'; class CardSwiper extends StatelessWidget { final List<Pelicula> peliculas; CardSwiper({@required this.peliculas}); @override Widget build(BuildContext context) { final _screenSize = MediaQuery.of(context).size; return Container( padding: EdgeInsets.only(top:10.0), child: new Swiper( layout: SwiperLayout.STACK, itemWidth: _screenSize.width * 0.7, itemHeight: _screenSize.height * 0.5, itemBuilder: (BuildContext context,int index){ return ClipRRect( borderRadius: BorderRadius.circular(20.0), // child: new Image.network("http://via.placeholder.com/350x150", child: FadeInImage( image: NetworkImage(peliculas[index].getPosterImg()), placeholder: AssetImage('assets/img/no-image.jpg'), fit: BoxFit.cover, ), // child: Text('pelicul'), // fit: BoxFit.cover,) ); }, itemCount: peliculas.length, // pagination: new SwiperPagination(), // control: new SwiperControl(), ), ); } }
0
mirrored_repositories/flutter_proyects_in_2020/peliculas/lib/src
mirrored_repositories/flutter_proyects_in_2020/peliculas/lib/src/widgets/movie_horizontal.dart
import 'package:flutter/material.dart'; import 'package:peliculas/src/models/pelicula_model.dart'; class MovieHorizontal extends StatelessWidget { final List<Pelicula> peliculas; MovieHorizontal({@required this.peliculas}); @override Widget build(BuildContext context) { final _screenSie = MediaQuery.of(context).size; return Container( height: _screenSie.height * 0.2, child: PageView( pageSnapping: false, controller: PageController( initialPage: 1, viewportFraction: 0.3, ), children: _tarjetas(context), ), ); } List<Widget> _tarjetas(BuildContext context) { return peliculas.map((pelicula) { return Container( margin: EdgeInsets.only(right: 15.0), child: Column( children: <Widget>[ ClipRRect( borderRadius: BorderRadius.circular(20.0), child: FadeInImage( image: NetworkImage(pelicula.getPosterImg()), placeholder: AssetImage('assets/img/no-image.jpg'), fit: BoxFit.cover, height: 110.0,//160.0 ), ), SizedBox(height: 5.0,), Text(pelicula.title, overflow: TextOverflow.ellipsis, style: Theme.of(context).textTheme.caption,), ], ), ); }).toList(); } }
0
mirrored_repositories/flutter_proyects_in_2020/peliculas/lib/src
mirrored_repositories/flutter_proyects_in_2020/peliculas/lib/src/pages/home_page.dart
import 'package:flutter/material.dart'; import 'package:peliculas/src/providers/peliculas_provider.dart'; import 'package:peliculas/src/widgets/card_swiper_widget.dart'; import 'package:peliculas/src/widgets/movie_horizontal.dart'; class HomePage extends StatelessWidget { final peliculasProvider = new PeliculasProvider(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Peliculas en Cines"), backgroundColor: Colors.indigoAccent, actions: <Widget>[ IconButton( icon: Icon(Icons.search), onPressed: (){}, ) ], ), // body: SafeArea( body: Container( child: Column( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ _swiperTarjetas(), _footer(context), ], ), ), ); } Widget _swiperTarjetas() { return FutureBuilder( future: peliculasProvider.getEnCines(), builder: (BuildContext context, AsyncSnapshot<List> snapshot){ if(snapshot.hasData){ return CardSwiper( peliculas: snapshot.data, ); }else{ return Container( height: 400.0, child: Center( child: CircularProgressIndicator() ) ); } }, ); // peliculasProvider.getEnCines(); // return CardSwiper( // peliculas: [1,2,3,4,5], // ); } Widget _footer(BuildContext context){ return Container( width: double.infinity, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Container( padding: EdgeInsets.only(left: 20.0), child: Text('Populares',style: Theme.of(context).textTheme.subhead)), SizedBox(height: 5.0,), FutureBuilder( future: peliculasProvider.getPopulares(), builder: (BuildContext context, AsyncSnapshot<List> snapshot){ // print(snapshot.data); // snapshot.data?.forEach( (p) => print(p.title)); if(snapshot.hasData){ return MovieHorizontal(peliculas: snapshot.data,); }else{ return Center(child: CircularProgressIndicator()); } }, ), ], ), ); } }
0
mirrored_repositories/flutter_proyects_in_2020/peliculas/lib/src
mirrored_repositories/flutter_proyects_in_2020/peliculas/lib/src/models/pelicula_model.dart
class Peliculas{ List<Pelicula> items = new List(); Peliculas(); Peliculas.fromJsonList(List<dynamic> jsonList){ if(jsonList == null) return; for (var item in jsonList) { final pelicula = new Pelicula.fromJsonMap(item); items.add(pelicula); } } } class Pelicula { double popularity; int voteCount; bool video; String posterPath; int id; bool adult; String backdropPath; String originalLanguage; String originalTitle; List<int> genreIds; String title; double voteAverage; String overview; String releaseDate; Pelicula({ this.popularity, this.voteCount, this.video, this.posterPath, this.id, this.adult, this.backdropPath, this.originalLanguage, this.originalTitle, this.genreIds, this.title, this.voteAverage, this.overview, this.releaseDate, }); Pelicula.fromJsonMap( Map<String,dynamic> json){ popularity = json['popularity'] / 1; voteCount = json['vote_count']; video = json['video']; posterPath = json['poster_path']; id = json['id']; adult = json['adult']; backdropPath = json['backdrop_path']; originalLanguage = json['originalLanguage']; originalTitle = json['original_title']; genreIds = json['genre_ids'].cast<int>(); title = json['title']; voteAverage = json['vote_average'] / 1; overview = json['overview']; releaseDate = json['release_date']; } getPosterImg(){ if(posterPath == null){ return 'https://upload.wikimedia.org/wikipedia/commons/thumb/2/2a/Flag_of_None.svg/1280px-Flag_of_None.svg.png'; }else{ return 'https://image.tmdb.org/t/p/w500/$posterPath'; } } } enum OriginalLanguage { EN, KO, ES, HI }
0
mirrored_repositories/flutter_proyects_in_2020/peliculas/lib/src
mirrored_repositories/flutter_proyects_in_2020/peliculas/lib/src/providers/peliculas_provider.dart
import 'package:peliculas/src/models/pelicula_model.dart'; import 'dart:convert'; import 'package:http/http.dart' as http; class PeliculasProvider{ String _apiKey = '5574cf0df2ab1f778029da4403da9516'; String _url = 'api.themoviedb.org'; String _languaje = 'es-Es'; Future<List<Pelicula>> _procesarRespuesta(Uri url) async{ final resp = await http.get( url); final decodedData = json.decode(resp.body); // print(decodedData['results']); final peliculas = new Peliculas.fromJsonList(decodedData['results']); // print(peliculas.items[1].title); return peliculas.items; } Future<List<Pelicula>> getEnCines() async{ final url = Uri.https(_url, '3/movie/now_playing',{ 'api_key' : _apiKey, 'language' : _languaje }); return _procesarRespuesta(url); } Future<List<Pelicula>> getPopulares() async { final url = Uri.https(_url, '3/movie/popular',{ 'api_key' : _apiKey, 'language' : _languaje }); return _procesarRespuesta(url); } }
0
mirrored_repositories/flutter_proyects_in_2020/peliculas
mirrored_repositories/flutter_proyects_in_2020/peliculas/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:peliculas/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/flutter_proyects_in_2020/flutter_responsive
mirrored_repositories/flutter_proyects_in_2020/flutter_responsive/lib/main.dart
import 'package:flutter/material.dart'; import 'package:flutter_responsive/src/pages/home_page.dart'; void main(){ runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: HomePage(), ); } }
0
mirrored_repositories/flutter_proyects_in_2020/flutter_responsive/lib/src
mirrored_repositories/flutter_proyects_in_2020/flutter_responsive/lib/src/pages/home_page.dart
import 'package:flutter/material.dart'; import 'package:responsive_builder/responsive_builder.dart'; class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { return ScreenTypeLayout( mobile: Container(color: Colors.blue,), tablet: Container(color: Colors.yellow), desktop: Container(color: Colors.red), watch: Container(color: Colors.purple), ); } }
0
mirrored_repositories/flutter_proyects_in_2020/flutter_responsive
mirrored_repositories/flutter_proyects_in_2020/flutter_responsive/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_responsive/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/flutter_proyects_in_2020/components
mirrored_repositories/flutter_proyects_in_2020/components/lib/main.dart
import 'package:components/src/pages/alert_page.dart'; import 'package:components/src/routes/route.dart'; import 'package:flutter/material.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; // import 'package:components/src/pages/home_temp.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, localizationsDelegates: [ GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, ], supportedLocales: [ const Locale('es','US'), const Locale('es','ES') ], title: 'Material App', // home: HomePage(), initialRoute: '/', routes: getAplicationRoutes(), onGenerateRoute: (RouteSettings settings){ print('Ruta Llamada: ${settings.name}'); return MaterialPageRoute( builder: (BuildContext context) => AlertPage() ); }, ); } }
0
mirrored_repositories/flutter_proyects_in_2020/components/lib/src
mirrored_repositories/flutter_proyects_in_2020/components/lib/src/routes/route.dart
import 'package:components/src/pages/input_page.dart'; import 'package:components/src/pages/listview_page.dart'; import 'package:components/src/pages/slider_page.dart'; import 'package:flutter/material.dart'; import 'package:components/src/pages/alert_page.dart'; import 'package:components/src/pages/animated_container.dart'; import 'package:components/src/pages/avatar_page.dart'; import 'package:components/src/pages/card_page.dart'; import 'package:components/src/pages/home_page.dart'; Map<String, WidgetBuilder> getAplicationRoutes(){ return <String, WidgetBuilder>{ '/' : (BuildContext context ) => HomePage(), 'alert' : (BuildContext context) => AlertPage(), AvatarPage.pageName : (BuildContext context) => AvatarPage(), 'card' : (BuildContext context) => CardPage(), 'animatedContainer' : (BuildContext context) => AnimatedContainerPage(), 'inputs' : (BuildContext context) => InputPage(), 'slider' : (BuildContext context) => SliderPage(), 'list' : (BuildContext context) => ListaPage(), }; }
0
mirrored_repositories/flutter_proyects_in_2020/components/lib/src
mirrored_repositories/flutter_proyects_in_2020/components/lib/src/pages/home_temp.dart
import 'package:flutter/material.dart'; class HomePageTemp extends StatelessWidget { final opciones = ['Uno','Dos','Tres','Cuatro']; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Componentes Tap'), ), body: ListView( children: _crearItemsCorta() ), ); } List<Widget> _crearItems(){ List<Widget> lista = new List<Widget>(); for (String opt in opciones) { final tempWidget = ListTile( title: Text(opt), ); lista..add(tempWidget) ..add(Divider( thickness: 1.0,)); } return lista; } List<Widget> _crearItemsCorta(){ return opciones.map((item) { return ListTile( title: Text(item + '!'), subtitle: Text('Cualquier cosa'), leading: Icon(Icons.account_balance), trailing: Icon(Icons.keyboard_arrow_right), onTap: (){}, ); }).toList(); } }
0
mirrored_repositories/flutter_proyects_in_2020/components/lib/src
mirrored_repositories/flutter_proyects_in_2020/components/lib/src/pages/home_page.dart
import 'package:components/src/pages/alert_page.dart'; import 'package:components/src/providers/menu_provider.dart'; import 'package:components/src/utils/icono_string_util.dart'; import 'package:flutter/material.dart'; class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Component Flutter'), ), body: _lista(), ); } Widget _lista(){ // print(menuProvider.opciones); /* menuProvider.cargarData().then((opciones) { print('_lista'); print(opciones); });*/ return FutureBuilder( future: menuProvider.cargarData(), initialData: [], builder: (context, AsyncSnapshot<List<dynamic>> snapshot){ // print('_builder'); // print(snapshot.data); return ListView( children: _listaItems(snapshot.data, context), ); }, ); /* return ListView( children: _listaItems(), );*/ } List<Widget> _listaItems(List<dynamic> data , BuildContext context) { // return [ // ListTile(title: Text('Hola Mundo'),), // ListTile(title: Text('Hola Mundo'),), // ListTile(title: Text('Hola Mundo'),), // ]; final List<Widget> opciones = []; // print('_DATA'); // print(data); data.forEach((opt) { print(opt); final widgetTemp = ListTile( title : Text(opt['texto']), leading:getIcon(opt['icon']), trailing: Icon(Icons.keyboard_arrow_right, color:Colors.blue), onTap: (){ // final route = MaterialPageRoute( // builder: (context) => AlertPage() // ); // Navigator.push(context, route); Navigator.pushNamed(context, opt['ruta']); }, ); opciones..add(widgetTemp) ..add(Divider()); }); return opciones; } }
0