repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/Flutter-Google-Maps
mirrored_repositories/Flutter-Google-Maps/lib/main.dart
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Google Maps Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Google Maps Demo'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { //GoogleMapController myController; Completer<GoogleMapController> _controller = Completer(); static const LatLng _center = const LatLng(37.42796133580664, -122.085749655962); final Set<Marker> _markers = {}; LatLng _lastMapPosition = _center; static final CameraPosition initCameraPosition = CameraPosition( target: LatLng(37.42796133580664, -122.085749655962), zoom: 14.4746, ); static final CameraPosition _kLake = CameraPosition( bearing: 192.8334901395799, target: LatLng(37.43296265331129, -122.08832357078792), tilt: 59.440717697143555, zoom: 19.151926040649414); void _pinHere() { setState(() { _markers.add(Marker( markerId: MarkerId(_lastMapPosition.toString()), position: _lastMapPosition, infoWindow: InfoWindow( title: 'Hello here', snippet: 'Super!', ), icon: BitmapDescriptor.defaultMarker, )); }); } void _onCamMove(CameraPosition position) { _lastMapPosition = position.target; } @override Widget build(BuildContext context) { return Scaffold( body: Stack( children: <Widget>[ GoogleMap( mapType: MapType.hybrid, onMapCreated: (GoogleMapController controller) { _controller.complete(controller); }, initialCameraPosition: initCameraPosition, compassEnabled: true, markers: _markers, onCameraMove: _onCamMove, ), SizedBox( child: Center( child: Icon( Icons.add_location, size: 40.0, color: Colors.pink[600], ), ), ) ], ), floatingActionButton: Column( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.end, children: <Widget>[ Padding( padding: const EdgeInsets.all(4.0), child: FloatingActionButton.extended( onPressed: _goToTheLake, icon: Icon(Icons.directions_boat), label: Text('To the lake!')), ), Padding( padding: const EdgeInsets.all(4.0), child: FloatingActionButton.extended( onPressed: _pinHere, icon: Icon(Icons.add_location), label: Text('Pin Here'), backgroundColor: Colors.pink, ), ) ], ), ); } Future<void> _goToTheLake() async { final GoogleMapController controller = await _controller.future; controller.animateCamera(CameraUpdate.newCameraPosition(_kLake)); } }
0
mirrored_repositories/Flutter-Google-Maps
mirrored_repositories/Flutter-Google-Maps/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_google_maps/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/Readify/my_library_app
mirrored_repositories/Readify/my_library_app/lib/main.dart
import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:my_library_app/app/widgets/custom_app_bar.dart'; import 'package:my_library_app/ui/pages/home_page.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { final textTheme = Theme.of(context).textTheme; return MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData( useMaterial3: true, textTheme: GoogleFonts.latoTextTheme(textTheme).copyWith( bodyMedium: GoogleFonts.oswald(textStyle: textTheme.bodyMedium), ), ), home: Scaffold( appBar: customAppBar(), endDrawer: kIsWeb ? null : const CustomDrawer(), body: const HomePage(), ), ); } }
0
mirrored_repositories/Readify/my_library_app/lib
mirrored_repositories/Readify/my_library_app/lib/network/api.dart
import 'dart:convert'; import 'package:dio/dio.dart'; import 'package:my_library_app/network/custom_exception.dart'; import 'package:my_library_app/schemas/schemas.dart'; class ApiClient { static final Dio _dio = Dio( BaseOptions( baseUrl: 'https://www.googleapis.com/', connectTimeout: const Duration(seconds: 5), receiveTimeout: const Duration(seconds: 5), ), ); String prefix = "v1/"; static String apiKey = "AIzaSyBYkPWj6lMxzvETjjEbE78jBMOWb4c7ya0"; static Future<ApiResponse> getBookListByCategory(String category) async { try { final response = await _dio.get('/books/v1/volumes', queryParameters: { 'q': 'subject:$category', 'key': apiKey, 'maxResult': 30, }); if (response.statusCode == 200) { final Map<String, dynamic> responseData = json.decode(response.toString()); return ApiResponse.fromJson(responseData); } else { throw CustomException("Something went wrong"); } } catch (error) { throw CustomException("Network Error: $error"); } } static Future<Response> postBook(Map<String, dynamic> data) async { try { Response response = await _dio.post('/books', data: data); if (response.statusCode == 201) { return response; } else { return throw CustomException("Some thing went wrong"); } } catch (error) { throw CustomException("Network Error: $error"); } } }
0
mirrored_repositories/Readify/my_library_app/lib
mirrored_repositories/Readify/my_library_app/lib/network/custom_exception.dart
class CustomException implements Exception { final String message; CustomException(this.message); @override String toString() => message; }
0
mirrored_repositories/Readify/my_library_app/lib
mirrored_repositories/Readify/my_library_app/lib/network/implementation.dart
import 'package:my_library_app/network/api.dart'; import 'package:my_library_app/schemas/schemas.dart'; class NetWorkImplementation { static Future<List<Book>> getBookListByCategory(String category) async { ApiResponse response = await ApiClient.getBookListByCategory(category); if (response.items!.isEmpty) { return []; } else { return response.items!; } } }
0
mirrored_repositories/Readify/my_library_app/lib/app
mirrored_repositories/Readify/my_library_app/lib/app/widgets/custom_app_bar.dart
import 'package:flutter/material.dart'; customAppBar() { return AppBar( title: SizedBox(width: 220, child: Image.asset('assets/images/web_logo.png')), centerTitle: true, ); } class CustomDrawer extends StatefulWidget { const CustomDrawer({super.key}); @override State<CustomDrawer> createState() => _CustomDrawerState(); } class _CustomDrawerState extends State<CustomDrawer> { @override Widget build(BuildContext context) { return Drawer( width: MediaQuery.of(context).size.width * 0.7, child: Container( color: const Color.fromARGB(255, 241, 236, 236), child: ListView( padding: EdgeInsets.zero, children: <Widget>[ DrawerHeader( padding: EdgeInsets.zero, child: Image.asset( 'assets/images/app_logo.jpeg', width: double.infinity, height: 200, // Set the height of the header fit: BoxFit.cover, // Use cover for best fit ), ), ListTile( title: const Text('Log in', style: TextStyle(color: Colors.red)), onTap: () { // Handle log in action }, ), ListTile( title: const Text('Sign in', style: TextStyle(color: Colors.red)), onTap: () { // Handle sign in action }, ), ListTile( title: const Text('Profile', style: TextStyle(color: Colors.red)), onTap: () { // Handle profile action }, ), ListTile( title: const Text('Sign out', style: TextStyle(color: Colors.red)), onTap: () { // Handle sign out action }, ), ], ), ), ); } }
0
mirrored_repositories/Readify/my_library_app/lib
mirrored_repositories/Readify/my_library_app/lib/schemas/schemas.dart
import 'package:json_annotation/json_annotation.dart'; part 'schemas.g.dart'; @JsonSerializable(explicitToJson: true) class ApiResponse { final String? kind; final int? totalItems; final List<Book>? items; ApiResponse({this.kind, this.totalItems, this.items}); factory ApiResponse.fromJson(Map<String, dynamic> json) => _$ApiResponseFromJson(json); Map<String, dynamic> toJson() => _$ApiResponseToJson(this); } @JsonSerializable(explicitToJson: true) class Book { final String? kind; final String? id; final String? etag; final String? selfLink; final VolumeInfo? volumeInfo; final SaleInfo? saleInfo; final AccessInfo? accessInfo; Book( {this.kind, this.id, this.etag, this.selfLink, this.volumeInfo, this.saleInfo, this.accessInfo}); factory Book.fromJson(Map<String, dynamic> json) => _$BookFromJson(json); Map<String, dynamic> toJson() => _$BookToJson(this); } @JsonSerializable(explicitToJson: true) class VolumeInfo { final String? title; final String? subtitle; final List<String>? authors; final String? publisher; final String? publishedDate; final String? description; final List<IndustryIdentifiers>? industryIdentifiers; final ReadingModes? readingModes; final int? pageCount; final String? printType; final List<String>? categories; final double? averageRating; final int? ratingsCount; final String? maturityRating; final bool? allowAnonLogging; final String? contentVersion; final PanelizationSummary? panelizationSummary; final ImageLinks? imageLinks; final String? language; final String? previewLink; final String? infoLink; final String? canonicalVolumeLink; VolumeInfo({ this.title, this.subtitle, this.authors, this.publisher, this.publishedDate, this.description, this.industryIdentifiers, this.readingModes, this.pageCount, this.printType, this.categories, this.averageRating, this.ratingsCount, this.maturityRating, this.allowAnonLogging, this.contentVersion, this.panelizationSummary, this.imageLinks, this.language, this.previewLink, this.infoLink, this.canonicalVolumeLink, }); factory VolumeInfo.fromJson(Map<String, dynamic> json) => _$VolumeInfoFromJson(json); Map<String, dynamic> toJson() => _$VolumeInfoToJson(this); } @JsonSerializable(explicitToJson: true) class IndustryIdentifiers { final String? type; final String? identifier; IndustryIdentifiers({this.type, this.identifier}); factory IndustryIdentifiers.fromJson(Map<String, dynamic> json) => _$IndustryIdentifiersFromJson(json); Map<String, dynamic> toJson() => _$IndustryIdentifiersToJson(this); } @JsonSerializable(explicitToJson: true) class ReadingModes { final bool? text; final bool? image; ReadingModes({this.text, this.image}); factory ReadingModes.fromJson(Map<String, dynamic> json) => _$ReadingModesFromJson(json); Map<String, dynamic> toJson() => _$ReadingModesToJson(this); } @JsonSerializable(explicitToJson: true) class PanelizationSummary { final bool? containsEpubBubbles; final bool? containsImageBubbles; PanelizationSummary({this.containsEpubBubbles, this.containsImageBubbles}); factory PanelizationSummary.fromJson(Map<String, dynamic> json) => _$PanelizationSummaryFromJson(json); Map<String, dynamic> toJson() => _$PanelizationSummaryToJson(this); } @JsonSerializable(explicitToJson: true) class ImageLinks { final String? smallThumbnail; final String? thumbnail; ImageLinks({this.smallThumbnail, this.thumbnail}); factory ImageLinks.fromJson(Map<String, dynamic> json) => _$ImageLinksFromJson(json); Map<String, dynamic> toJson() => _$ImageLinksToJson(this); } @JsonSerializable(explicitToJson: true) class SaleInfo { final String? country; final String? saleability; final bool? isEbook; SaleInfo({this.country, this.saleability, this.isEbook}); factory SaleInfo.fromJson(Map<String, dynamic> json) => _$SaleInfoFromJson(json); Map<String, dynamic> toJson() => _$SaleInfoToJson(this); } @JsonSerializable(explicitToJson: true) class AccessInfo { final String? country; final String? viewability; final bool? embeddable; final bool? publicDomain; final String? textToSpeechPermission; final Epub? epub; final Epub? pdf; final String? webReaderLink; final String? accessViewStatus; final bool? quoteSharingAllowed; AccessInfo({ this.country, this.viewability, this.embeddable, this.publicDomain, this.textToSpeechPermission, this.epub, this.pdf, this.webReaderLink, this.accessViewStatus, this.quoteSharingAllowed, }); factory AccessInfo.fromJson(Map<String, dynamic> json) => _$AccessInfoFromJson(json); Map<String, dynamic> toJson() => _$AccessInfoToJson(this); } @JsonSerializable(explicitToJson: true) class Epub { final bool? isAvailable; final String? acsTokenLink; Epub({this.isAvailable, this.acsTokenLink}); factory Epub.fromJson(Map<String, dynamic> json) => _$EpubFromJson(json); Map<String, dynamic> toJson() => _$EpubToJson(this); }
0
mirrored_repositories/Readify/my_library_app/lib
mirrored_repositories/Readify/my_library_app/lib/schemas/schemas.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'schemas.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** ApiResponse _$ApiResponseFromJson(Map<String, dynamic> json) => ApiResponse( kind: json['kind'] as String?, totalItems: json['totalItems'] as int?, items: (json['items'] as List<dynamic>?) ?.map((e) => Book.fromJson(e as Map<String, dynamic>)) .toList(), ); Map<String, dynamic> _$ApiResponseToJson(ApiResponse instance) => <String, dynamic>{ 'kind': instance.kind, 'totalItems': instance.totalItems, 'items': instance.items?.map((e) => e.toJson()).toList(), }; Book _$BookFromJson(Map<String, dynamic> json) => Book( kind: json['kind'] as String?, id: json['id'] as String?, etag: json['etag'] as String?, selfLink: json['selfLink'] as String?, volumeInfo: json['volumeInfo'] == null ? null : VolumeInfo.fromJson(json['volumeInfo'] as Map<String, dynamic>), saleInfo: json['saleInfo'] == null ? null : SaleInfo.fromJson(json['saleInfo'] as Map<String, dynamic>), accessInfo: json['accessInfo'] == null ? null : AccessInfo.fromJson(json['accessInfo'] as Map<String, dynamic>), ); Map<String, dynamic> _$BookToJson(Book instance) => <String, dynamic>{ 'kind': instance.kind, 'id': instance.id, 'etag': instance.etag, 'selfLink': instance.selfLink, 'volumeInfo': instance.volumeInfo?.toJson(), 'saleInfo': instance.saleInfo?.toJson(), 'accessInfo': instance.accessInfo?.toJson(), }; VolumeInfo _$VolumeInfoFromJson(Map<String, dynamic> json) => VolumeInfo( title: json['title'] as String?, subtitle: json['subtitle'] as String?, authors: (json['authors'] as List<dynamic>?)?.map((e) => e as String).toList(), publisher: json['publisher'] as String?, publishedDate: json['publishedDate'] as String?, description: json['description'] as String?, industryIdentifiers: (json['industryIdentifiers'] as List<dynamic>?) ?.map((e) => IndustryIdentifiers.fromJson(e as Map<String, dynamic>)) .toList(), readingModes: json['readingModes'] == null ? null : ReadingModes.fromJson(json['readingModes'] as Map<String, dynamic>), pageCount: json['pageCount'] as int?, printType: json['printType'] as String?, categories: (json['categories'] as List<dynamic>?) ?.map((e) => e as String) .toList(), averageRating: (json['averageRating'] as num?)?.toDouble(), ratingsCount: json['ratingsCount'] as int?, maturityRating: json['maturityRating'] as String?, allowAnonLogging: json['allowAnonLogging'] as bool?, contentVersion: json['contentVersion'] as String?, panelizationSummary: json['panelizationSummary'] == null ? null : PanelizationSummary.fromJson( json['panelizationSummary'] as Map<String, dynamic>), imageLinks: json['imageLinks'] == null ? null : ImageLinks.fromJson(json['imageLinks'] as Map<String, dynamic>), language: json['language'] as String?, previewLink: json['previewLink'] as String?, infoLink: json['infoLink'] as String?, canonicalVolumeLink: json['canonicalVolumeLink'] as String?, ); Map<String, dynamic> _$VolumeInfoToJson(VolumeInfo instance) => <String, dynamic>{ 'title': instance.title, 'subtitle': instance.subtitle, 'authors': instance.authors, 'publisher': instance.publisher, 'publishedDate': instance.publishedDate, 'description': instance.description, 'industryIdentifiers': instance.industryIdentifiers?.map((e) => e.toJson()).toList(), 'readingModes': instance.readingModes?.toJson(), 'pageCount': instance.pageCount, 'printType': instance.printType, 'categories': instance.categories, 'averageRating': instance.averageRating, 'ratingsCount': instance.ratingsCount, 'maturityRating': instance.maturityRating, 'allowAnonLogging': instance.allowAnonLogging, 'contentVersion': instance.contentVersion, 'panelizationSummary': instance.panelizationSummary?.toJson(), 'imageLinks': instance.imageLinks?.toJson(), 'language': instance.language, 'previewLink': instance.previewLink, 'infoLink': instance.infoLink, 'canonicalVolumeLink': instance.canonicalVolumeLink, }; IndustryIdentifiers _$IndustryIdentifiersFromJson(Map<String, dynamic> json) => IndustryIdentifiers( type: json['type'] as String?, identifier: json['identifier'] as String?, ); Map<String, dynamic> _$IndustryIdentifiersToJson( IndustryIdentifiers instance) => <String, dynamic>{ 'type': instance.type, 'identifier': instance.identifier, }; ReadingModes _$ReadingModesFromJson(Map<String, dynamic> json) => ReadingModes( text: json['text'] as bool?, image: json['image'] as bool?, ); Map<String, dynamic> _$ReadingModesToJson(ReadingModes instance) => <String, dynamic>{ 'text': instance.text, 'image': instance.image, }; PanelizationSummary _$PanelizationSummaryFromJson(Map<String, dynamic> json) => PanelizationSummary( containsEpubBubbles: json['containsEpubBubbles'] as bool?, containsImageBubbles: json['containsImageBubbles'] as bool?, ); Map<String, dynamic> _$PanelizationSummaryToJson( PanelizationSummary instance) => <String, dynamic>{ 'containsEpubBubbles': instance.containsEpubBubbles, 'containsImageBubbles': instance.containsImageBubbles, }; ImageLinks _$ImageLinksFromJson(Map<String, dynamic> json) => ImageLinks( smallThumbnail: json['smallThumbnail'] as String?, thumbnail: json['thumbnail'] as String?, ); Map<String, dynamic> _$ImageLinksToJson(ImageLinks instance) => <String, dynamic>{ 'smallThumbnail': instance.smallThumbnail, 'thumbnail': instance.thumbnail, }; SaleInfo _$SaleInfoFromJson(Map<String, dynamic> json) => SaleInfo( country: json['country'] as String?, saleability: json['saleability'] as String?, isEbook: json['isEbook'] as bool?, ); Map<String, dynamic> _$SaleInfoToJson(SaleInfo instance) => <String, dynamic>{ 'country': instance.country, 'saleability': instance.saleability, 'isEbook': instance.isEbook, }; AccessInfo _$AccessInfoFromJson(Map<String, dynamic> json) => AccessInfo( country: json['country'] as String?, viewability: json['viewability'] as String?, embeddable: json['embeddable'] as bool?, publicDomain: json['publicDomain'] as bool?, textToSpeechPermission: json['textToSpeechPermission'] as String?, epub: json['epub'] == null ? null : Epub.fromJson(json['epub'] as Map<String, dynamic>), pdf: json['pdf'] == null ? null : Epub.fromJson(json['pdf'] as Map<String, dynamic>), webReaderLink: json['webReaderLink'] as String?, accessViewStatus: json['accessViewStatus'] as String?, quoteSharingAllowed: json['quoteSharingAllowed'] as bool?, ); Map<String, dynamic> _$AccessInfoToJson(AccessInfo instance) => <String, dynamic>{ 'country': instance.country, 'viewability': instance.viewability, 'embeddable': instance.embeddable, 'publicDomain': instance.publicDomain, 'textToSpeechPermission': instance.textToSpeechPermission, 'epub': instance.epub?.toJson(), 'pdf': instance.pdf?.toJson(), 'webReaderLink': instance.webReaderLink, 'accessViewStatus': instance.accessViewStatus, 'quoteSharingAllowed': instance.quoteSharingAllowed, }; Epub _$EpubFromJson(Map<String, dynamic> json) => Epub( isAvailable: json['isAvailable'] as bool?, acsTokenLink: json['acsTokenLink'] as String?, ); Map<String, dynamic> _$EpubToJson(Epub instance) => <String, dynamic>{ 'isAvailable': instance.isAvailable, 'acsTokenLink': instance.acsTokenLink, };
0
mirrored_repositories/Readify/my_library_app/lib/ui
mirrored_repositories/Readify/my_library_app/lib/ui/widgets/loader.dart
import 'package:flutter/material.dart'; class CustomLoader extends StatelessWidget { const CustomLoader({super.key}); @override Widget build(BuildContext context) { return SizedBox( width: 100, height: 100, child: Image.asset("assets/images/loader_2.gif"), ); } }
0
mirrored_repositories/Readify/my_library_app/lib/ui
mirrored_repositories/Readify/my_library_app/lib/ui/widgets/book_container.dart
import 'package:flutter/material.dart'; import 'package:progressive_image/progressive_image.dart'; class BookContainer extends StatelessWidget { const BookContainer({ Key? key, required this.title, this.imageUrl, required this.containerHeight, required this.containerWidth, }) : super(key: key); final String title; final String? imageUrl; final double containerHeight; final double containerWidth; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(8.0), child: Column( children: [ ClipRRect( borderRadius: const BorderRadius.all(Radius.circular(5)), child: imageUrl != null ? ProgressiveImage( placeholder: NetworkImage(imageUrl!), thumbnail: NetworkImage(imageUrl!), image: NetworkImage(imageUrl!), width: containerWidth, height: containerHeight - 20, ) : Image.asset( "assets/images/no_image_available.jpg", width: containerWidth, height: containerHeight - 20, ), ), SizedBox( width: containerWidth, height: 20, child: Text( title, overflow: TextOverflow.ellipsis, ), ) ], ), ); } }
0
mirrored_repositories/Readify/my_library_app/lib/ui
mirrored_repositories/Readify/my_library_app/lib/ui/pages/home_page.dart
import 'package:carousel_slider/carousel_slider.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:my_library_app/network/implementation.dart'; import 'package:my_library_app/schemas/schemas.dart'; import 'package:my_library_app/ui/widgets/book_container.dart'; import 'package:my_library_app/ui/widgets/loader.dart'; class HomePage extends StatefulWidget { const HomePage({super.key}); @override State<HomePage> createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { bool _isLoading = true; List<Book> healthList = []; List<Book> technologyList = []; List<Book> horrorList = []; List<String> carouselList = [ "assets/sliders/slider_1.png", "assets/sliders/slider_2.png", "assets/sliders/slider_3.png", "assets/sliders/slider_4.png", ]; @override void initState() { loadBooks(); super.initState(); } loadBooks() async { healthList = await NetWorkImplementation.getBookListByCategory("health"); technologyList = await NetWorkImplementation.getBookListByCategory("technology"); horrorList = await NetWorkImplementation.getBookListByCategory("horror"); setState(() { _isLoading = false; }); } @override Widget build(BuildContext context) { double width = MediaQuery.of(context).size.width; double height = MediaQuery.of(context).size.height; return SizedBox( width: width, height: height, child: _isLoading ? const CustomLoader() : SingleChildScrollView( child: Column( children: [ //CarouselSlider carouselSlider(carouselList), const Divider(), Container( padding: const EdgeInsets.only(left: 15, right: 15), child: Column( children: [ headerText("Health"), const Divider(), gapBuilder(), layoutBuilderForBookContainer(context, healthList), gapBuilder(), headerText("Technology"), const Divider(), layoutBuilderForBookContainer(context, technologyList), headerText("Horror"), const Divider(), gapBuilder(), layoutBuilderForBookContainer(context, horrorList) ], ), ), ], ), ), ); } } carouselSlider(List<String> carouselList) { return CarouselSlider.builder( options: CarouselOptions( height: kIsWeb ? 400 : 200, autoPlay: true, autoPlayInterval: const Duration(seconds: 3), autoPlayAnimationDuration: const Duration(milliseconds: 800), autoPlayCurve: Curves.fastOutSlowIn, enlargeCenterPage: true, enlargeFactor: 0.3, ), itemCount: 4, itemBuilder: (BuildContext context, int index, int pageViewIndex) => Padding( padding: const EdgeInsets.all(5), child: ClipRRect( borderRadius: BorderRadius.circular(5), child: Image.asset( carouselList[index], fit: kIsWeb ? BoxFit.fill : BoxFit.fitWidth, width: MediaQuery.of(context) .size .width, // Full width of the screen minus padding height: double.infinity, // Take full height available ), ), ), ); } gapBuilder() { return const SizedBox( height: 10, ); } headerText(String header) { return Align( alignment: Alignment.topLeft, child: InkWell( child: Text(header), ), ); } layoutBuilderForBookContainer(BuildContext context, List<Book> bookList) { double width = MediaQuery.of(context).size.width; double height = MediaQuery.of(context).size.height; return SizedBox( width: width * 0.9, height: kIsWeb ? height * 0.2 : height * 0.2, child: ListView.builder( scrollDirection: Axis.horizontal, itemCount: bookList.length > 10 ? 20 : bookList.length, itemBuilder: (context, index) { return LayoutBuilder( builder: (context, constraints) { double containerHeight = kIsWeb ? constraints.maxHeight * 0.9 : constraints.maxHeight * 0.8; double containerWidth = kIsWeb ? constraints.maxWidth * 0.1 : constraints.maxWidth * 0.8; return SizedBox( width: kIsWeb ? width * 0.1 : width * 0.3, height: height * 0.9, child: BookContainer( title: bookList[index].volumeInfo!.title!, imageUrl: bookList[index].volumeInfo?.imageLinks?.thumbnail, containerHeight: containerHeight, containerWidth: containerWidth, ), ); }, ); }, ), ); }
0
mirrored_repositories/Readify/my_library_app
mirrored_repositories/Readify/my_library_app/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility 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:my_library_app/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/financial_literacy_game
mirrored_repositories/financial_literacy_game/lib/main.dart
import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '/l10n/lg_intl.dart'; import 'config/constants.dart'; import 'config/themes.dart'; import 'domain/game_data_notifier.dart'; import 'firebase_options.dart'; import 'l10n/l10n.dart'; import 'presentation/screens/home_page.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, ); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); // This widget is the root of your application. @override Widget build(BuildContext context) { return const ProviderScope( child: MaterialAppConsumerWidget(), ); } } class MaterialAppConsumerWidget extends ConsumerWidget { const MaterialAppConsumerWidget({ super.key, }); @override Widget build(BuildContext context, WidgetRef ref) { return MaterialApp( debugShowCheckedModeBanner: false, title: appTitle, themeMode: ThemeMode.system, theme: lightTheme, darkTheme: darkTheme, locale: ref.watch(gameDataNotifierProvider).locale, localizationsDelegates: const [ AppLocalizations.delegate, GlobalMaterialLocalizations.delegate, GlobalCupertinoLocalizations.delegate, //GlobalWidgetsLocalizations.delegate, LgMaterialLocalizations.delegate, //LgMaterialLocalizations.delegate, ], supportedLocales: L10n.all, home: const Homepage(), ); } }
0
mirrored_repositories/financial_literacy_game/lib
mirrored_repositories/financial_literacy_game/lib/config/themes.dart
import 'package:flutter/material.dart'; // light theme ThemeData lightTheme = ThemeData( brightness: Brightness.light, useMaterial3: true, // use material 3 design for all design elements //colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal), //fontFamily: 'Georgia', // define the default text family // textTheme: const TextTheme( // titleLarge: TextStyle(fontSize: 50, fontWeight: FontWeight.bold), // titleSmall: TextStyle(fontSize: 20, fontWeight: FontWeight.bold), // labelLarge: TextStyle(fontSize: 20), // ), ); // dark theme is a copy of light theme with specific modifications ThemeData darkTheme = lightTheme.copyWith( brightness: Brightness.dark, );
0
mirrored_repositories/financial_literacy_game/lib
mirrored_repositories/financial_literacy_game/lib/config/color_palette.dart
import 'package:flutter/material.dart'; class ColorPalette { Color get background => const Color.fromRGBO(224, 247, 250, 1.0); Color get appBarBackground => const Color.fromRGBO(128, 222, 234, 1.0); Color get backgroundSectionCard => const Color.fromRGBO(128, 222, 234, 1.0); Color get backgroundContentCard => const Color.fromRGBO(0, 131, 143, 1.0); Color get cashIndicator => const Color.fromRGBO(255, 160, 122, 1.0); Color get popUpBackground => const Color.fromRGBO(224, 247, 250, 1.0); Color get buttonBackground => const Color.fromRGBO(0, 131, 143, 1.0); Color get buttonBackgroundSpecial => const Color.fromRGBO(90, 97, 97, 1.0); Color get selectedButtonBackground => const Color.fromRGBO(76, 175, 80, 1.0); Color get darkText => const Color.fromRGBO(0, 0, 0, 0.85); Color get lightText => const Color.fromRGBO(255, 255, 255, 1.0); Color get gameWinText => const Color.fromRGBO(76, 175, 80, 1.0); Color get gameLostText => const Color.fromRGBO(244, 67, 54, 1.0); Color get lifeBarForeground => const Color.fromRGBO(76, 175, 80, 1.0); Color get lifeBarBackground => const Color.fromRGBO(70, 68, 68, 0.85); Color get errorSnackBarBackground => const Color.fromRGBO(244, 67, 54, 1.0); }
0
mirrored_repositories/financial_literacy_game/lib
mirrored_repositories/financial_literacy_game/lib/config/constants.dart
const String appTitle = 'FinSim Game Paola'; // confetti duration in seconds const int showConfettiSeconds = 2; // maximum Width of play area const double playAreaMaxWidth = 600; // aspect ratio of overview content cards (cash, income, expenses) const double overviewAspectRatio = 1; // aspect ratio of asset content cards (cows, chickens, goats) const double assetsAspectRatio = 1; // decimal points for borrow and interest rates // on "investment options" screen const int decimalValuesToDisplay = 0; // initial values when new level starts const double defaultLevelStartMoney = 5; const double defaultPersonalIncome = 8; const double defaultPersonalExpenses = 7; // default values const int defaultLifeSpan = 6; const int defaultLoanTerm = 2; const double defaultCashInterest = 0.05; // used when not randomized // limits for random values const double minimumSavingsRate = 0.0; const double maximumSavingsRate = 0.10; const double stepsSavingsRate = 0.05; const double minimumInterestRate = 0.15; const double maximumInterestRate = 0.30; const double stepsInterestRate = 0.05; const double minimumRiskLevel = 0.05; const double maximumRiskLevel = 0.25; const double stepsRiskLevel = 0.05; const double priceVariation = 0.20; // varies price of asset by +/- 20% const int incomeVariation = 1; // varies income of asset by +/- $1 enum BuyDecision { buyCash, loan, dontBuy, }
0
mirrored_repositories/financial_literacy_game/lib/presentation
mirrored_repositories/financial_literacy_game/lib/presentation/widgets/content_card.dart
import 'package:flutter/material.dart'; import '../../config/color_palette.dart'; class ContentCard extends StatelessWidget { const ContentCard({ super.key, required this.content, this.aspectRatio = 1.0, }); final Widget content; final double aspectRatio; @override Widget build(BuildContext context) { return AspectRatio( aspectRatio: aspectRatio, child: Container( decoration: BoxDecoration( color: ColorPalette().backgroundContentCard, borderRadius: BorderRadius.circular(12.0), ), child: Padding( padding: const EdgeInsets.all(8.0), child: content, ), ), ); } }
0
mirrored_repositories/financial_literacy_game/lib/presentation
mirrored_repositories/financial_literacy_game/lib/presentation/widgets/section_card.dart
import 'package:financial_literacy_game/config/color_palette.dart'; import 'package:flutter/material.dart'; class SectionCard extends StatelessWidget { const SectionCard({ super.key, required this.title, required this.content, }); final String title; final Widget content; @override Widget build(BuildContext context) { return Container( decoration: BoxDecoration( color: ColorPalette().backgroundSectionCard, borderRadius: BorderRadius.circular(22.0), ), child: Padding( padding: const EdgeInsets.all(18.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( title, style: TextStyle( fontSize: 20.0, color: ColorPalette().darkText, ), ), const SizedBox(height: 10), content, ], ), ), ); } }
0
mirrored_repositories/financial_literacy_game/lib/presentation
mirrored_repositories/financial_literacy_game/lib/presentation/widgets/asset_detail_dialog.dart
import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../config/color_palette.dart'; import '../../domain/game_data_notifier.dart'; class AssetDetailDialog extends ConsumerWidget { const AssetDetailDialog({ super.key, }); @override Widget build(BuildContext context, WidgetRef ref) { return AlertDialog( title: Text(AppLocalizations.of(context)!.assets[0].toUpperCase()), content: Column( mainAxisSize: MainAxisSize.min, children: [ AspectRatio( aspectRatio: 9.0, child: Container( color: Colors.lightBlue, child: Row( children: const [], ), ), ), ...ref .watch(gameDataNotifierProvider) .assets .map( (asset) => Padding( padding: const EdgeInsets.symmetric(vertical: 3.0), child: AspectRatio( aspectRatio: 9.0, child: Row( children: [ Row( children: [ Text( '${asset.numberOfAnimals.toString()} x', style: TextStyle( fontSize: 20.0, color: ColorPalette().darkText, ), ), const SizedBox(width: 5.0), Image.asset(asset.imagePath), ], ), Expanded( flex: 4, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 10.0), child: Container( height: 10.0, decoration: BoxDecoration( borderRadius: BorderRadius.circular(50.0), color: ColorPalette().lifeBarBackground, ), child: Align( alignment: Alignment.centerLeft, child: FractionallySizedBox( widthFactor: asset.age / asset.lifeExpectancy, child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(50.0), color: ColorPalette().lifeBarForeground, ), ), ), ), ), ), ), const SizedBox(width: 10), Text( asset.income.toStringAsFixed(2), style: TextStyle( fontSize: 16.0, color: ColorPalette().darkText, ), ), ], ), ), ), ) .toList(), AspectRatio( aspectRatio: 9.0, child: Text( ref .watch(gameDataNotifierProvider.notifier) .calculateTotalIncome() .toStringAsFixed(2), textAlign: TextAlign.right, style: TextStyle( fontSize: 16.0, color: ColorPalette().darkText, ), ), ) ], ), ); } }
0
mirrored_repositories/financial_literacy_game/lib/presentation
mirrored_repositories/financial_literacy_game/lib/presentation/widgets/sign_in_dialog.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../config/color_palette.dart'; import '../../domain/concepts/person.dart'; import '../../domain/game_data_notifier.dart'; import '../../domain/utils/database.dart'; import '../../domain/utils/device_and_personal_data.dart'; import '../../domain/utils/utils.dart'; import 'menu_dialog.dart'; class SignInDialog extends ConsumerStatefulWidget { const SignInDialog({Key? key}) : super(key: key); @override ConsumerState<SignInDialog> createState() => _SignInDialogState(); } class _SignInDialogState extends ConsumerState<SignInDialog> { late TextEditingController firstNameTextController; late TextEditingController lastNameTextController; bool isProcessing = false; Future<bool> setPersonData(Person enteredPerson) async { if (enteredPerson.firstName == '' || enteredPerson.lastName == '') { showErrorSnackBar( context: context, errorMessage: AppLocalizations.of(context)!.enterName.capitalize(), ); return false; } // remove whitespaces String trimmedFirstName = enteredPerson.firstName!.trim(); String trimmedLastName = enteredPerson.lastName!.trim(); // remove leading or trailing dashes ("-") String cleanedFirstName = removeTrailing("-", trimmedFirstName); cleanedFirstName = removeLeading("-", cleanedFirstName); String cleanedLastName = removeTrailing("-", trimmedLastName); cleanedLastName = removeLeading("-", cleanedLastName); // Capitalize first letter and lower case all other letters cleanedFirstName = "${cleanedFirstName[0].toUpperCase()}${cleanedFirstName.substring(1).toLowerCase()}"; cleanedLastName = "${cleanedLastName[0].toUpperCase()}${cleanedLastName.substring(1).toLowerCase()}"; Person cleanedPerson = Person( firstName: cleanedFirstName, lastName: cleanedLastName, ); ref.read(gameDataNotifierProvider.notifier).setPerson(cleanedPerson); savePersonLocally(cleanedPerson); await saveUserInFirestore(cleanedPerson); ref.read(gameDataNotifierProvider.notifier).resetGame(); return true; } @override void initState() { super.initState(); firstNameTextController = TextEditingController(); lastNameTextController = TextEditingController(); } @override void dispose() { super.dispose(); firstNameTextController.dispose(); lastNameTextController.dispose(); } @override Widget build(BuildContext context) { return Stack( children: [ MenuDialog( showCloseButton: false, title: AppLocalizations.of(context)!.titleSignIn, content: Column( mainAxisSize: MainAxisSize.min, children: [ SizedBox( height: MediaQuery.of(context).viewInsets.bottom == 0 ? 150 : 100, child: SingleChildScrollView( child: Text(AppLocalizations.of(context)!.welcomeText), ), ), TextField( enabled: !isProcessing, controller: firstNameTextController, decoration: InputDecoration( hintText: AppLocalizations.of(context)! .hintFirstName .capitalize()), inputFormatters: [ FilteringTextInputFormatter.allow(RegExp('[^0-9]')) ], ), TextField( enabled: !isProcessing, controller: lastNameTextController, decoration: InputDecoration( hintText: AppLocalizations.of(context)! .hintLastName .capitalize()), inputFormatters: [ FilteringTextInputFormatter.allow(RegExp('[^0-9]')) ], ), ], ), actions: [ ElevatedButton( style: ElevatedButton.styleFrom( elevation: 5.0, backgroundColor: ColorPalette().buttonBackground, foregroundColor: ColorPalette().lightText, ), onPressed: isProcessing ? null : () async { setState(() { isProcessing = true; }); bool personWasCreated = await setPersonData( Person( firstName: firstNameTextController.text, lastName: lastNameTextController.text, ), ); //await Future.delayed(const Duration(seconds: 2)); if (personWasCreated) { if (context.mounted) { Navigator.of(context).pop(); // showDialog( // barrierDismissible: false, // context: context, // builder: (context) { // return const HowToPlayDialog(); // }, //); } } else { setState(() { isProcessing = false; }); } }, child: Text( AppLocalizations.of(context)!.continueButton.capitalize()), ), ], ), if (isProcessing) const Align( alignment: Alignment.center, child: CircularProgressIndicator(), ), ], ); } }
0
mirrored_repositories/financial_literacy_game/lib/presentation
mirrored_repositories/financial_literacy_game/lib/presentation/widgets/lost_game_dialog.dart
import 'package:auto_size_text/auto_size_text.dart'; import 'package:financial_literacy_game/domain/utils/utils.dart'; import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../config/color_palette.dart'; import '../../domain/game_data_notifier.dart'; import '../../domain/utils/database.dart'; class LostGameDialog extends StatelessWidget { final WidgetRef ref; const LostGameDialog({ required this.ref, super.key, }); @override Widget build(BuildContext context) { return AlertDialog( content: SizedBox( height: 100, width: 100, child: AutoSizeText( AppLocalizations.of(context)!.lostGame, style: TextStyle( fontSize: 20, height: 2, // line height 200%, 1= 100%, were 0.9 = 90% of actual line height color: ColorPalette().gameLostText, // font color fontStyle: FontStyle.normal, ), ), ), actions: [ TextButton( onPressed: () { ref.read(gameDataNotifierProvider.notifier).restartLevel(); Navigator.pop(context); }, child: Text(AppLocalizations.of(context)!.restartLevel.capitalize()), ), TextButton( onPressed: () { endCurrentGameSession(status: Status.lost); ref.read(gameDataNotifierProvider.notifier).resetGame(); Navigator.pop(context); }, child: Text(AppLocalizations.of(context)!.restartGame.capitalize()), ), ], ); } }
0
mirrored_repositories/financial_literacy_game/lib/presentation
mirrored_repositories/financial_literacy_game/lib/presentation/widgets/is_this_you_dialog.dart
import 'package:financial_literacy_game/presentation/widgets/sign_in_dialog_with_code.dart'; import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../config/color_palette.dart'; import '../../domain/concepts/person.dart'; import '../../domain/game_data_notifier.dart'; import '../../domain/utils/database.dart'; import '../../domain/utils/device_and_personal_data.dart'; import 'menu_dialog.dart'; class IsThisYouDialog extends ConsumerStatefulWidget { final Person person; const IsThisYouDialog({required this.person, Key? key}) : super(key: key); @override ConsumerState<IsThisYouDialog> createState() => _IsThisYouDialogState(); } class _IsThisYouDialogState extends ConsumerState<IsThisYouDialog> { bool isProcessing = false; @override void initState() { super.initState(); } @override void dispose() { super.dispose(); } @override Widget build(BuildContext context) { return Stack( children: [ MenuDialog( showCloseButton: false, title: AppLocalizations.of(context)!.confirmNameTitle, content: Text(AppLocalizations.of(context)! .confirmName(widget.person.firstName!, widget.person.lastName!)), actions: [ ElevatedButton( style: ElevatedButton.styleFrom( elevation: 5.0, backgroundColor: ColorPalette().buttonBackground, foregroundColor: ColorPalette().lightText, ), onPressed: () { Navigator.of(context).pop(); showDialog( barrierDismissible: false, context: context, builder: (context) { return const SignInDialogNew(); }, ); }, child: Text( AppLocalizations.of(context)!.noButton, ), ), ElevatedButton( style: ElevatedButton.styleFrom( elevation: 5.0, backgroundColor: ColorPalette().buttonBackground, foregroundColor: ColorPalette().lightText, ), onPressed: isProcessing ? null : () async { setState(() { isProcessing = true; }); ref .read(gameDataNotifierProvider.notifier) .setPerson(widget.person); savePersonLocally(widget.person); await saveUserInFirestore(widget.person); ref.read(gameDataNotifierProvider.notifier).resetGame(); setState(() { isProcessing = false; }); if (context.mounted) { Navigator.of(context).pop(); // showDialog( // barrierDismissible: false, // context: context, // builder: (context) { // return const HowToPlayDialog(); // }, // ); } }, child: Text(AppLocalizations.of(context)!.yesButton), ), ], ), if (isProcessing) const Align( alignment: Alignment.center, child: CircularProgressIndicator(), ), ], ); } }
0
mirrored_repositories/financial_literacy_game/lib/presentation
mirrored_repositories/financial_literacy_game/lib/presentation/widgets/language_selection_dialog.dart
import 'package:financial_literacy_game/config/color_palette.dart'; import 'package:financial_literacy_game/presentation/widgets/menu_dialog.dart'; import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../domain/game_data_notifier.dart'; import '../../domain/utils/device_and_personal_data.dart'; import '../../l10n/l10n.dart'; class LanguageSelectionDialog extends ConsumerWidget { final String title; final Widget? showDialogWidgetAfterPop; const LanguageSelectionDialog( {required this.title, this.showDialogWidgetAfterPop, Key? key}) : super(key: key); @override Widget build(BuildContext context, WidgetRef ref) { Locale selectedLocale = ref.watch(gameDataNotifierProvider).locale; return MenuDialog( showCloseButton: false, title: title, content: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: L10n.all .map( (locale) => Padding( padding: const EdgeInsets.only(top: 10.0), child: ElevatedButton( style: ElevatedButton.styleFrom( elevation: 5.0, backgroundColor: locale == selectedLocale ? ColorPalette().selectedButtonBackground : ColorPalette().buttonBackground, foregroundColor: ColorPalette().lightText, ), onPressed: () { ref .read(gameDataNotifierProvider.notifier) .setLocale(locale); saveLocalLocally(locale); //Navigator.of(context).pop(); }, child: Localizations.override( context: context, locale: locale, child: Builder( builder: (context) { return Text( AppLocalizations.of(context)!.language, ); }, ), ), ), ), ) .toList(), ), actions: [ ElevatedButton( style: ElevatedButton.styleFrom( elevation: 5.0, backgroundColor: ColorPalette().buttonBackground, foregroundColor: ColorPalette().lightText, ), onPressed: () { Navigator.of(context).pop(); if (showDialogWidgetAfterPop != null) { showDialog( barrierDismissible: false, context: context, builder: (context) { return showDialogWidgetAfterPop!; }, ); } }, child: Text(AppLocalizations.of(context)!.confirm), ), ], ); } }
0
mirrored_repositories/financial_literacy_game/lib/presentation
mirrored_repositories/financial_literacy_game/lib/presentation/widgets/overview_content.dart
import 'package:auto_size_text/auto_size_text.dart'; import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '/domain/utils/utils.dart'; import '../../config/color_palette.dart'; import '../../config/constants.dart'; import '../../domain/game_data_notifier.dart'; import 'content_card.dart'; class OverviewContent extends ConsumerWidget { const OverviewContent({ super.key, }); @override Widget build(BuildContext context, WidgetRef ref) { final AutoSizeGroup valueSizeGroup = AutoSizeGroup(); double convertedCash = ref .read(gameDataNotifierProvider.notifier) .convertAmount(ref.watch(gameDataNotifierProvider).cash); double convertedIncome = ref .read(gameDataNotifierProvider.notifier) .convertAmount(ref.watch(gameDataNotifierProvider.notifier).calculateTotalIncome()); double convertedExpenses = ref .read(gameDataNotifierProvider.notifier) .convertAmount(ref.watch(gameDataNotifierProvider.notifier).calculateTotalExpenses()); return Row( children: [ Expanded( child: ContentCard( aspectRatio: overviewAspectRatio, content: OverviewTileContent( title: AppLocalizations.of(context)!.cash.capitalize(), value: convertedCash, group: valueSizeGroup, ), ), ), const SizedBox(width: 7.0), Expanded( child: ContentCard( aspectRatio: overviewAspectRatio, content: OverviewTileContent( title: AppLocalizations.of(context)!.income.capitalize(), value: convertedIncome, group: valueSizeGroup, ), ), ), const SizedBox(width: 7.0), Expanded( child: ContentCard( aspectRatio: overviewAspectRatio, content: OverviewTileContent( title: AppLocalizations.of(context)!.expenses.capitalize(), value: -convertedExpenses, group: valueSizeGroup, ), ), ), ], ); } } class OverviewTileContent extends ConsumerWidget { const OverviewTileContent({ super.key, required this.title, required this.value, required this.group, }); final String title; final double value; final AutoSizeGroup group; @override Widget build(BuildContext context, WidgetRef ref) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( title, style: TextStyle( fontSize: 16.0, color: ColorPalette().lightText, ), ), Expanded( flex: 5, child: Align( alignment: Alignment.bottomRight, child: AutoSizeText( AppLocalizations.of(context)!.cashValue(value), maxLines: 1, group: group, style: TextStyle( fontSize: 100.0, color: ColorPalette().lightText, ), ), ), ), ], ); } }
0
mirrored_repositories/financial_literacy_game/lib/presentation
mirrored_repositories/financial_literacy_game/lib/presentation/widgets/cash_alert_dialog.dart
import 'package:financial_literacy_game/domain/utils/utils.dart'; import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; class CashAlertDialog extends StatelessWidget { const CashAlertDialog({ super.key, }); @override Widget build(BuildContext context) { return AlertDialog( // Dialog will be displayed when user does not have enough cash title: Text(AppLocalizations.of(context)!.error.capitalize()), content: Text(AppLocalizations.of(context)!.cashAlert.capitalize()), actions: [ TextButton( onPressed: () => Navigator.pop(context, true), child: Text(AppLocalizations.of(context)!.confirm), ) ], ); } }
0
mirrored_repositories/financial_literacy_game/lib/presentation
mirrored_repositories/financial_literacy_game/lib/presentation/widgets/how_to_play_dialog.dart
import 'package:carousel_slider/carousel_slider.dart'; import 'package:financial_literacy_game/config/color_palette.dart'; import 'package:financial_literacy_game/domain/utils/utils.dart'; import 'package:financial_literacy_game/presentation/widgets/menu_dialog.dart'; import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'cash_indicator.dart'; import 'next_period_button.dart'; class HowToPlayDialog extends ConsumerWidget { const HowToPlayDialog({Key? key}) : super(key: key); @override Widget build(BuildContext context, WidgetRef ref) { return MenuDialog( title: AppLocalizations.of(context)!.howToPlay.capitalize(), content: SizedBox( height: 300, width: 500, // max width of dialog child: CarouselSlider( options: CarouselOptions( aspectRatio: 1.0, //viewportFraction: 0.8, enlargeCenterPage: true, enableInfiniteScroll: false, ), items: [ // Carousel with text instructions to swipe through HowToPlayCard( content: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: [ const NextPeriodButton(isDemonstrationMode: true), const SizedBox(height: 20.0), Text( AppLocalizations.of(context)!.instructionText1, style: const TextStyle(fontSize: 20.0), textAlign: TextAlign.center, ), ], ), ), HowToPlayCard( content: Text( AppLocalizations.of(context)!.instructionText2, style: const TextStyle(fontSize: 20.0), textAlign: TextAlign.center, ), ), HowToPlayCard( content: Text( AppLocalizations.of(context)!.instructionText3, style: const TextStyle(fontSize: 20.0), textAlign: TextAlign.center, ), ), HowToPlayCard( content: Text( AppLocalizations.of(context)!.instructionText4, style: const TextStyle(fontSize: 20.0), textAlign: TextAlign.center, ), ), HowToPlayCard( content: Column( mainAxisSize: MainAxisSize.min, children: [ Text( '${AppLocalizations.of(context)!.cashGoal}: ' '${75.toStringAsFixed(2)}', style: TextStyle( fontSize: 17.0, color: ColorPalette().darkText, ), ), const SizedBox(height: 10.0), const CashIndicator( currentCash: 75, cashGoal: 100, ), const SizedBox(height: 20.0), Text( AppLocalizations.of(context)!.instructionText5, style: const TextStyle(fontSize: 20.0), textAlign: TextAlign.center, ), ], ), ), HowToPlayCard( content: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: [ IconButton( iconSize: 40.0, onPressed: () {}, icon: Icon( Icons.settings, color: ColorPalette().darkText, ), ), const SizedBox(height: 20.0), Text( AppLocalizations.of(context)!.instructionText6, style: const TextStyle(fontSize: 20.0), textAlign: TextAlign.center, ), ], ), ), ], ), ), ); } } class HowToPlayCard extends StatelessWidget { const HowToPlayCard({ super.key, required this.content, }); final Widget content; @override Widget build(BuildContext context) { return Container( decoration: BoxDecoration( color: ColorPalette().backgroundContentCard, borderRadius: BorderRadius.circular(15.0), ), child: Center( child: Padding( padding: const EdgeInsets.all(17.0), child: content, ), ), ); } }
0
mirrored_repositories/financial_literacy_game/lib/presentation
mirrored_repositories/financial_literacy_game/lib/presentation/widgets/next_level_dialog.dart
import 'package:financial_literacy_game/domain/utils/utils.dart'; import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../config/color_palette.dart'; import '../../domain/game_data_notifier.dart'; import 'menu_dialog.dart'; class NextLevelDialog extends StatelessWidget { final WidgetRef ref; const NextLevelDialog({ required this.ref, super.key, }); @override Widget build(BuildContext context) { return MenuDialog( showCloseButton: false, title: AppLocalizations.of(context)!.congratulations.capitalize(), content: Text( AppLocalizations.of(context)!.reachedNextLevel.capitalize(), style: TextStyle( fontSize: 20, color: ColorPalette().darkText, fontStyle: FontStyle.normal, ), ), actions: [ TextButton( onPressed: () { Navigator.pop(context); ref.read(gameDataNotifierProvider.notifier).moveToNextLevel(); }, child: Text(AppLocalizations.of(context)!.next.capitalize()), ), ], ); } }
0
mirrored_repositories/financial_literacy_game/lib/presentation
mirrored_repositories/financial_literacy_game/lib/presentation/widgets/welcome_back_dialog.dart
import 'package:financial_literacy_game/domain/game_data_notifier.dart'; import 'package:financial_literacy_game/domain/utils/utils.dart'; import 'package:financial_literacy_game/presentation/widgets/sign_in_dialog_with_code.dart'; import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../config/color_palette.dart'; import '../../domain/concepts/person.dart'; import '../../domain/utils/database.dart'; import 'menu_dialog.dart'; class WelcomeBackDialog extends ConsumerStatefulWidget { const WelcomeBackDialog({Key? key}) : super(key: key); @override ConsumerState<WelcomeBackDialog> createState() => _WelcomeBackDialogState(); } class _WelcomeBackDialogState extends ConsumerState<WelcomeBackDialog> { bool isClicked = false; @override Widget build(BuildContext context) { // get current person from game data Person person = ref.read(gameDataNotifierProvider).person; return Stack( children: [ MenuDialog( showCloseButton: false, // welcomes back user with first and last name title: AppLocalizations.of(context)!.welcomeBack( person.firstName!.capitalize(), person.lastName!.capitalize()), content: Column( mainAxisSize: MainAxisSize.min, children: [ Text( AppLocalizations.of(context)!.sameUser(person.firstName!), ), const SizedBox(height: 10.0), if (ref.read(gameDataNotifierProvider).levelId != 0) ElevatedButton( style: ElevatedButton.styleFrom( elevation: 5.0, backgroundColor: ColorPalette().buttonBackground, foregroundColor: ColorPalette().lightText, ), onPressed: isClicked ? null : () async { setState(() { isClicked = true; }); bool couldReconnect = await reconnectToGameSession(person: person); if (!couldReconnect) { ref .read(gameDataNotifierProvider.notifier) .resetGame(); } if (context.mounted) { Navigator.of(context).pop(); } }, child: Text(AppLocalizations.of(context)! .startAtLevel( (ref.read(gameDataNotifierProvider).levelId + 1) .toStringAsFixed(0)) .capitalize()), ), if (ref.read(gameDataNotifierProvider).levelId != 0) const SizedBox(width: 20), const SizedBox(height: 10.0), ElevatedButton( style: ElevatedButton.styleFrom( elevation: 5.0, backgroundColor: ColorPalette().buttonBackground, foregroundColor: ColorPalette().lightText, ), onPressed: isClicked ? null : () async { setState(() { isClicked = true; }); await endCurrentGameSession( status: Status.abandoned, person: person); ref.read(gameDataNotifierProvider.notifier).resetGame(); if (context.mounted) { Navigator.of(context).pop(); } }, child: Text( AppLocalizations.of(context)!.restartGame.capitalize()), ), const SizedBox(height: 25.0), Text( AppLocalizations.of(context)! .signInDifferentPerson .capitalize(), ), const SizedBox(height: 10.0), ElevatedButton( style: ElevatedButton.styleFrom( elevation: 5.0, backgroundColor: ColorPalette().buttonBackground, foregroundColor: ColorPalette().lightText, ), onPressed: isClicked ? null : () { setState(() { isClicked = true; }); Navigator.of(context).pop(); showDialog( barrierDismissible: false, context: context, builder: (context) { return const SignInDialogNew(); }, ); }, child: Text(AppLocalizations.of(context)!.notMe.capitalize()), ), ], ), ), if (isClicked) const Center(child: CircularProgressIndicator()), ], ); } } // // class WelcomeBackDialog extends ConsumerWidget { // const WelcomeBackDialog({Key? key}) : super(key: key); // // @override // Widget build(BuildContext context, WidgetRef ref) { // Person person = ref.read(gameDataNotifierProvider).person; // return MenuDialog( // showCloseButton: false, // title: 'Welcome back, ${person.firstName} ${person.lastName}!', // content: Column( // mainAxisSize: MainAxisSize.min, // children: [ // Text( // "If you are ${person.firstName}, simply start the game.", // ), // const SizedBox(height: 10.0), // Row( // mainAxisSize: MainAxisSize.min, // mainAxisAlignment: MainAxisAlignment.center, // children: [ // if (ref.read(gameDataNotifierProvider).levelId != 0) // ElevatedButton( // style: ElevatedButton.styleFrom( // elevation: 5.0, // backgroundColor: ColorPalette().buttonBackground, // foregroundColor: ColorPalette().lightText, // ), // onPressed: () async { // bool couldReconnect = // await reconnectToGameSession(person: person); // if (!couldReconnect) { // ref.read(gameDataNotifierProvider.notifier).resetGame(); // } // if (context.mounted) { // Navigator.of(context).pop(); // } // }, // child: Text( // 'Start at level ${ref.read(gameDataNotifierProvider).levelId + 1}'), // ), // if (ref.read(gameDataNotifierProvider).levelId != 0) // const SizedBox(width: 20), // ElevatedButton( // style: ElevatedButton.styleFrom( // elevation: 5.0, // backgroundColor: ColorPalette().buttonBackground, // foregroundColor: ColorPalette().lightText, // ), // onPressed: () async { // await endCurrentGameSession( // status: Status.abandoned, person: person); // ref.read(gameDataNotifierProvider.notifier).resetGame(); // if (context.mounted) { // Navigator.of(context).pop(); // } // }, // child: Text(AppLocalizations.of(context)!.restartGame), // ), // ], // ), // const SizedBox(height: 25.0), // Text( // AppLocalizations.of(context)!.signInDifferentPerson, // ), // const SizedBox(height: 10.0), // ElevatedButton( // style: ElevatedButton.styleFrom( // elevation: 5.0, // backgroundColor: ColorPalette().buttonBackground, // foregroundColor: ColorPalette().lightText, // ), // onPressed: () { // Navigator.of(context).pop(); // showDialog( // barrierDismissible: false, // context: context, // builder: (context) { // return const SignInDialog(); // }, // ); // }, // child: Text(AppLocalizations.of(context)!.notMe), // ), // ], // ), // ); // } // }
0
mirrored_repositories/financial_literacy_game/lib/presentation
mirrored_repositories/financial_literacy_game/lib/presentation/widgets/next_period_button.dart
import 'package:auto_size_text/auto_size_text.dart'; import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../config/color_palette.dart'; import 'investment_dialog.dart'; class NextPeriodButton extends ConsumerWidget { const NextPeriodButton({ this.isDemonstrationMode = false, super.key, }); final bool isDemonstrationMode; @override Widget build(BuildContext context, WidgetRef ref) { return SizedBox( width: 120, height: 30, child: ElevatedButton( style: ElevatedButton.styleFrom( elevation: 5.0, foregroundColor: ColorPalette().darkText, backgroundColor: ColorPalette().cashIndicator, textStyle: const TextStyle(fontSize: 20.0), ), onPressed: () { if (!isDemonstrationMode) { showDialog( barrierDismissible: false, context: context, builder: (context) { return InvestmentDialog(ref: ref); }); } }, child: AutoSizeText(AppLocalizations.of(context)!.next.toUpperCase()), ), ); } }
0
mirrored_repositories/financial_literacy_game/lib/presentation
mirrored_repositories/financial_literacy_game/lib/presentation/widgets/sign_in_dialog_with_code.dart
import 'package:financial_literacy_game/presentation/widgets/sign_in_with_name_dialog.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../config/color_palette.dart'; import '../../domain/concepts/person.dart'; import '../../domain/utils/database.dart'; import '../../domain/utils/utils.dart'; import 'is_this_you_dialog.dart'; import 'menu_dialog.dart'; class SignInDialogNew extends ConsumerStatefulWidget { const SignInDialogNew({Key? key}) : super(key: key); @override ConsumerState<SignInDialogNew> createState() => _SignInDialogNewState(); } class _SignInDialogNewState extends ConsumerState<SignInDialogNew> { late TextEditingController uidTextController; bool isProcessing = false; Future<Person?> findPersonByUID({required String uid}) async { // Exit if code has wrong length and show warning if (uid.length != 7) { showErrorSnackBar( context: context, errorMessage: AppLocalizations.of(context)!.enterUID.capitalize(), ); return null; } // CHECK IF USER WITH UID ALREADY EXISTS (ANYWHERE) Person? user = await searchUserbyUIDInFirestore(uid); if (user != null) { //print('${user.firstName} ${user.lastName}'); //ref.read(gameDataNotifierProvider.notifier).setPerson(user); //savePersonLocally(user); //await saveUserInFirestore(user); //ref.read(gameDataNotifierProvider.notifier).resetGame(); return user; } else { if (context.mounted) { showErrorSnackBar( context: context, errorMessage: AppLocalizations.of(context)!.codeNotFound, ); } return null; } } @override void initState() { super.initState(); uidTextController = TextEditingController(); } @override void dispose() { super.dispose(); uidTextController.dispose(); } @override Widget build(BuildContext context) { return Stack( children: [ MenuDialog( showCloseButton: false, title: AppLocalizations.of(context)!.titleSignIn.capitalize(), content: Column( mainAxisSize: MainAxisSize.min, children: [ // Commented out the welcome screen // SizedBox( // height: // MediaQuery.of(context).viewInsets.bottom == 0 ? 150 : 100, // child: SingleChildScrollView( // child: Text(AppLocalizations.of(context)!.welcomeText), // ), // ), TextField( enabled: !isProcessing, controller: uidTextController, decoration: InputDecoration( hintText: AppLocalizations.of(context)!.hintUID), // Length of code is 7 characters maxLength: 7, maxLengthEnforcement: MaxLengthEnforcement.enforced, inputFormatters: [ FilteringTextInputFormatter.allow(RegExp('[A-Z0-9]')) ], keyboardType: TextInputType.text, textCapitalization: TextCapitalization.characters, ), ], ), actions: [ ElevatedButton( style: ElevatedButton.styleFrom( elevation: 5.0, backgroundColor: ColorPalette().buttonBackgroundSpecial, foregroundColor: ColorPalette().lightText, ), // button when no code available onPressed: () { Navigator.of(context).pop(); showDialog( barrierDismissible: false, context: context, builder: (context) { return const SignInWithNameDialog(); }, ); }, child: Text(AppLocalizations.of(context)!.noCodeButton), ), ElevatedButton( style: ElevatedButton.styleFrom( elevation: 5.0, backgroundColor: ColorPalette().buttonBackground, foregroundColor: ColorPalette().lightText, ), onPressed: isProcessing ? null : () async { setState(() { isProcessing = true; }); Person? foundPerson = await findPersonByUID(uid: uidTextController.text); if (foundPerson != null) { if (context.mounted) { Navigator.of(context).pop(); showDialog( barrierDismissible: false, context: context, builder: (context) { return IsThisYouDialog(person: foundPerson); }, ); } } else { setState(() { isProcessing = false; }); } }, child: Text( AppLocalizations.of(context)!.continueButton.capitalize()), ), ], ), if (isProcessing) const Align( alignment: Alignment.center, child: CircularProgressIndicator(), ), ], ); } }
0
mirrored_repositories/financial_literacy_game/lib/presentation
mirrored_repositories/financial_literacy_game/lib/presentation/widgets/sign_in_with_name_dialog.dart
import 'package:financial_literacy_game/presentation/widgets/sign_in_dialog_with_code.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../config/color_palette.dart'; import '../../domain/concepts/person.dart'; import '../../domain/game_data_notifier.dart'; import '../../domain/utils/database.dart'; import '../../domain/utils/device_and_personal_data.dart'; import '../../domain/utils/utils.dart'; import 'menu_dialog.dart'; class SignInWithNameDialog extends ConsumerStatefulWidget { const SignInWithNameDialog({Key? key}) : super(key: key); @override ConsumerState<SignInWithNameDialog> createState() => _SignInWithNameDialogState(); } class _SignInWithNameDialogState extends ConsumerState<SignInWithNameDialog> { late TextEditingController firstNameTextController; late TextEditingController lastNameTextController; bool isProcessing = false; Future<bool> setPersonData(Person enteredPerson) async { // show error message when text field left blank if (enteredPerson.firstName == '' || enteredPerson.lastName == '') { showErrorSnackBar( context: context, errorMessage: AppLocalizations.of(context)!.enterName.capitalize(), ); return false; } // remove whitespaces from text fields String trimmedFirstName = enteredPerson.firstName!.trim(); String trimmedLastName = enteredPerson.lastName!.trim(); // remove leading or trailing dashes ("-") String cleanedFirstName = removeTrailing("-", trimmedFirstName); cleanedFirstName = removeLeading("-", cleanedFirstName); String cleanedLastName = removeTrailing("-", trimmedLastName); cleanedLastName = removeLeading("-", cleanedLastName); // Capitalize first letter and lower case all other letters cleanedFirstName = "${cleanedFirstName[0].toUpperCase()}${cleanedFirstName.substring(1).toLowerCase()}"; cleanedLastName = "${cleanedLastName[0].toUpperCase()}${cleanedLastName.substring(1).toLowerCase()}"; // create cleaned person Person cleanedPerson = Person( firstName: cleanedFirstName, lastName: cleanedLastName, uid: enteredPerson.uid, ); // set the new person in the game data as current player ref.read(gameDataNotifierProvider.notifier).setPerson(cleanedPerson); savePersonLocally(cleanedPerson); await saveUserInFirestore(cleanedPerson); // reset game when new user starts playing ref.read(gameDataNotifierProvider.notifier).resetGame(); return true; } @override void initState() { super.initState(); firstNameTextController = TextEditingController(); lastNameTextController = TextEditingController(); } @override void dispose() { super.dispose(); firstNameTextController.dispose(); lastNameTextController.dispose(); } @override Widget build(BuildContext context) { return Stack( children: [ MenuDialog( showCloseButton: false, title: AppLocalizations.of(context)!.titleSignIn.capitalize(), content: Column( mainAxisSize: MainAxisSize.min, children: [ Text(AppLocalizations.of(context)!.signInName), TextField( enabled: !isProcessing, controller: firstNameTextController, decoration: InputDecoration( hintText: AppLocalizations.of(context)! .hintFirstName .capitalize()), inputFormatters: [ FilteringTextInputFormatter.allow(RegExp('[^0-9]')) ], ), TextField( enabled: !isProcessing, controller: lastNameTextController, decoration: InputDecoration( hintText: AppLocalizations.of(context)! .hintLastName .capitalize()), inputFormatters: [ FilteringTextInputFormatter.allow(RegExp('[^0-9]')) ], ), ], ), actions: [ ElevatedButton( style: ElevatedButton.styleFrom( elevation: 5.0, backgroundColor: ColorPalette().buttonBackground, foregroundColor: ColorPalette().lightText, ), onPressed: () { Navigator.of(context).pop(); showDialog( barrierDismissible: false, context: context, builder: (context) { return const SignInDialogNew(); }, ); }, child: Text(AppLocalizations.of(context)!.backButton), ), ElevatedButton( style: ElevatedButton.styleFrom( elevation: 5.0, backgroundColor: ColorPalette().buttonBackground, foregroundColor: ColorPalette().lightText, ), onPressed: isProcessing ? null : () async { setState(() { isProcessing = true; }); bool personWasCreated = await setPersonData( Person( firstName: firstNameTextController.text, lastName: lastNameTextController.text, uid: 'test', ), ); //await Future.delayed(const Duration(seconds: 2)); if (personWasCreated) { if (context.mounted) { Navigator.of(context).pop(); // showDialog( // barrierDismissible: false, // context: context, // builder: (context) { // return const HowToPlayDialog(); // }, // ); } } else { setState(() { isProcessing = false; }); } }, child: Text( AppLocalizations.of(context)!.continueButton.capitalize()), ), ], ), if (isProcessing) const Align( alignment: Alignment.center, child: CircularProgressIndicator(), ), ], ); } }
0
mirrored_repositories/financial_literacy_game/lib/presentation
mirrored_repositories/financial_literacy_game/lib/presentation/widgets/cash_indicator.dart
import 'dart:math'; import 'package:flutter/material.dart'; import '../../config/color_palette.dart'; class CashIndicator extends StatelessWidget { final double currentCash; final double cashGoal; const CashIndicator({ super.key, required this.currentCash, required this.cashGoal, }); @override Widget build(BuildContext context) { return LayoutBuilder(builder: (context, constraints) { return Stack( clipBehavior: Clip.none, children: [ Container( height: 10, decoration: BoxDecoration( color: Colors.black54, borderRadius: BorderRadius.circular(20.0), ), ), Positioned( top: -1.0, child: Container( height: 12, width: max(0, min(constraints.maxWidth, constraints.maxWidth * currentCash / cashGoal)), decoration: BoxDecoration( color: ColorPalette().cashIndicator, borderRadius: BorderRadius.circular(20.0), ), ), ), ], ); }); } }
0
mirrored_repositories/financial_literacy_game/lib/presentation
mirrored_repositories/financial_literacy_game/lib/presentation/widgets/investment_dialog.dart
import 'dart:math'; import 'package:auto_size_text/auto_size_text.dart'; import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../config/color_palette.dart'; import '../../config/constants.dart'; import '../../domain/concepts/asset.dart'; import '../../domain/concepts/level.dart'; import '../../domain/concepts/loan.dart'; import '../../domain/entities/assets.dart'; import '../../domain/entities/levels.dart'; import '../../domain/game_data_notifier.dart'; import '../../domain/utils/utils.dart'; import 'asset_carousel.dart'; import 'cash_alert_dialog.dart'; import 'lost_game_dialog.dart'; import 'next_level_dialog.dart'; import 'won_game_dialog.dart'; class InvestmentDialog extends StatefulWidget { final WidgetRef ref; const InvestmentDialog({Key? key, required this.ref}) : super(key: key); @override State<InvestmentDialog> createState() => _InvestmentDialogState(); } void checkBankruptcy(WidgetRef ref, BuildContext context) { if (ref.read(gameDataNotifierProvider).isBankrupt) { showDialog( barrierDismissible: false, context: context, builder: (context) { return LostGameDialog(ref: ref); }, ); } } void checkGameHasEnded(WidgetRef ref, BuildContext context) { if (ref.read(gameDataNotifierProvider).gameIsFinished) { ref.read(gameDataNotifierProvider.notifier).showConfetti(); showDialog( barrierDismissible: false, context: context, builder: (context) { return WonGameDialog(ref: ref); }, ); } } void checkNextLevelReached(WidgetRef ref, BuildContext context) { if (ref.read(gameDataNotifierProvider).currentLevelSolved) { ref.read(gameDataNotifierProvider.notifier).showConfetti(); showDialog( barrierDismissible: false, context: context, builder: (context) { return NextLevelDialog(ref: ref); }, ); } } class _InvestmentDialogState extends State<InvestmentDialog> { final AutoSizeGroup textGroup = AutoSizeGroup(); late List<Asset> levelAssets; late Loan levelLoan; late Level currentLevel; int _selectedIndex = 0; @override void initState() { Level defaultLevel = levels[widget.ref.read(gameDataNotifierProvider).levelId]; currentLevel = defaultLevel.copyWith( loan: defaultLevel.loanInterestRandomized ? getRandomLoan() : defaultLevel.loan, savingsRate: defaultLevel.savingsInterestRandomized ? getRandomDouble( start: minimumSavingsRate, end: maximumSavingsRate, steps: stepsSavingsRate, ) : defaultLevel.savingsRate, ); if (currentLevel.assetTypeRandomized) { List<Asset> randomizedAssets = []; for (int i = 0; i < currentLevel.assets.length; i++) { randomizedAssets.add(currentLevel.assetRiskLevelActive ? getRandomAsset() : getRandomAsset().copyWith(riskLevel: 0)); } currentLevel = currentLevel.copyWith(assets: randomizedAssets); } if (currentLevel.assetRiskLevelActive && currentLevel.assetRiskLevelRandomized) { List<Asset> randomizedRiskAssets = []; for (Asset asset in currentLevel.assets) { randomizedRiskAssets.add( asset.copyWith( riskLevel: getRandomDouble( start: minimumRiskLevel, end: maximumRiskLevel, steps: stepsRiskLevel, ), ), ); } currentLevel = currentLevel.copyWith(assets: randomizedRiskAssets); } if (currentLevel.assetIncomeAndCostsRandomized) { List<Asset> randomizedIncomeAndCostsAssets = []; for (Asset asset in currentLevel.assets) { randomizedIncomeAndCostsAssets.add( asset.copyWith( price: asset.price + (asset.price ~/ (1 / getRandomDouble( start: 0, end: priceVariation, steps: 0.01)) * (Random().nextBool() ? -1 : 1)), income: asset.income + (Random().nextBool() ? -1 : 1) * (Random().nextBool() ? 0 : incomeVariation), ), ); } currentLevel = currentLevel.copyWith(assets: randomizedIncomeAndCostsAssets); } levelAssets = currentLevel.assets; levelLoan = currentLevel.loan; //widget.ref.read(gameDataNotifierProvider.notifier).setCashInterest(currentLevel.savingsRate); super.initState(); } void setIndex(int index) { setState(() { _selectedIndex = index; }); } @override Widget build(BuildContext context) { Asset selectedAsset = levelAssets[_selectedIndex]; Future<bool> showNotEnoughCash() async { return await showDialog( context: context, barrierDismissible: false, builder: (context) { return const CashAlertDialog(); }); } Future<bool> showAnimalDiedWarning(Asset asset) async { return await showDialog( context: context, barrierDismissible: false, builder: (context) { return AlertDialog( title: Text(AppLocalizations.of(context)!.warning), content: asset.numberOfAnimals > 1 ? Text(AppLocalizations.of(context)!.assetsDied.capitalize()) : Text( AppLocalizations.of(context)!.assetDied(asset.type.name)), actions: [ TextButton( onPressed: () => Navigator.pop(context, true), child: Text(AppLocalizations.of(context)!.confirm), ) ], ); }); } return Center( child: SingleChildScrollView( child: AlertDialog( backgroundColor: ColorPalette().popUpBackground, insetPadding: EdgeInsets.zero, // title: Text( // AppLocalizations.of(context)!.investmentOptions, // style: const TextStyle( // fontSize: 20.0, // fontWeight: FontWeight.bold, // ), // ), content: SizedBox( width: min(MediaQuery.of(context).size.width, 400), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ AutoSizeText( AppLocalizations.of(context)! .currentCash(widget.ref .read(gameDataNotifierProvider.notifier) .convertAmount( widget.ref.read(gameDataNotifierProvider).cash)) .capitalize(), maxLines: 2, style: const TextStyle( fontSize: 25, fontWeight: FontWeight.bold), group: textGroup, ), const SizedBox(height: 5), AspectRatio( aspectRatio: 1.0, child: AssetCarousel( assets: levelAssets, textGroup: textGroup, changingIndex: setIndex, ), ), const SizedBox(height: 5), // AutoSizeText( // AppLocalizations.of(context)!.tip.capitalize(), // maxLines: 1, // style: const TextStyle( // fontSize: 20, // fontWeight: FontWeight.bold, // ), // group: textGroup, // ), if (currentLevel.showLoanBorrowOption) AutoSizeText( AppLocalizations.of(context)! .borrowAt((levelLoan.interestRate * 100) .toStringAsFixed(decimalValuesToDisplay)) .capitalize(), maxLines: 2, style: const TextStyle( fontSize: 100, fontWeight: FontWeight.bold, ), group: textGroup, ), if (currentLevel.savingsRate != 0 || currentLevel.savingsInterestRandomized) AutoSizeText( AppLocalizations.of(context)!.interestCash( (currentLevel.savingsRate * 100) .toStringAsFixed(decimalValuesToDisplay)), maxLines: 2, style: const TextStyle( fontSize: 100, fontWeight: FontWeight.bold, ), group: textGroup, ), if (currentLevel.savingsRate == 0 && currentLevel.showCashBuyOption) AutoSizeText( generateCashTipMessage( ref: widget.ref, context: context, asset: selectedAsset, level: currentLevel, ), maxLines: 2, style: const TextStyle( fontSize: 100, fontWeight: FontWeight.bold, fontStyle: FontStyle.italic, color: Colors.black, ), group: textGroup, ), if (currentLevel.savingsRate == 0 && currentLevel.showLoanBorrowOption) AutoSizeText( generateLoanTipMessage( context: context, asset: selectedAsset, level: currentLevel, ref: widget.ref, ), maxLines: 2, style: const TextStyle( fontSize: 100, fontWeight: FontWeight.bold, fontStyle: FontStyle.italic, color: Colors.black, ), group: textGroup, ), ], ), ), actions: [ ElevatedButton( style: ElevatedButton.styleFrom( elevation: 8.0, foregroundColor: ColorPalette().lightText, backgroundColor: ColorPalette().buttonBackground, textStyle: const TextStyle(fontSize: 13.0), ), onPressed: () { widget.ref.read(gameDataNotifierProvider.notifier).advance( newCashInterest: currentLevel.savingsRate, buyDecision: BuyDecision.dontBuy, selectedAsset: selectedAsset, ); Navigator.pop(context); checkBankruptcy(widget.ref, context); checkGameHasEnded(widget.ref, context); checkNextLevelReached(widget.ref, context); }, child: Text(AppLocalizations.of(context)!.dontBuy), ), if (currentLevel.showCashBuyOption) ElevatedButton( style: ElevatedButton.styleFrom( elevation: 8.0, foregroundColor: ColorPalette().lightText, backgroundColor: ColorPalette().buttonBackground, textStyle: const TextStyle(fontSize: 13.0), ), onPressed: () async { if (await widget.ref .read(gameDataNotifierProvider.notifier) .buyAsset( selectedAsset, showNotEnoughCash, showAnimalDiedWarning, currentLevel.savingsRate, ) == true) { if (context.mounted) { Navigator.pop(context); checkBankruptcy(widget.ref, context); checkGameHasEnded(widget.ref, context); checkNextLevelReached(widget.ref, context); } } }, child: Text(AppLocalizations.of(context)!.payCash)), if (currentLevel.showLoanBorrowOption) ElevatedButton( style: ElevatedButton.styleFrom( elevation: 8.0, foregroundColor: ColorPalette().lightText, backgroundColor: ColorPalette().buttonBackground, textStyle: const TextStyle(fontSize: 13.0), ), onPressed: () async { await widget.ref .read(gameDataNotifierProvider.notifier) .loanAsset(levelLoan, selectedAsset, showAnimalDiedWarning, currentLevel.savingsRate); if (context.mounted) { Navigator.pop(context); checkBankruptcy(widget.ref, context); checkGameHasEnded(widget.ref, context); checkNextLevelReached(widget.ref, context); } }, child: Text(AppLocalizations.of(context)!.borrow)), ], ), ), ); } }
0
mirrored_repositories/financial_literacy_game/lib/presentation
mirrored_repositories/financial_literacy_game/lib/presentation/widgets/settings_dialog.dart
import 'package:financial_literacy_game/config/color_palette.dart'; import 'package:financial_literacy_game/domain/utils/utils.dart'; import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../../domain/game_data_notifier.dart'; import 'how_to_play_dialog.dart'; import 'language_selection_dialog.dart'; import 'menu_dialog.dart'; class SettingsDialog extends ConsumerWidget { const SettingsDialog({Key? key}) : super(key: key); @override Widget build(BuildContext context, WidgetRef ref) { return MenuDialog( title: AppLocalizations.of(context)!.settings.capitalize(), content: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ ElevatedButton( style: ElevatedButton.styleFrom( elevation: 5.0, backgroundColor: ColorPalette().buttonBackground, foregroundColor: ColorPalette().lightText, ), onPressed: () { Navigator.of(context).pop(); showDialog( context: context, builder: (context) { // returns the how to dialog return const HowToPlayDialog(); }, ); }, child: Text(AppLocalizations.of(context)!.howToPlay), ), const SizedBox(height: 10), ElevatedButton( style: ElevatedButton.styleFrom( elevation: 5.0, backgroundColor: ColorPalette().buttonBackground, foregroundColor: ColorPalette().lightText, ), onPressed: () async { SharedPreferences prefs = await SharedPreferences.getInstance(); await prefs.clear(); if (context.mounted) { Navigator.of(context).pop(); } }, child: Text(AppLocalizations.of(context)!.clearCache.capitalize()), ), // COMMENTED OUT: OPTION TO ADVANCE TO THE NEXT LEVEL const SizedBox(height: 10), ElevatedButton( style: ElevatedButton.styleFrom( elevation: 5.0, backgroundColor: ColorPalette().buttonBackground, foregroundColor: ColorPalette().lightText, ), onPressed: () { ref.read(gameDataNotifierProvider.notifier).moveToNextLevel(); Navigator.of(context).pop(); }, child: Text(AppLocalizations.of(context)!.nextLevel.capitalize()), ), const SizedBox(height: 10), ElevatedButton( style: ElevatedButton.styleFrom( elevation: 5.0, backgroundColor: ColorPalette().buttonBackground, foregroundColor: ColorPalette().lightText, ), onPressed: () { Navigator.of(context).pop(); showDialog( context: context, builder: (context) { return LanguageSelectionDialog( title: AppLocalizations.of(context)! .languagesTitle .capitalize(), ); }, ); }, child: Text(AppLocalizations.of(context)!.languagesTitle.capitalize()), ), // ElevatedButton( // style: ElevatedButton.styleFrom( // elevation: 5.0, // backgroundColor: ColorPalette().buttonBackground, // foregroundColor: ColorPalette().lightText, // ), // onPressed: () {}, // child: const Text('Restart Game'), // ), ], ), ); } }
0
mirrored_repositories/financial_literacy_game/lib/presentation
mirrored_repositories/financial_literacy_game/lib/presentation/widgets/won_game_dialog.dart
import 'package:auto_size_text/auto_size_text.dart'; import 'package:financial_literacy_game/config/color_palette.dart'; import 'package:financial_literacy_game/domain/utils/utils.dart'; import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../domain/game_data_notifier.dart'; import '../../domain/utils/database.dart'; class WonGameDialog extends StatelessWidget { final WidgetRef ref; const WonGameDialog({ required this.ref, super.key, }); @override Widget build(BuildContext context) { return AlertDialog( content: SizedBox( height: 100, width: 100, child: AutoSizeText( AppLocalizations.of(context)!.gameFinished.capitalize(), style: TextStyle( fontSize: 20, height: 2, //line height 200%, 1= 100%, were 0.9 = 90% of actual line height color: ColorPalette().gameWinText, // font color fontStyle: FontStyle.normal, ), ), ), actions: [ TextButton( onPressed: () { endCurrentGameSession(status: Status.won); ref.read(gameDataNotifierProvider.notifier).resetGame(); Navigator.pop(context); }, child: Text(AppLocalizations.of(context)!.restart.capitalize()), ), ], ); } }
0
mirrored_repositories/financial_literacy_game/lib/presentation
mirrored_repositories/financial_literacy_game/lib/presentation/widgets/asset_content.dart
import 'package:auto_size_text/auto_size_text.dart'; import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../config/color_palette.dart'; import '../../config/constants.dart'; import '../../domain/concepts/asset.dart'; import '../../domain/game_data_notifier.dart'; class AssetContent extends ConsumerWidget { const AssetContent({ super.key, }); @override Widget build(BuildContext context, WidgetRef ref) { final AutoSizeGroup valueSizeGroup = AutoSizeGroup(); int cows = ref.watch(gameDataNotifierProvider).cows; int chickens = ref.watch(gameDataNotifierProvider).chickens; int goats = ref.watch(gameDataNotifierProvider).goats; double cowIncome = ref .watch(gameDataNotifierProvider.notifier) .calculateIncome(AssetType.cow); double convertedCowIncome = ref.read(gameDataNotifierProvider.notifier).convertAmount(cowIncome); double chickenIncome = ref .watch(gameDataNotifierProvider.notifier) .calculateIncome(AssetType.chicken); double convertedChickenIncome = ref .read(gameDataNotifierProvider.notifier) .convertAmount(chickenIncome); double goatIncome = ref .watch(gameDataNotifierProvider.notifier) .calculateIncome(AssetType.goat); double convertedGoatIncome = ref.read(gameDataNotifierProvider.notifier).convertAmount(goatIncome); return GestureDetector( onTap: () { // showDialog( // context: context, // builder: (context) { // return const AssetDetailDialog(); // }, // ); }, child: Row( children: [ Expanded( child: SmallAssetCard( title: AppLocalizations.of(context)!.cow, count: cows, income: convertedCowIncome, group: valueSizeGroup, imagePath: 'assets/images/cow.png', )), const SizedBox(width: 7.0), Expanded( child: SmallAssetCard( title: AppLocalizations.of(context)!.chicken, count: chickens, income: convertedChickenIncome, group: valueSizeGroup, imagePath: 'assets/images/chicken.png', )), const SizedBox(width: 7.0), Expanded( child: SmallAssetCard( title: AppLocalizations.of(context)!.goat, count: goats, income: convertedGoatIncome, group: valueSizeGroup, imagePath: 'assets/images/goat.png', )), ], ), ); } } class SmallAssetCard extends ConsumerWidget { const SmallAssetCard({ super.key, required this.title, required this.count, required this.income, required this.group, required this.imagePath, }); final String title; final int count; final double income; final AutoSizeGroup group; final String imagePath; @override Widget build(BuildContext context, WidgetRef ref) { return AspectRatio( aspectRatio: assetsAspectRatio, child: Container( decoration: BoxDecoration( color: ColorPalette().backgroundContentCard, borderRadius: BorderRadius.circular(15.0), ), child: Padding( padding: const EdgeInsets.all(5.0), child: Column( children: [ Expanded( flex: 1, child: AutoSizeText( '$count x', textAlign: TextAlign.right, style: TextStyle( color: ColorPalette().lightText, fontSize: 50.0, ), ), ), // Expanded( // child: AutoSizeText( // 'x', // textAlign: TextAlign.right, // style: TextStyle( // color: ColorPalette().lightText, // fontSize: 100.0, // ), // ), // ), Expanded( flex: 2, child: Padding( padding: const EdgeInsets.all(5.0), child: Image.asset(imagePath), ), ), // Expanded( // child: Row( // children: [ // Expanded( // flex: 2, // child: AutoSizeText( // '$count', // textAlign: TextAlign.right, // style: TextStyle( // color: ColorPalette().lightText, // fontSize: 100.0, // ), // ), // ), // Expanded( // flex: 5, // child: AutoSizeText( // ' x $title', // maxLines: 1, // minFontSize: 8, // style: TextStyle( // color: ColorPalette().lightText, // fontSize: 100.0, // ), // ), // ), // ], // ), // ), Expanded( flex: 1, child: Row( children: [ Expanded( flex: 1, child: AutoSizeText( AppLocalizations.of(context)!.cashValue(income), textAlign: TextAlign.center, style: TextStyle( color: ColorPalette().lightText, fontSize: 100.0, ), ), // Align( // alignment: Alignment.centerRight, // child: AutoSizeText( // '+\$${income.toStringAsFixed(2)}', // style: TextStyle( // color: ColorPalette().lightText, // fontSize: 100.0, // ), // ), // ), ), // Expanded( // child: AutoSizeText( // ' / period', // minFontSize: 4, // maxLines: 1, // style: TextStyle( // color: ColorPalette().lightText, // fontSize: 100.0, // ), // ), // ), ], ), ), ], ), ), ), ); } }
0
mirrored_repositories/financial_literacy_game/lib/presentation
mirrored_repositories/financial_literacy_game/lib/presentation/widgets/loan_content.dart
import 'package:auto_size_text/auto_size_text.dart'; import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../config/color_palette.dart'; import '../../domain/concepts/loan.dart'; import '../../domain/game_data_notifier.dart'; class LoanContent extends ConsumerWidget { const LoanContent({ super.key, }); @override Widget build(BuildContext context, WidgetRef ref) { final AutoSizeGroup loanSizeGroup = AutoSizeGroup(); List<Loan> loans = ref.watch(gameDataNotifierProvider).loans; List<Widget> widgetList = []; for (Loan loan in loans) { widgetList.add( LoanCard( loan: loan, group: loanSizeGroup, ), ); } return Row( children: [ Expanded( child: Column( children: widgetList, ), ) ], ); } } class LoanCard extends ConsumerWidget { const LoanCard({ super.key, required this.loan, required this.group, }); final Loan loan; final AutoSizeGroup group; @override Widget build(BuildContext context, WidgetRef ref) { return Padding( padding: const EdgeInsets.only(bottom: 10.0), child: AspectRatio( aspectRatio: 9.0, child: Container( decoration: BoxDecoration( color: ColorPalette().backgroundContentCard, borderRadius: BorderRadius.circular(15.0), ), child: Padding( padding: const EdgeInsets.all(8.0), child: Row( children: [ Expanded( child: Align( alignment: Alignment.center, child: Image.asset(loan.asset.imagePath), ), ), Expanded( child: AutoSizeText( AppLocalizations.of(context)!.cashValue(ref .read(gameDataNotifierProvider.notifier) .convertAmount( loan.asset.price * (1 + loan.interestRate))), maxLines: 1, style: TextStyle( color: ColorPalette().lightText, fontSize: 50, ), ), ), Expanded( child: Align( alignment: Alignment.center, child: AutoSizeText( AppLocalizations.of(context)!.cashValue(ref .read(gameDataNotifierProvider.notifier) .convertAmount(loan.paymentPerPeriod)), maxLines: 1, style: TextStyle( color: ColorPalette().lightText, fontSize: 50.0, ), ), ), ), Expanded( child: Align( alignment: Alignment.center, child: AutoSizeText( '${loan.age} / ${loan.termInPeriods}', maxLines: 1, style: TextStyle( color: ColorPalette().lightText, fontSize: 50.0, ), ), ), ), ], ), ), ), ), ); } }
0
mirrored_repositories/financial_literacy_game/lib/presentation
mirrored_repositories/financial_literacy_game/lib/presentation/widgets/menu_dialog.dart
import 'package:defer_pointer/defer_pointer.dart'; import 'package:flutter/material.dart'; import '../../config/color_palette.dart'; class MenuDialog extends StatelessWidget { const MenuDialog({ required this.title, this.content, this.actions, this.showCloseButton = true, super.key, }); final String title; final bool showCloseButton; final Widget? content; final List<Widget>? actions; @override Widget build(BuildContext context) { return DeferredPointerHandler( child: AnimatedContainer( padding: MediaQuery.of(context).padding, duration: const Duration(milliseconds: 300), child: AlertDialog( backgroundColor: ColorPalette().background, title: Stack( clipBehavior: Clip.none, children: [ Text( title, style: TextStyle( color: ColorPalette().darkText, ), ), if (showCloseButton) Positioned( top: -30.0, right: -30.0, child: Container( width: 30, height: 30, decoration: BoxDecoration( shape: BoxShape.circle, color: ColorPalette().buttonBackground, ), child: DeferPointer( child: IconButton( iconSize: 100, padding: const EdgeInsets.all(5.0), onPressed: () => Navigator.of(context).pop(), icon: Center( child: FittedBox( child: Icon( Icons.close, color: ColorPalette().lightText, ), ), ), ), ), ), ), ], ), content: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 500), child: content, ), actions: actions, ), ), ); } }
0
mirrored_repositories/financial_literacy_game/lib/presentation
mirrored_repositories/financial_literacy_game/lib/presentation/widgets/asset_carousel.dart
import 'package:auto_size_text/auto_size_text.dart'; import 'package:carousel_slider/carousel_slider.dart'; import 'package:financial_literacy_game/domain/utils/utils.dart'; import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../config/color_palette.dart'; import '../../domain/concepts/asset.dart'; import '../../domain/game_data_notifier.dart'; class AssetCarousel extends ConsumerWidget { final List<Asset> assets; final AutoSizeGroup textGroup; final Function changingIndex; const AssetCarousel({ Key? key, required this.assets, required this.textGroup, required this.changingIndex, }) : super(key: key); @override Widget build(BuildContext context, WidgetRef ref) { // build widget to display from asset List<Widget> widgetList = []; for (Asset asset in assets) { widgetList.add( LayoutBuilder(builder: (context, constraints) { String assetName; switch (asset.type) { case AssetType.cow: { assetName = AppLocalizations.of(context)!.cow; } break; case AssetType.chicken: { assetName = AppLocalizations.of(context)!.chicken; } break; case AssetType.goat: { assetName = AppLocalizations.of(context)!.goat; } break; default: { assetName = AppLocalizations.of(context)!.chicken; } break; } return Container( height: constraints.maxHeight, width: constraints.maxWidth * 1.2, decoration: BoxDecoration( color: ColorPalette().backgroundContentCard, borderRadius: BorderRadius.circular(15.0), ), child: Padding( padding: const EdgeInsets.all(5.0), child: Column( //mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( flex: 1, child: Align( alignment: Alignment.center, child: AutoSizeText( '${asset.numberOfAnimals} x $assetName', style: const TextStyle( fontSize: 20, //fontWeight: FontWeight.bold, color: Colors.white, ), ), ), ), const Spacer(), Expanded( flex: 2, child: Align( alignment: Alignment.center, child: Image.asset(asset.imagePath, fit: BoxFit.cover), ), ), const Spacer(), Expanded( flex: 2, child: AutoSizeText( AppLocalizations.of(context)! .price(ref .read(gameDataNotifierProvider.notifier) .convertAmount(asset.price)) .capitalize(), style: const TextStyle( fontSize: 100, color: Colors.white, ), group: textGroup, ), ), Expanded( flex: 2, child: AutoSizeText( AppLocalizations.of(context)! .incomePerYear(ref .read(gameDataNotifierProvider.notifier) .convertAmount(asset.income)) .capitalize(), style: const TextStyle( fontSize: 100, color: Colors.white, ), group: textGroup, ), ), Expanded( flex: 2, child: AutoSizeText( AppLocalizations.of(context)! .lifeExpectancy(asset.lifeExpectancy) .capitalize(), style: const TextStyle( fontSize: 100, color: Colors.white, ), group: textGroup, ), ), if (asset.riskLevel > 0) Expanded( flex: 2, child: AutoSizeText( AppLocalizations.of(context)! .lifeRisk((100 / (asset.riskLevel * 100)) .toStringAsFixed(0)) .capitalize(), style: TextStyle( fontSize: 100, color: Colors.grey[200], ), group: textGroup, ), ), ], ), ), ); }), ); } return CarouselSlider( options: CarouselOptions( aspectRatio: 1.0, //viewportFraction: 0.8, enlargeCenterPage: true, enableInfiniteScroll: false, onPageChanged: (index, reason) { changingIndex(index); }), items: widgetList, ); } }
0
mirrored_repositories/financial_literacy_game/lib/presentation
mirrored_repositories/financial_literacy_game/lib/presentation/widgets/game_app_bar.dart
import 'package:auto_size_text/auto_size_text.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../config/color_palette.dart'; import '../../config/constants.dart'; import '../../domain/game_data_notifier.dart'; import '../../presentation/widgets/settings_dialog.dart'; class GameAppBar extends ConsumerWidget implements PreferredSizeWidget { const GameAppBar({ Key? key, }) : preferredSize = const Size.fromHeight(kToolbarHeight), super(key: key); @override final Size preferredSize; @override Widget build(BuildContext context, WidgetRef ref) { return AppBar( backgroundColor: ColorPalette().appBarBackground, title: Padding( padding: const EdgeInsets.only(left: 5.0), child: AutoSizeText( ref.watch(gameDataNotifierProvider).person.exists() ? '$appTitle - ${ref.watch(gameDataNotifierProvider).person.firstName} ' '${ref.watch(gameDataNotifierProvider).person.lastName}' : appTitle, style: TextStyle( fontSize: 100, color: ColorPalette().darkText, ), maxFontSize: 22, maxLines: 1, ), ), actions: [ IconButton( onPressed: () { showDialog( //barrierDismissible: true, context: context, builder: (context) { return const SettingsDialog(); }, ); }, icon: Icon( Icons.settings, color: ColorPalette().darkText, ), ), const SizedBox(width: 5.0), ], ); } }
0
mirrored_repositories/financial_literacy_game/lib/presentation
mirrored_repositories/financial_literacy_game/lib/presentation/widgets/level_info_card.dart
import 'package:financial_literacy_game/config/color_palette.dart'; import 'package:financial_literacy_game/domain/game_data_notifier.dart'; import 'package:financial_literacy_game/domain/utils/utils.dart'; import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../domain/entities/levels.dart'; import 'cash_indicator.dart'; import 'next_period_button.dart'; import 'section_card.dart'; class LevelInfoCard extends ConsumerWidget { const LevelInfoCard({ super.key, required this.levelId, required this.currentCash, required this.nextLevelCash, }); final int levelId; final double currentCash; final double nextLevelCash; @override Widget build(BuildContext context, WidgetRef ref) { double convertedCurrentCash = ref.read(gameDataNotifierProvider.notifier).convertAmount(currentCash); double convertedNextLevelCash = ref .read(gameDataNotifierProvider.notifier) .convertAmount(nextLevelCash); return Stack( children: [ SectionCard( title: AppLocalizations.of(context)! .level((levelId + 1), levels.length) .capitalize(), content: Column( children: [ Text( AppLocalizations.of(context)! .cashGoalReach(convertedNextLevelCash), style: TextStyle( fontSize: 18.0, fontWeight: FontWeight.bold, color: ColorPalette().darkText, ), ), const SizedBox(height: 7.5), Row( children: [ Text( AppLocalizations.of(context)!.cashValue(0.00), style: const TextStyle(fontSize: 16.0), ), const SizedBox(width: 8), Expanded( child: CashIndicator( currentCash: convertedCurrentCash, cashGoal: convertedNextLevelCash, ), ), const SizedBox(width: 8), Text( AppLocalizations.of(context)! .cashValue(convertedNextLevelCash), style: const TextStyle(fontSize: 16.0), ), ], ), ], ), ), const Positioned( top: 15.0, right: 15.0, child: NextPeriodButton(), ), ], ); } }
0
mirrored_repositories/financial_literacy_game/lib/presentation
mirrored_repositories/financial_literacy_game/lib/presentation/widgets/personal_content.dart
import 'package:auto_size_text/auto_size_text.dart'; import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../domain/game_data_notifier.dart'; import 'content_card.dart'; class PersonalContent extends ConsumerWidget { const PersonalContent({ super.key, }); @override Widget build(BuildContext context, WidgetRef ref) { return Row( children: [ Expanded( child: ContentCard( aspectRatio: 5.0, content: PersonalTileContent( income: ref.watch(gameDataNotifierProvider).personalIncome, expenses: ref.watch(gameDataNotifierProvider).personalExpenses, ), ), ), const SizedBox(width: 7.0), ], ); } } class PersonalTileContent extends StatelessWidget { const PersonalTileContent({ super.key, required this.income, required this.expenses, }); final double income; final double expenses; @override Widget build(BuildContext context) { return Row( children: [ Expanded( child: Align( alignment: Alignment.center, child: Column( children: [ Expanded( flex: 2, child: AutoSizeText( '\$$income', style: TextStyle( color: Colors.grey[200], fontSize: 50.0, ), ), ), Expanded( child: AutoSizeText( AppLocalizations.of(context)!.income, maxLines: 1, minFontSize: 2, style: TextStyle( color: Colors.grey[500], fontSize: 50.0, ), ), ), ], ), ), ), Expanded( child: Align( alignment: Alignment.center, child: Column( children: [ Expanded( flex: 2, child: AutoSizeText( '-\$$expenses', style: TextStyle( color: Colors.grey[200], fontSize: 50.0, ), ), ), Expanded( child: AutoSizeText( 'expenses', maxLines: 1, minFontSize: 2, style: TextStyle( color: Colors.grey[500], fontSize: 50.0, ), ), ), ], ), ), ), Expanded( child: Align( alignment: Alignment.center, child: AutoSizeText( '\$${income - expenses}', style: TextStyle( color: Colors.grey[200], fontSize: 50.0, ), ), ), ), ], ); } }
0
mirrored_repositories/financial_literacy_game/lib/presentation
mirrored_repositories/financial_literacy_game/lib/presentation/screens/home_page.dart
import 'dart:math'; import 'package:confetti/confetti.dart'; import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../config/color_palette.dart'; import '../../config/constants.dart'; import '../../domain/entities/levels.dart'; import '../../domain/game_data_notifier.dart'; import '../../domain/utils/device_and_personal_data.dart'; import '../../l10n/l10n.dart'; import '../widgets/asset_content.dart'; import '../widgets/game_app_bar.dart'; import '../widgets/language_selection_dialog.dart'; import '../widgets/level_info_card.dart'; import '../widgets/loan_content.dart'; import '../widgets/overview_content.dart'; import '../widgets/section_card.dart'; import '../widgets/sign_in_dialog_with_code.dart'; import '../widgets/welcome_back_dialog.dart'; class Homepage extends ConsumerStatefulWidget { const Homepage({Key? key}) : super(key: key); @override ConsumerState<Homepage> createState() => _HomepageState(); } class _HomepageState extends ConsumerState<Homepage> { @override void initState() { WidgetsBinding.instance.addPostFrameCallback((_) async { // get info from device that has been stored previously await getDeviceInfo(); bool personLoaded = await loadPerson(ref: ref); // get locale from system settings Locale locale = await L10n.getSystemLocale(); ref.read(gameDataNotifierProvider.notifier).setLocale(locale); // if the person has been stored from previous game sessions if (personLoaded) { // loading last level the user played bool levelLoaded = await loadLevelIDFromLocal(ref: ref); if (levelLoaded) { if (context.mounted) { showDialog( barrierDismissible: false, context: context, builder: (context) { return const WelcomeBackDialog(); }, ); } } } else { // if there is no user stored on device if (context.mounted) { showDialog( barrierDismissible: false, context: context, builder: (context) { // show language options available return LanguageSelectionDialog( title: AppLocalizations.of(context)!.selectLanguage, showDialogWidgetAfterPop: const SignInDialogNew(), ); }, ); } } }); super.initState(); } @override void dispose() { super.dispose(); } @override Widget build(BuildContext context) { int levelId = ref.watch(gameDataNotifierProvider).levelId; return Stack( children: [ Scaffold( backgroundColor: ColorPalette().background, resizeToAvoidBottomInset: false, appBar: const GameAppBar(), body: SafeArea( // homepage scrollable when screen to small child: SingleChildScrollView( child: Center( child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: playAreaMaxWidth), child: Padding( padding: const EdgeInsets.all(15.0), child: Column( children: [ LevelInfoCard( currentCash: ref.watch(gameDataNotifierProvider).cash, levelId: levelId, nextLevelCash: levels[levelId].cashGoal, ), const SizedBox(height: 10), SectionCard( title: AppLocalizations.of(context)!.overview.toUpperCase(), content: const OverviewContent(), ), const SizedBox(height: 10), // if (levels[ref.read(gameDataNotifierProvider).levelId] // .includePersonalIncome) // SectionCard( // title: AppLocalizations.of(context)! // .personal // .toUpperCase(), // content: const PersonalContent()), // if (levels[ref.read(gameDataNotifierProvider).levelId] // .includePersonalIncome) // const SizedBox(height: 10), SectionCard( title: AppLocalizations.of(context)!.assets.toUpperCase(), content: const AssetContent(), ), const SizedBox(height: 10), SectionCard( title: AppLocalizations.of(context)!.loan(2).toUpperCase(), content: const LoanContent(), ), ], ), ), ), ), ), ), ), Align( alignment: Alignment.topCenter, child: ConfettiWidget( confettiController: ref.watch(gameDataNotifierProvider).confettiController, shouldLoop: true, emissionFrequency: 0.03, numberOfParticles: 20, maxBlastForce: 25, minBlastForce: 7, // colors: [ // ColorPalette().lightText, // ColorPalette().cashIndicator, // ColorPalette().backgroundContentCard, // ], gravity: 0.2, particleDrag: 0.05, blastDirection: pi, blastDirectionality: BlastDirectionality.explosive, ), ), ], ); } }
0
mirrored_repositories/financial_literacy_game/lib
mirrored_repositories/financial_literacy_game/lib/domain/game_data_notifier.dart
import 'dart:math'; import 'package:confetti/confetti.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../config/constants.dart'; import '../l10n/l10n.dart'; import 'concepts/asset.dart'; import 'concepts/game_data.dart'; import 'concepts/loan.dart'; import 'concepts/person.dart'; import 'concepts/recorded_data.dart'; import 'entities/levels.dart'; import 'utils/database.dart'; import 'utils/device_and_personal_data.dart'; import 'utils/utils.dart'; final gameDataNotifierProvider = StateNotifierProvider<GameDataNotifier, GameData>( (ref) => GameDataNotifier()); class GameDataNotifier extends StateNotifier<GameData> { GameDataNotifier() : super( GameData( person: Person(), locale: L10n.defaultLocale, cash: levels[0].startingCash, personalIncome: (levels[0].includePersonalIncome ? levels[0].personalIncome : 0), personalExpenses: (levels[0].includePersonalIncome ? levels[0].personalExpenses : 0), confettiController: ConfettiController(), recordedDataList: [ RecordedData( levelId: 0, cashValues: [levels[0].startingCash], ), ], ), ); void setPerson(Person newPerson) { state = state.copyWith(person: newPerson); debugPrint( 'Person set to ${newPerson.firstName} ${newPerson.lastName} in game data.'); } // convert money amounts to display in local currency based on locale double convertAmount(double defaultMoneyInUSD) { return state.conversionRate * defaultMoneyInUSD; } // setting new locale (language and format) void setLocale(Locale newLocale) { if (L10n.all.contains(newLocale)) { state = state.copyWith(locale: newLocale); debugPrint('New locale set to $newLocale'); } else { debugPrint('Locale $newLocale not supported'); } } void loadLevel(int levelID) { _loadLevel(levelID); debugPrint('Level ${levelID + 1} loaded from locally saved data.'); } // show confetti animation for a certain amount of time void showConfetti() async { debugPrint('Showing confetti.'); state.confettiController.play(); await Future.delayed(const Duration(seconds: showConfettiSeconds)); state.confettiController.stop(); } // void setCashInterest(double newInterest) { // state = state.copyWith(cashInterest: newInterest); // } // function to advance to next period in game void advance({ required double newCashInterest, required BuyDecision buyDecision, required Asset selectedAsset, }) async { // update cash interest state = state.copyWith(cashInterest: newCashInterest); // calculate interest on cash state = state.copyWith(cash: state.cash * (1 + state.cashInterest)); // age assets by one period List<Asset> survivedAssets = []; for (Asset asset in state.assets) { if (asset.age < asset.lifeExpectancy) { // add to survived list if not too old and let animal age Asset olderAsset = asset.copyWith(age: asset.age + 1); survivedAssets.add(olderAsset); } } state = state.copyWith(assets: survivedAssets); // age loans by one period List<Loan> activeLoans = []; for (Loan loan in state.loans) { if (loan.age < loan.termInPeriods) { // add to loan list if not paid off Loan olderLoan = loan.copyWith(age: loan.age + 1); activeLoans.add(olderLoan); } } state = state.copyWith(loans: activeLoans); double netIncome = calculateTotalIncome() - calculateTotalExpenses(); double newCash = state.cash + netIncome; state = state.copyWith(cash: newCash); advancePeriodFirestore( newCashValue: newCash, buyDecision: buyDecision, offeredAsset: selectedAsset, ); // check if bankrupt if (state.cash < 0) { state = state.copyWith(isBankrupt: true); } // check if next level was reached //int nextLevelId = state.levelId + 1; if (state.cash >= levels[state.levelId].cashGoal) { // check if game has ended if (state.levelId + 1 >= (levels.length)) { state = state.copyWith(gameIsFinished: true); } else { // TODO: ADD NEW RECORDED DATA OBJECT TO LIST state = state.copyWith(currentLevelSolved: true); } } } void restartLevel() { // TODO: double-check why this is saved to same game session restartLevelFirebase( level: state.levelId + 1, startingCash: levels[state.levelId].startingCash, ); state = state.copyWith(isBankrupt: false); _loadLevel(state.levelId); } // move on to next level, reset cash, loans, and assets, reset level solved flag void moveToNextLevel() { // TODO: ADD NEW RECORDED DATA OBJECT // state.recordedDataList.add( // RecordedData( // levelId: state.levelId + 1, // cashValues: [levels[state.levelId + 1].startingCash], // ), // ); int nextLevelID = state.levelId + 1; _loadLevel(nextLevelID); newLevelFirestore( levelID: nextLevelID, startingCash: levels[nextLevelID].startingCash, ); } void _loadLevel(int levelID) { if (levelID >= 0 && levelID < levels.length) { // move to specified level, reset cash state = state.copyWith( levelId: levelID, cash: levels[levelID].startingCash, assets: [], // remove all previous assets loans: [], // remove all previous loans currentLevelSolved: false, // resetLevelSolved flag ); // save current level locally saveLevelIDLocally(levelID); } } void _addAsset(Asset newAsset) { List<Asset> newAssetList = copyAssetArray(state.assets); newAssetList.add(newAsset); state = state.copyWith(assets: newAssetList); } void _addLoan(Loan newLoan) { List<Loan> newLoanList = copyLoanArray(state.loans); newLoanList.add(newLoan); state = state.copyWith(loans: newLoanList); } Future<bool> _animalDied(Asset asset, Function showAnimalDied) async { if (asset.riskLevel > Random().nextDouble()) { return await showAnimalDied(asset); } else { return false; } } Future<bool> buyAsset( Asset asset, Function showNotEnoughCash, Function showAnimalDied, double newCashInterest, ) async { if (state.cash >= asset.price) { state = state.copyWith(cash: state.cash - asset.price); //check if animal died based on risk level if (!await _animalDied(asset, showAnimalDied)) { _addAsset(asset); } advance( newCashInterest: newCashInterest, buyDecision: BuyDecision.buyCash, selectedAsset: asset, ); return true; } else { showNotEnoughCash(); return false; } } Future<void> loanAsset( Loan loan, Asset asset, Function showAnimalDied, double newCashInterest, ) async { // check if animal died based on risk level if (!await _animalDied(asset, showAnimalDied)) { _addAsset(asset); } Loan issuedLoan = loan.copyWith(asset: asset); _addLoan(issuedLoan); advance( newCashInterest: newCashInterest, buyDecision: BuyDecision.loan, selectedAsset: asset, ); } double calculateTotalExpenses() { double loanPayments = 0; for (Loan loan in state.loans) { loanPayments += loan.paymentPerPeriod; } double totalExpenses = loanPayments + (levels[state.levelId].includePersonalIncome ? state.personalExpenses : 0); return totalExpenses; } // calculate total income of everything double calculateTotalIncome() { double assetIncome = 0; for (Asset asset in state.assets) { assetIncome += asset.income; } double totalIncome = assetIncome + (levels[state.levelId].includePersonalIncome ? state.personalIncome : 0); return totalIncome; } // calculate income for specific asset double calculateIncome(AssetType assetType) { double income = 0; for (Asset asset in state.assets) { if (asset.type == assetType) { income += asset.income; } } return income; } void resetGame() { state = GameData( person: state.person, locale: state.locale, // reset to level 1 with starting cash cash: levels[0].startingCash, personalIncome: (levels[0].includePersonalIncome ? levels[0].personalIncome : 0), personalExpenses: (levels[0].includePersonalIncome ? levels[0].personalExpenses : 0), confettiController: state.confettiController, ); // save current level locally saveLevelIDLocally(0); startGameSession( person: state.person, startingCash: levels[0].startingCash); } // not being used in current version of the game double calculateSavingsROI( {required double cashInterest, int lifeExpectancy = 6}) { return (state.cash * pow(1 + cashInterest, lifeExpectancy) - state.cash) / lifeExpectancy; } // double calculateBuyCashROI({ // required double riskLevel, // required double expectedIncome, // required double assetPrice, // int lifeExpectancy = 6, // }) { // return (lifeExpectancy * expectedIncome * (1 - riskLevel) - assetPrice) / lifeExpectancy; // } // // double calculateBorrowROI({ // required double riskLevel, // required double expectedIncome, // required double assetPrice, // required double interestRate, // int lifeExpectancy = 6, // }) { // return (lifeExpectancy * expectedIncome * (1 - riskLevel) - (assetPrice * (1 + interestRate))) / // lifeExpectancy; // } }
0
mirrored_repositories/financial_literacy_game/lib/domain
mirrored_repositories/financial_literacy_game/lib/domain/entities/assets.dart
import 'dart:math'; import '../concepts/asset.dart'; Asset goats = Asset( type: AssetType.goat, numberOfAnimals: 3, imagePath: 'assets/images/goat.png', price: 13, income: 3, lifeExpectancy: 5, riskLevel: 0.15, ); Asset cow = Asset( type: AssetType.cow, numberOfAnimals: 1, imagePath: 'assets/images/cow.png', price: 14, income: 4, lifeExpectancy: 4, riskLevel: 0.20, ); Asset chickens = Asset( type: AssetType.chicken, numberOfAnimals: 50, imagePath: 'assets/images/chicken.png', price: 10, income: 2, lifeExpectancy: 6, riskLevel: 0.10, ); List<Asset> allDefaultAssets = [goats, cow, chickens]; Asset getRandomAsset() { return allDefaultAssets[Random().nextInt(allDefaultAssets.length)]; }
0
mirrored_repositories/financial_literacy_game/lib/domain
mirrored_repositories/financial_literacy_game/lib/domain/entities/levels.dart
import '../concepts/level.dart'; import '../concepts/loan.dart'; import 'assets.dart'; List<Level> levels = [ // Level 1 - cash only, no interest on cash, high starting cash amount Level( startingCash: 50, cashGoal: 75, assets: [chickens.copyWith(riskLevel: 0)], loan: Loan(interestRate: 0.25, asset: cow), assetTypeRandomized: true, assetIncomeAndCostsRandomized: true, showCashBuyOption: true, savingsRate: 0.00, ), // Level 2 - cash only, no interest on cash, low starting cash amount Level( startingCash: 15, cashGoal: 50, assets: [chickens.copyWith(riskLevel: 0)], loan: Loan(interestRate: 0.25, asset: cow), assetTypeRandomized: true, assetIncomeAndCostsRandomized: true, showCashBuyOption: true, savingsRate: 0.00, ), // Level 3 - borrow only, no interest on cash, low starting cash amount Level( startingCash: 15, cashGoal: 50, assets: [chickens.copyWith(riskLevel: 0)], loan: Loan(interestRate: 0.20, asset: cow), assetTypeRandomized: true, assetIncomeAndCostsRandomized: true, showLoanBorrowOption: true, savingsRate: 0.00, ), // Level 4 - borrow and cash options, no interest on cash, low starting cash amount Level( startingCash: 10, cashGoal: 50, assets: [chickens.copyWith(riskLevel: 0)], loan: Loan(interestRate: 0.20, asset: cow), assetTypeRandomized: true, assetIncomeAndCostsRandomized: true, showCashBuyOption: true, showLoanBorrowOption: true, savingsRate: 0.00, ), // Level 5 - borrow and cash option, low starting cash amount, default risk per asset Level( startingCash: 15, cashGoal: 50, assets: [ chickens.copyWith(riskLevel: 0), ], loan: Loan(interestRate: 0.20, asset: cow), assetTypeRandomized: true, assetIncomeAndCostsRandomized: true, assetRiskLevelActive: true, assetRiskLevelRandomized: false, showCashBuyOption: true, showLoanBorrowOption: true, savingsRate: 0.00, ), // Level 6 - borrow and cash option, low starting cash amount, // multiple assets, randomized risk Level( startingCash: 15, cashGoal: 50, assets: [ chickens.copyWith(riskLevel: 0), chickens.copyWith(riskLevel: 0), chickens.copyWith(riskLevel: 0), ], loan: Loan(interestRate: 0.20, asset: cow), assetTypeRandomized: true, assetIncomeAndCostsRandomized: true, assetRiskLevelActive: true, assetRiskLevelRandomized: true, showCashBuyOption: true, showLoanBorrowOption: true, savingsRate: 0.00, ), ];
0
mirrored_repositories/financial_literacy_game/lib/domain
mirrored_repositories/financial_literacy_game/lib/domain/entities/loans.dart
import '../concepts/loan.dart'; import 'assets.dart'; Loan defaultLoan = Loan(interestRate: 0.25, asset: cow);
0
mirrored_repositories/financial_literacy_game/lib/domain
mirrored_repositories/financial_literacy_game/lib/domain/concepts/level.dart
import '../../config/constants.dart'; import '../utils/utils.dart'; import 'asset.dart'; import 'loan.dart'; class Level { final double cashGoal; final double startingCash; final double personalIncome; final double personalExpenses; final List<Asset> assets; final bool includePersonalIncome; final bool showCashBuyOption; final bool showLoanBorrowOption; final bool assetTypeRandomized; final bool assetRiskLevelActive; final bool assetRiskLevelRandomized; final bool assetIncomeAndCostsRandomized; final bool loanInterestRandomized; final bool savingsInterestRandomized; final Loan loan; final double savingsRate; Level({ required this.cashGoal, this.startingCash = defaultLevelStartMoney, this.personalIncome = defaultPersonalIncome, this.personalExpenses = defaultPersonalExpenses, required this.assets, this.includePersonalIncome = false, this.showCashBuyOption = false, this.showLoanBorrowOption = false, this.assetTypeRandomized = false, this.assetRiskLevelActive = false, this.assetRiskLevelRandomized = false, this.assetIncomeAndCostsRandomized = false, this.loanInterestRandomized = false, this.savingsInterestRandomized = false, required this.loan, this.savingsRate = defaultCashInterest, }); // method to copy custom class Level copyWith({ double? startingCash, double? cashGoal, double? personalIncome, double? personalExpenses, List<Asset>? assets, bool? includePersonalIncome, bool? showCashBuyOption, bool? showLoanBorrowOption, bool? assetTypeRandomized, bool? assetRiskLevelActive, bool? assetRiskLevelRandomized, bool? assetIncomeAndCostsRandomized, bool? loanInterestRandomized, bool? savingsInterestRandomized, Loan? loan, double? savingsRate, }) { return Level( startingCash: startingCash ?? this.startingCash, cashGoal: cashGoal ?? this.cashGoal, personalIncome: personalIncome ?? this.personalIncome, personalExpenses: personalExpenses ?? this.personalExpenses, assets: assets ?? copyAssetArray(this.assets), includePersonalIncome: includePersonalIncome ?? this.includePersonalIncome, showCashBuyOption: showCashBuyOption ?? this.showCashBuyOption, showLoanBorrowOption: showLoanBorrowOption ?? this.showLoanBorrowOption, assetTypeRandomized: assetTypeRandomized ?? this.assetTypeRandomized, assetRiskLevelActive: assetRiskLevelActive ?? this.assetRiskLevelActive, assetRiskLevelRandomized: assetRiskLevelRandomized ?? this.assetRiskLevelRandomized, assetIncomeAndCostsRandomized: assetIncomeAndCostsRandomized ?? this.assetIncomeAndCostsRandomized, loanInterestRandomized: loanInterestRandomized ?? this.loanInterestRandomized, savingsInterestRandomized: savingsInterestRandomized ?? this.savingsInterestRandomized, loan: loan ?? this.loan.copyWith(), savingsRate: savingsRate ?? this.savingsRate, ); } }
0
mirrored_repositories/financial_literacy_game/lib/domain
mirrored_repositories/financial_literacy_game/lib/domain/concepts/loan.dart
import '../../config/constants.dart'; import '../entities/assets.dart'; import '../utils/utils.dart'; import 'asset.dart'; class Loan { final double interestRate; final Asset asset; final int termInPeriods; final int age; Loan({ required this.interestRate, required this.asset, this.termInPeriods = defaultLoanTerm, this.age = 0, }); // method to copy custom class Loan copyWith({ double? interestRate, Asset? asset, int? termInPeriods, int? age, }) { return Loan( interestRate: interestRate ?? this.interestRate, asset: asset ?? this.asset.copyWith(), termInPeriods: termInPeriods ?? this.termInPeriods, age: age ?? this.age, ); } double get paymentPerPeriod { return asset.price * (1 + interestRate) / termInPeriods; } } Loan getRandomLoan() { return Loan( interestRate: getRandomDouble( start: minimumInterestRate, end: maximumInterestRate, steps: stepsInterestRate, ), asset: cow); }
0
mirrored_repositories/financial_literacy_game/lib/domain
mirrored_repositories/financial_literacy_game/lib/domain/concepts/recorded_data.dart
import '../utils/utils.dart'; class RecordedData { final int levelId; final List<double> cashValues; RecordedData({ required this.levelId, required this.cashValues, }); // method to copy custom class RecordedData copyWith({ int? levelId, List<double>? cashValues, }) { return RecordedData( levelId: levelId ?? this.levelId, cashValues: cashValues ?? copyCashArray(this.cashValues), ); } }
0
mirrored_repositories/financial_literacy_game/lib/domain
mirrored_repositories/financial_literacy_game/lib/domain/concepts/asset.dart
import '../../config/constants.dart'; class Asset { final AssetType type; final int numberOfAnimals; final String imagePath; final double price; final double income; final double riskLevel; final int lifeExpectancy; final int age; Asset({ required this.type, required this.numberOfAnimals, required this.imagePath, required this.price, required this.income, required this.riskLevel, this.lifeExpectancy = defaultLifeSpan, this.age = 0, }); // method to copy custom class Asset copyWith({ AssetType? type, int? numberOfAnimals, String? imagePath, double? price, double? income, double? riskLevel, int? lifeExpectancy, int? age, }) { return Asset( type: type ?? this.type, numberOfAnimals: numberOfAnimals ?? this.numberOfAnimals, imagePath: imagePath ?? this.imagePath, price: price ?? this.price, income: income ?? this.income, riskLevel: riskLevel ?? this.riskLevel, lifeExpectancy: lifeExpectancy ?? this.lifeExpectancy, age: age ?? this.age, ); } } enum AssetType { cow, chicken, goat, } // extension ReturnStrings on AssetType { // String get name { // switch (this) { // case AssetType.cow: // return AppLocalizations.of(context)!.cow; // case AssetType.chicken: // return AppLocalizations.of(context)!.chicken; // case AssetType.goat: // return AppLocalizations.of(context)!.goat; // } // } // }
0
mirrored_repositories/financial_literacy_game/lib/domain
mirrored_repositories/financial_literacy_game/lib/domain/concepts/game_data.dart
import 'dart:ui'; import 'package:confetti/confetti.dart'; import 'package:financial_literacy_game/l10n/l10n.dart'; import '../../config/constants.dart'; import '../../domain/concepts/recorded_data.dart'; import '../concepts/person.dart'; import '../utils/utils.dart'; import 'asset.dart'; import 'loan.dart'; class GameData { final Person person; final Locale locale; final double cash; final int levelId; final int period; final double cashInterest; final double personalIncome; final double personalExpenses; final ConfettiController confettiController; final List<Asset> assets; final List<Loan> loans; final bool isBankrupt; final bool currentLevelSolved; final bool gameIsFinished; final List<RecordedData> recordedDataList; GameData({ required this.person, required this.locale, required this.cash, required this.personalIncome, required this.personalExpenses, required this.confettiController, this.levelId = 0, this.period = 0, this.cashInterest = defaultCashInterest, this.assets = const [], this.loans = const [], this.isBankrupt = false, this.currentLevelSolved = false, this.gameIsFinished = false, this.recordedDataList = const [], }); // method to copy custom class GameData copyWith({ Person? person, Locale? locale, int? levelId, int? period, double? cash, double? cashInterest, double? personalIncome, double? personalExpenses, ConfettiController? confettiController, List<Asset>? assets, List<Loan>? loans, bool? isBankrupt, bool? currentLevelSolved, bool? gameIsFinished, List<RecordedData>? recordedDataList, }) { return GameData( person: person ?? this.person.copyWith(), locale: locale ?? this.locale, levelId: levelId ?? this.levelId, period: period ?? this.period, cash: cash ?? this.cash, cashInterest: cashInterest ?? this.cashInterest, personalIncome: personalIncome ?? this.personalIncome, personalExpenses: personalExpenses ?? this.personalExpenses, confettiController: confettiController ?? this.confettiController, assets: assets ?? copyAssetArray(this.assets), loans: loans ?? copyLoanArray(this.loans), isBankrupt: isBankrupt ?? this.isBankrupt, currentLevelSolved: currentLevelSolved ?? this.currentLevelSolved, gameIsFinished: gameIsFinished ?? this.gameIsFinished, recordedDataList: recordedDataList ?? copyRecordedDataArray(this.recordedDataList), ); } int get cows { int cows = 0; for (Asset asset in assets) { if (asset.type == AssetType.cow) { cows += asset.numberOfAnimals; } } return cows; } int get chickens { int chickens = 0; for (Asset asset in assets) { if (asset.type == AssetType.chicken) { chickens += asset.numberOfAnimals; } } return chickens; } int get goats { int goats = 0; for (Asset asset in assets) { if (asset.type == AssetType.goat) { goats += asset.numberOfAnimals; } } return goats; } double get conversionRate { return L10n.getConversionRate(locale); } }
0
mirrored_repositories/financial_literacy_game/lib/domain
mirrored_repositories/financial_literacy_game/lib/domain/concepts/person.dart
class Person { final String? firstName; final String? lastName; final String? uid; Person({ this.firstName, this.lastName, this.uid, }); Person copyWith({ String? firstName, String? lastName, String? uid, }) { return Person( firstName: firstName ?? this.firstName, lastName: lastName ?? this.lastName, uid: uid ?? this.uid, ); } bool exists() { return firstName != null && lastName != null && uid != null; } }
0
mirrored_repositories/financial_literacy_game/lib/domain
mirrored_repositories/financial_literacy_game/lib/domain/utils/device_and_personal_data.dart
import 'dart:ui'; import 'package:device_info_plus/device_info_plus.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../concepts/person.dart'; import '../game_data_notifier.dart'; Future<void> getDeviceInfo() async { DeviceInfoPlugin deviceInfo = DeviceInfoPlugin(); if (kIsWeb) { WebBrowserInfo webBrowserInfo = await deviceInfo.webBrowserInfo; debugPrint('Running on ${webBrowserInfo.userAgent}'); } } Future<bool> loadPerson({required WidgetRef ref}) async { final prefs = await SharedPreferences.getInstance(); String? savedFirstName = prefs.getString('firstName'); String? savedLastName = prefs.getString('lastName'); if (savedFirstName == null || savedLastName == null) return false; debugPrint('Loaded person $savedFirstName $savedLastName from local storage.'); Person loadedPerson = Person(firstName: savedFirstName, lastName: savedLastName); ref.read(gameDataNotifierProvider.notifier).setPerson(loadedPerson); return true; } void savePersonLocally(Person person) async { debugPrint('Save person ${person.firstName} ${person.lastName} with UID ${person.uid} to local ' 'storage.'); if (person.exists()) { final prefs = await SharedPreferences.getInstance(); prefs.setString('firstName', person.firstName!); prefs.setString('lastName', person.lastName!); prefs.setString('uid', person.uid!); } } Future<bool> loadLevelIDFromLocal({required WidgetRef ref}) async { final prefs = await SharedPreferences.getInstance(); int? savedLastPlayedLevelID = prefs.getInt('lastPlayedLevelID'); if (savedLastPlayedLevelID == null) { return false; } else { ref.read(gameDataNotifierProvider.notifier).loadLevel(savedLastPlayedLevelID); return true; } } void saveLevelIDLocally(int levelID) async { final prefs = await SharedPreferences.getInstance(); prefs.setInt('lastPlayedLevelID', levelID); } void saveLocalLocally(Locale locale) async { final prefs = await SharedPreferences.getInstance(); prefs.setString('languageCode', locale.languageCode); if (locale.countryCode != null) { prefs.setString('countryCode', locale.countryCode!); } } Future<Locale?> loadLocaleFromLocal() async { final prefs = await SharedPreferences.getInstance(); String? languageCode = prefs.getString('languageCode'); String? countryCode = prefs.getString('countryCode'); if (languageCode == null || languageCode != 'lg' && countryCode == null) { return null; } else { if (countryCode == null) { return Locale(languageCode); } else { return Locale(languageCode, countryCode); } } }
0
mirrored_repositories/financial_literacy_game/lib/domain
mirrored_repositories/financial_literacy_game/lib/domain/utils/utils.dart
import 'dart:math'; import 'package:financial_literacy_game/domain/game_data_notifier.dart'; import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../config/color_palette.dart'; import '../../domain/concepts/recorded_data.dart'; import '../concepts/asset.dart'; import '../concepts/level.dart'; import '../concepts/loan.dart'; List<RecordedData> copyRecordedDataArray(List<RecordedData> recordedDataList) { List<RecordedData> copiedRecordedDataList = []; for (RecordedData recordedData in recordedDataList) { copiedRecordedDataList.add(recordedData); } return copiedRecordedDataList; } List<double> copyCashArray(List<double> cashList) { List<double> copiedCashList = []; for (double cashValue in cashList) { copiedCashList.add(cashValue); } return copiedCashList; } List<Asset> copyAssetArray(List<Asset> assetList) { List<Asset> copiedAssetList = []; for (Asset asset in assetList) { copiedAssetList.add(asset.copyWith()); } return copiedAssetList; } // helper method to copy a list of loans List<Loan> copyLoanArray(List<Loan> loanList) { List<Loan> copiedLoanList = []; for (Loan loan in loanList) { copiedLoanList.add(loan.copyWith()); } return copiedLoanList; } // get random double value double getRandomDouble( {required double start, required double end, required double steps}) { List<double> randomStepList = List.generate( (end * 100 - start * 100) ~/ (steps * 100) + 1, (index) => start + index * steps); return randomStepList[Random().nextInt(randomStepList.length)]; } String generateCashTipMessage({ required Asset asset, required Level level, required BuildContext context, required WidgetRef ref, }) { String tipString = '${AppLocalizations.of(context)!.cash}: '; double profit = asset.income * asset.lifeExpectancy - asset.price; double convertedProfit = ref.read(gameDataNotifierProvider.notifier).convertAmount(profit); String profitString = AppLocalizations.of(context)!.cashValue(convertedProfit); tipString += '(${AppLocalizations.of(context)!.cashValue(ref.read(gameDataNotifierProvider.notifier).convertAmount(asset.income))} x ' '${asset.lifeExpectancy}) - ${AppLocalizations.of(context)!.cashValue(ref.read(gameDataNotifierProvider.notifier).convertAmount(asset.price))} = ' '$profitString'; return tipString; } String generateLoanTipMessage({ required Asset asset, required Level level, required BuildContext context, required WidgetRef ref, }) { String tipString = '${AppLocalizations.of(context)!.loan(1)}: '; double profit = asset.income * asset.lifeExpectancy - asset.price * (1 + level.loan.interestRate); double convertedProfit = ref.read(gameDataNotifierProvider.notifier).convertAmount(profit); String profitString = AppLocalizations.of(context)!.cashValue(convertedProfit); tipString += '(${AppLocalizations.of(context)!.cashValue(ref.read(gameDataNotifierProvider.notifier).convertAmount(asset.income))} x ${asset.lifeExpectancy}) - (${AppLocalizations.of(context)!.cashValue(ref.read(gameDataNotifierProvider.notifier).convertAmount(asset.price))} x ${1 + level.loan.interestRate}) = ' '$profitString'; return tipString; } // extension to allow capitalization of first letter in strings extension StringExtension on String { String capitalize() { return "${this[0].toUpperCase()}${substring(1).toLowerCase()}"; } } void showErrorSnackBar( {required BuildContext context, required String errorMessage}) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( duration: const Duration(seconds: 2), backgroundColor: ColorPalette().errorSnackBarBackground, content: Text( errorMessage, style: TextStyle(color: ColorPalette().darkText), ), ), ); } String removeTrailing(String pattern, String from) { if (pattern.isEmpty) return from; var i = from.length; while (from.startsWith(pattern, i - pattern.length)) { i -= pattern.length; } return from.substring(0, i); } String removeLeading(String pattern, String from) { if (pattern.isEmpty) return from; var i = 0; while (from.startsWith(pattern, i)) { i += pattern.length; } return from.substring(i); }
0
mirrored_repositories/financial_literacy_game/lib/domain
mirrored_repositories/financial_literacy_game/lib/domain/utils/database.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:financial_literacy_game/config/constants.dart'; import 'package:flutter/material.dart'; import '../concepts/asset.dart'; import '../concepts/person.dart'; FirebaseFirestore db = FirebaseFirestore.instance; // store the Firestore collection of users CollectionReference userCollectionRef = db.collection('users'); // store the Firestore collection of uid user list CollectionReference uidListsCollectionRef = db.collection('uidLists'); // variables to save current documents in database DocumentReference? currentGameSessionRef; DocumentReference? currentLevelDataRef; Future<QuerySnapshot> _findUserInFirestoreByUID({required String uid}) async { // call to Firestore to look up user via uid that was entered return await userCollectionRef.where('uid', isEqualTo: uid).get(); } Future<QuerySnapshot> _findUserInFirestore({required Person person}) async { return await userCollectionRef // look for current person in database .where('firstName', isEqualTo: person.firstName) .where('lastName', isEqualTo: person.lastName) .where('uid', isEqualTo: person.uid) .get(); } Future<DocumentReference?> _findLatestGameSessionRef( {required Person person}) async { QuerySnapshot userQuerySnapshot = await _findUserInFirestore(person: person); if (userQuerySnapshot.docs.length == 1) { // TODO: Can we change this to make it more general? debugPrint("Unique User Found."); // get the first document in list QueryDocumentSnapshot docSnap = userQuerySnapshot.docs.first; CollectionReference gameSessionRef = docSnap.reference.collection('gameSessions'); QuerySnapshot lastGameSessionSnap = await gameSessionRef .orderBy('startedOn', descending: true) .limit(1) .get(); debugPrint("Last game session found."); return lastGameSessionSnap.docs.first.reference; } else { debugPrint("Last game session not found."); return null; } } void _createNewLevel({ required int level, required double startingCash, }) async { if (currentGameSessionRef == null) { debugPrint('Current game session could not be found.'); return; } Map<String, dynamic> levelContent = { // information that gets saved to the database per level 'level': level, 'startedOn': DateTime.now(), 'levelStatus': Status.active.name, 'periods': 0, 'cash': [startingCash], 'decisions': [], 'offeredAssets': [], }; CollectionReference levelDataRef = currentGameSessionRef!.collection('levelData'); currentLevelDataRef = await levelDataRef.add(levelContent); } void restartLevelFirebase({ required int level, required double startingCash, }) async { if (currentLevelDataRef == null) { return; } currentLevelDataRef!.set( { 'levelStatus': Status.lost.name, 'completedOn': DateTime.now(), }, SetOptions(merge: true), ); _createNewLevel(level: level, startingCash: startingCash); } Future<bool> reconnectToGameSession({required Person person}) async { currentGameSessionRef = await _findLatestGameSessionRef(person: person); if (currentGameSessionRef == null) { debugPrint("Could not find latest game session."); return false; } QuerySnapshot lastLevelSnapShot = await currentGameSessionRef! .collection('levelData') .orderBy('startedOn', descending: true) .limit(1) .get(); if (lastLevelSnapShot.docs.length != 1) { return false; } currentLevelDataRef = lastLevelSnapShot.docs.first.reference; return true; } Future<Person?> searchUserbyUIDInFirestore(String uid) async { // get snapshot of users from Firestore QuerySnapshot userQuerySnapshot = await _findUserInFirestoreByUID(uid: uid); if (userQuerySnapshot.docs.isEmpty) { debugPrint("No active user found. Checking uid lists..."); // get all documents from uidLists collection QuerySnapshot uidListsQuerySnapshot = await uidListsCollectionRef.get(); for (QueryDocumentSnapshot docSnap in uidListsQuerySnapshot.docs) { // get uidList from document List<dynamic> uidList = docSnap.get('uids'); // go through list that consists of users for (Map<String, dynamic> listEntry in uidList) { if (uid == listEntry['uid']) { // return the person connected to uid return Person( firstName: listEntry['firstName'], lastName: listEntry['lastName'], uid: listEntry['uid'], ); } } } return null; } else { // if the user is not found in Firestore debugPrint("User with uid $uid found."); QueryDocumentSnapshot docSnap = userQuerySnapshot.docs.first; String firstName = docSnap.get('firstName'); String lastName = docSnap.get('lastName'); return Person( firstName: firstName, lastName: lastName, uid: uid, ); } } Future<void> saveUserInFirestore(Person person) async { // get snapshot for specific user search QuerySnapshot userQuerySnapshot = await _findUserInFirestore(person: person); // save user if document does not exist yet if (userQuerySnapshot.docs.isEmpty) { debugPrint( 'save new user ${person.firstName} ${person.lastName} to firebase...'); Map<String, dynamic> userEntry = <String, dynamic>{ "firstName": person.firstName, "lastName": person.lastName, "uid": person.uid, "createdOn": DateTime.now(), }; await userCollectionRef.add(userEntry); } // otherwise do not save a new user else { debugPrint('User ${person.firstName} ${person.lastName} already exists'); await endCurrentGameSession(status: Status.abandoned, person: person); debugPrint('Deactivate last game session'); } } Future<void> startGameSession({ required Person person, required double startingCash, }) async { debugPrint("Starting new game session."); QuerySnapshot userQuerySnapshot = await _findUserInFirestore(person: person); if (userQuerySnapshot.docs.length != 1) { debugPrint("More than one user found."); } QueryDocumentSnapshot docSnap = userQuerySnapshot.docs.first; CollectionReference gameSessionRef = docSnap.reference.collection('gameSessions'); Map<String, dynamic> gameSessionContent = { 'startedOn': DateTime.now(), 'sessionStatus': Status.active.name, }; currentGameSessionRef = await gameSessionRef.add(gameSessionContent); _createNewLevel(level: 1, startingCash: startingCash); } Future<void> endCurrentGameSession( {required Status status, Person? person}) async { if (currentGameSessionRef == null) { debugPrint('No current game session could be found.'); if (person == null) { debugPrint('User info was not given.'); return; } bool reconnectSuccessful = await reconnectToGameSession(person: person); if (!reconnectSuccessful) { return; } } debugPrint("Closing current level with status ${status.name}."); await currentLevelDataRef!.set({ 'levelStatus': status.name, 'completedOn': DateTime.now(), }, SetOptions(merge: true)); debugPrint("Ending current game session with status ${status.name}."); await currentGameSessionRef!.set({ 'sessionStatus': status.name, 'completedOn': DateTime.now(), }, SetOptions(merge: true)); } void newLevelFirestore({ required int levelID, required double startingCash, }) async { currentLevelDataRef!.set( {'levelStatus': Status.won.name, 'completedOn': DateTime.now()}, SetOptions(merge: true), ); _createNewLevel(level: levelID + 1, startingCash: startingCash); } void advancePeriodFirestore({ required double newCashValue, required BuyDecision buyDecision, required Asset offeredAsset, }) async { DocumentSnapshot docSnap = await currentLevelDataRef!.get(); // add cash value to list List<double> cashArray = List.from(docSnap.get('cash')); cashArray.add(double.parse(newCashValue.toStringAsFixed(2))); // add buy decision to list List<String> decisionArray = List.from(docSnap.get('decisions')); decisionArray.add(buyDecision.name); // add cashROI to list List<Map<String, dynamic>> offeredAssets = List.from(docSnap.get('offeredAssets')); Map<String, dynamic> newMapFromAsset = { 'type': offeredAsset.type.name, 'price': offeredAsset.price, 'income': offeredAsset.income, 'riskLevel': offeredAsset.riskLevel, 'lifeExpectancy': offeredAsset.lifeExpectancy, }; offeredAssets.add(newMapFromAsset); docSnap.reference.set( { 'periods': FieldValue.increment(1), 'cash': cashArray, 'decisions': decisionArray, 'offeredAssets': offeredAssets, }, SetOptions( merge: true, )); } enum Status { active, won, lost, abandoned, } // enum LevelStatus { // active, // won, // lost, // }
0
mirrored_repositories/financial_literacy_game/lib
mirrored_repositories/financial_literacy_game/lib/l10n/lg_intl.dart
import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:intl/date_symbol_data_custom.dart' as date_symbol_data_custom; import 'package:intl/date_symbols.dart' as intl; import 'package:intl/intl.dart' as intl; /// A custom set of date patterns for the `lg` locale. /// /// These are not accurate and are just a clone of the date patterns for the /// `no` locale to demonstrate how one would write and use custom date patterns. // #docregion Date const lgLocaleDatePatterns = { 'd': 'd.', 'E': 'ccc', 'EEEE': 'cccc', 'LLL': 'LLL', // #enddocregion Date 'LLLL': 'LLLL', 'M': 'L.', 'Md': 'd.M.', 'MEd': 'EEE d.M.', 'MMM': 'LLL', 'MMMd': 'd. MMM', 'MMMEd': 'EEE d. MMM', 'MMMM': 'LLLL', 'MMMMd': 'd. MMMM', 'MMMMEEEEd': 'EEEE d. MMMM', 'QQQ': 'QQQ', 'QQQQ': 'QQQQ', 'y': 'y', 'yM': 'M.y', 'yMd': 'd.M.y', 'yMEd': 'EEE d.MM.y', 'yMMM': 'MMM y', 'yMMMd': 'd. MMM y', 'yMMMEd': 'EEE d. MMM y', 'yMMMM': 'MMMM y', 'yMMMMd': 'd. MMMM y', 'yMMMMEEEEd': 'EEEE d. MMMM y', 'yQQQ': 'QQQ y', 'yQQQQ': 'QQQQ y', 'H': 'HH', 'Hm': 'HH:mm', 'Hms': 'HH:mm:ss', 'j': 'HH', 'jm': 'HH:mm', 'jms': 'HH:mm:ss', 'jmv': 'HH:mm v', 'jmz': 'HH:mm z', 'jz': 'HH z', 'm': 'm', 'ms': 'mm:ss', 's': 's', 'v': 'v', 'z': 'z', 'zzzz': 'zzzz', 'ZZZZ': 'ZZZZ', }; /// A custom set of date symbols for the `lg` locale. /// /// These are not accurate and are just a clone of the date symbols for the /// `no` locale to demonstrate how one would write and use custom date symbols. // #docregion Date2 const lgDateSymbols = { 'NAME': 'lg', 'ERAS': <dynamic>[ 'f.Kr.', 'e.Kr.', ], // #enddocregion Date2 'ERANAMES': <dynamic>[ 'før Kristus', 'etter Kristus', ], 'NARROWMONTHS': <dynamic>[ 'J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D', ], 'STANDALONENARROWMONTHS': <dynamic>[ 'J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D', ], 'MONTHS': <dynamic>[ 'januar', 'februar', 'mars', 'april', 'mai', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'desember', ], 'STANDALONEMONTHS': <dynamic>[ 'januar', 'februar', 'mars', 'april', 'mai', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'desember', ], 'SHORTMONTHS': <dynamic>[ 'jan.', 'feb.', 'mar.', 'apr.', 'mai', 'jun.', 'jul.', 'aug.', 'sep.', 'okt.', 'nov.', 'des.', ], 'STANDALONESHORTMONTHS': <dynamic>[ 'jan', 'feb', 'mar', 'apr', 'mai', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'des', ], 'WEEKDAYS': <dynamic>[ 'søndag', 'mandag', 'tirsdag', 'onsdag', 'torsdag', 'fredag', 'lørdag', ], 'STANDALONEWEEKDAYS': <dynamic>[ 'søndag', 'mandag', 'tirsdag', 'onsdag', 'torsdag', 'fredag', 'lørdag', ], 'SHORTWEEKDAYS': <dynamic>[ 'søn.', 'man.', 'tir.', 'ons.', 'tor.', 'fre.', 'lør.', ], 'STANDALONESHORTWEEKDAYS': <dynamic>[ 'søn.', 'man.', 'tir.', 'ons.', 'tor.', 'fre.', 'lør.', ], 'NARROWWEEKDAYS': <dynamic>[ 'S', 'M', 'T', 'O', 'T', 'F', 'L', ], 'STANDALONENARROWWEEKDAYS': <dynamic>[ 'S', 'M', 'T', 'O', 'T', 'F', 'L', ], 'SHORTQUARTERS': <dynamic>[ 'K1', 'K2', 'K3', 'K4', ], 'QUARTERS': <dynamic>[ '1. kvartal', '2. kvartal', '3. kvartal', '4. kvartal', ], 'AMPMS': <dynamic>[ 'a.m.', 'p.m.', ], 'DATEFORMATS': <dynamic>[ 'EEEE d. MMMM y', 'd. MMMM y', 'd. MMM y', 'dd.MM.y', ], 'TIMEFORMATS': <dynamic>[ 'HH:mm:ss zzzz', 'HH:mm:ss z', 'HH:mm:ss', 'HH:mm', ], 'AVAILABLEFORMATS': null, 'FIRSTDAYOFWEEK': 0, 'WEEKENDRANGE': <dynamic>[ 5, 6, ], 'FIRSTWEEKCUTOFFDAY': 3, 'DATETIMEFORMATS': <dynamic>[ '{1} {0}', '{1} \'kl\'. {0}', '{1}, {0}', '{1}, {0}', ], }; // #docregion Delegate class _LgMaterialLocalizationsDelegate extends LocalizationsDelegate<MaterialLocalizations> { const _LgMaterialLocalizationsDelegate(); @override bool isSupported(Locale locale) => locale.languageCode == 'lg'; @override Future<MaterialLocalizations> load(Locale locale) async { final String localeName = intl.Intl.canonicalizedLocale(locale.toString()); // The locale (in this case `lg`) needs to be initialized into the custom // date symbols and patterns setup that Flutter uses. date_symbol_data_custom.initializeDateFormattingCustom( locale: localeName, patterns: lgLocaleDatePatterns, symbols: intl.DateSymbols.deserializeFromMap(lgDateSymbols), ); return SynchronousFuture<MaterialLocalizations>( LgMaterialLocalizations( localeName: localeName, // The `intl` library's NumberFormat class is generated from CLDR data // (see https://github.com/dart-lang/intl/blob/master/lib/number_symbols_data.dart). // Unfortunately, there is no way to use a locale that isn't defined in // this map and the only way to work around this is to use a listed // locale's NumberFormat symbols. So, here we use the number formats // for 'en_US' instead. decimalFormat: intl.NumberFormat('#,##0.###', 'en_US'), twoDigitZeroPaddedFormat: intl.NumberFormat('00', 'en_US'), // DateFormat here will use the symbols and patterns provided in the // `date_symbol_data_custom.initializeDateFormattingCustom` call above. // However, an alternative is to simply use a supported locale's // DateFormat symbols, similar to NumberFormat above. fullYearFormat: intl.DateFormat('y', localeName), compactDateFormat: intl.DateFormat('yMd', localeName), shortDateFormat: intl.DateFormat('yMMMd', localeName), mediumDateFormat: intl.DateFormat('EEE, MMM d', localeName), longDateFormat: intl.DateFormat('EEEE, MMMM d, y', localeName), yearMonthFormat: intl.DateFormat('MMMM y', localeName), shortMonthDayFormat: intl.DateFormat('MMM d'), ), ); } @override bool shouldReload(_LgMaterialLocalizationsDelegate old) => false; } // #enddocregion Delegate /// A custom set of localizations for the 'lg' locale. In this example, only /// the value for openAppDrawerTooltip was modified to use a custom message as /// an example. Everything else uses the American English (en_US) messages /// and formatting. class LgMaterialLocalizations extends GlobalMaterialLocalizations { const LgMaterialLocalizations({ super.localeName = 'lg', required super.fullYearFormat, required super.compactDateFormat, required super.shortDateFormat, required super.mediumDateFormat, required super.longDateFormat, required super.yearMonthFormat, required super.shortMonthDayFormat, required super.decimalFormat, required super.twoDigitZeroPaddedFormat, }); // #docregion Getters @override String get moreButtonTooltip => r'More'; @override String get aboutListTileTitleRaw => r'About $applicationName'; @override String get alertDialogLabel => r'Alert'; // #enddocregion Getters @override String get anteMeridiemAbbreviation => r'AM'; @override String get backButtonTooltip => r'Back'; @override String get cancelButtonLabel => r'CANCEL'; @override String get closeButtonLabel => r'CLOSE'; @override String get closeButtonTooltip => r'Close'; @override String get collapsedIconTapHint => r'Expand'; @override String get continueButtonLabel => r'CONTINUE'; @override String get copyButtonLabel => r'COPY'; @override String get cutButtonLabel => r'CUT'; @override String get deleteButtonTooltip => r'Delete'; @override String get dialogLabel => r'Dialog'; @override String get drawerLabel => r'Navigation menu'; @override String get expandedIconTapHint => r'Collapse'; @override String get firstPageTooltip => r'First page'; @override String get hideAccountsLabel => r'Hide accounts'; @override String get lastPageTooltip => r'Last page'; @override String get licensesPageTitle => r'Licenses'; @override String get modalBarrierDismissLabel => r'Dismiss'; @override String get nextMonthTooltip => r'Next month'; @override String get nextPageTooltip => r'Next page'; @override String get okButtonLabel => r'OK'; @override // A custom drawer tooltip message. String get openAppDrawerTooltip => r'Custom Navigation Menu Tooltip'; // #docregion Raw @override String get pageRowsInfoTitleRaw => r'$firstRow–$lastRow of $rowCount'; @override String get pageRowsInfoTitleApproximateRaw => r'$firstRow–$lastRow of about $rowCount'; // #enddocregion Raw @override String get pasteButtonLabel => r'PASTE'; @override String get popupMenuLabel => r'Popup menu'; @override String get menuBarMenuLabel => r'Menu Bar Label'; @override String get postMeridiemAbbreviation => r'PM'; @override String get previousMonthTooltip => r'Previous month'; @override String get previousPageTooltip => r'Previous page'; @override String get refreshIndicatorSemanticLabel => r'Refresh'; @override String? get remainingTextFieldCharacterCountFew => null; @override String? get remainingTextFieldCharacterCountMany => null; @override String get remainingTextFieldCharacterCountOne => r'1 character remaining'; @override String get remainingTextFieldCharacterCountOther => r'$remainingCount characters remaining'; @override String? get remainingTextFieldCharacterCountTwo => null; @override String get remainingTextFieldCharacterCountZero => r'No characters remaining'; @override String get reorderItemDown => r'Move down'; @override String get reorderItemLeft => r'Move left'; @override String get reorderItemRight => r'Move right'; @override String get reorderItemToEnd => r'Move to the end'; @override String get reorderItemToStart => r'Move to the start'; @override String get reorderItemUp => r'Move up'; @override String get rowsPerPageTitle => r'Rows per page:'; @override ScriptCategory get scriptCategory => ScriptCategory.englishLike; @override String get searchFieldLabel => r'Search'; @override String get selectAllButtonLabel => r'SELECT ALL'; @override String? get selectedRowCountTitleFew => null; @override String? get selectedRowCountTitleMany => null; @override String get selectedRowCountTitleOne => r'1 item selected'; @override String get selectedRowCountTitleOther => r'$selectedRowCount items selected'; @override String? get selectedRowCountTitleTwo => null; @override String get selectedRowCountTitleZero => r'No items selected'; @override String get showAccountsLabel => r'Show accounts'; @override String get showMenuTooltip => r'Show menu'; @override String get signedInLabel => r'Signed in'; @override String get tabLabelRaw => r'Tab $tabIndex of $tabCount'; @override TimeOfDayFormat get timeOfDayFormatRaw => TimeOfDayFormat.h_colon_mm_space_a; @override String get timePickerHourModeAnnouncement => r'Select hours'; @override String get timePickerMinuteModeAnnouncement => r'Select minutes'; @override String get viewLicensesButtonLabel => r'VIEW LICENSES'; @override List<String> get narrowWeekdays => const <String>['S', 'M', 'T', 'W', 'T', 'F', 'S']; @override int get firstDayOfWeekIndex => 0; static const LocalizationsDelegate<MaterialLocalizations> delegate = _LgMaterialLocalizationsDelegate(); @override String get calendarModeButtonLabel => r'Switch to calendar'; @override String get dateHelpText => r'mm/dd/yyyy'; @override String get dateInputLabel => r'Enter Date'; @override String get dateOutOfRangeLabel => r'Out of range.'; @override String get datePickerHelpText => r'SELECT DATE'; @override String get dateRangeEndDateSemanticLabelRaw => r'End date $fullDate'; @override String get dateRangeEndLabel => r'End Date'; @override String get dateRangePickerHelpText => 'SELECT RANGE'; @override String get dateRangeStartDateSemanticLabelRaw => 'Start date \$fullDate'; @override String get dateRangeStartLabel => 'Start Date'; @override String get dateSeparator => '/'; @override String get dialModeButtonLabel => 'Switch to dial picker mode'; @override String get inputDateModeButtonLabel => 'Switch to input'; @override String get inputTimeModeButtonLabel => 'Switch to text input mode'; @override String get invalidDateFormatLabel => 'Invalid format.'; @override String get invalidDateRangeLabel => 'Invalid range.'; @override String get invalidTimeLabel => 'Enter a valid time'; @override String get licensesPackageDetailTextOther => '\$licenseCount licenses'; @override String get saveButtonLabel => 'SAVE'; @override String get selectYearSemanticsLabel => 'Select year'; @override String get timePickerDialHelpText => 'SELECT TIME'; @override String get timePickerHourLabel => 'Hour'; @override String get timePickerInputHelpText => 'ENTER TIME'; @override String get timePickerMinuteLabel => 'Minute'; @override String get unspecifiedDate => 'Date'; @override String get unspecifiedDateRange => 'Date Range'; @override String get keyboardKeyAlt => throw UnimplementedError(); @override String get keyboardKeyAltGraph => throw UnimplementedError(); @override String get keyboardKeyBackspace => throw UnimplementedError(); @override String get keyboardKeyCapsLock => throw UnimplementedError(); @override String get keyboardKeyChannelDown => throw UnimplementedError(); @override String get keyboardKeyChannelUp => throw UnimplementedError(); @override String get keyboardKeyControl => throw UnimplementedError(); @override String get keyboardKeyDelete => throw UnimplementedError(); String get keyboardKeyEisu => throw UnimplementedError(); @override String get keyboardKeyEject => throw UnimplementedError(); @override String get keyboardKeyEnd => throw UnimplementedError(); @override String get keyboardKeyEscape => throw UnimplementedError(); @override String get keyboardKeyFn => throw UnimplementedError(); @override String get keyboardKeyHome => throw UnimplementedError(); @override String get keyboardKeyInsert => throw UnimplementedError(); @override String get keyboardKeyMeta => throw UnimplementedError(); @override String get keyboardKeyMetaMacOs => throw UnimplementedError(); @override String get keyboardKeyMetaWindows => throw UnimplementedError(); @override String get keyboardKeyNumLock => throw UnimplementedError(); @override String get keyboardKeyNumpad0 => throw UnimplementedError(); @override String get keyboardKeyNumpad1 => throw UnimplementedError(); @override String get keyboardKeyNumpad2 => throw UnimplementedError(); @override String get keyboardKeyNumpad3 => throw UnimplementedError(); @override String get keyboardKeyNumpad4 => throw UnimplementedError(); @override String get keyboardKeyNumpad5 => throw UnimplementedError(); @override String get keyboardKeyNumpad6 => throw UnimplementedError(); @override String get keyboardKeyNumpad7 => throw UnimplementedError(); @override String get keyboardKeyNumpad8 => throw UnimplementedError(); @override String get keyboardKeyNumpad9 => throw UnimplementedError(); @override String get keyboardKeyNumpadAdd => throw UnimplementedError(); @override String get keyboardKeyNumpadComma => throw UnimplementedError(); @override String get keyboardKeyNumpadDecimal => throw UnimplementedError(); @override String get keyboardKeyNumpadDivide => throw UnimplementedError(); @override String get keyboardKeyNumpadEnter => throw UnimplementedError(); @override String get keyboardKeyNumpadEqual => throw UnimplementedError(); @override String get keyboardKeyNumpadMultiply => throw UnimplementedError(); @override String get keyboardKeyNumpadParenLeft => throw UnimplementedError(); @override String get keyboardKeyNumpadParenRight => throw UnimplementedError(); @override String get keyboardKeyNumpadSubtract => throw UnimplementedError(); @override String get keyboardKeyPageDown => throw UnimplementedError(); @override String get keyboardKeyPageUp => throw UnimplementedError(); @override String get keyboardKeyPower => throw UnimplementedError(); @override String get keyboardKeyPowerOff => throw UnimplementedError(); @override String get keyboardKeyPrintScreen => throw UnimplementedError(); @override String get keyboardKeyScrollLock => throw UnimplementedError(); @override String get keyboardKeySelect => throw UnimplementedError(); @override String get keyboardKeySpace => throw UnimplementedError(); get scrimOnTapHintRaw => throw UnimplementedError(); get bottomSheetLabel => throw UnimplementedError(); get currentDateLabel => throw UnimplementedError(); get keyboardKeyShift => throw UnimplementedError(); get scrimLabel => throw UnimplementedError(); @override // TODO: implement collapsedHint String get collapsedHint => throw UnimplementedError(); @override // TODO: implement expandedHint String get expandedHint => throw UnimplementedError(); @override // TODO: implement expansionTileCollapsedHint String get expansionTileCollapsedHint => throw UnimplementedError(); @override // TODO: implement expansionTileCollapsedTapHint String get expansionTileCollapsedTapHint => throw UnimplementedError(); @override // TODO: implement expansionTileExpandedHint String get expansionTileExpandedHint => throw UnimplementedError(); @override // TODO: implement expansionTileExpandedTapHint String get expansionTileExpandedTapHint => throw UnimplementedError(); @override // TODO: implement lookUpButtonLabel String get lookUpButtonLabel => throw UnimplementedError(); @override // TODO: implement menuDismissLabel String get menuDismissLabel => throw UnimplementedError(); @override // TODO: implement scanTextButtonLabel String get scanTextButtonLabel => throw UnimplementedError(); @override // TODO: implement searchWebButtonLabel String get searchWebButtonLabel => throw UnimplementedError(); @override // TODO: implement shareButtonLabel String get shareButtonLabel => throw UnimplementedError(); }
0
mirrored_repositories/financial_literacy_game/lib
mirrored_repositories/financial_literacy_game/lib/l10n/l10n.dart
import 'dart:ui'; import 'package:flutter/material.dart'; import '../domain/utils/device_and_personal_data.dart'; class L10n { static const defaultLocale = Locale('en', 'GB'); static final all = [ defaultLocale, // const Locale('kn', 'IN'), // const Locale('lg'), const Locale('es', 'GT'), ]; static Future<Locale> getSystemLocale() async { // try to load saved locale from local memory Locale? loadedLocale = await loadLocaleFromLocal(); if (loadedLocale != null) { return loadedLocale; } // get default locale from system Locale systemLocale = window.locale; debugPrint( 'System locale: ${systemLocale.languageCode} / ${systemLocale.countryCode}'); // use system locale only if supported if (L10n.all.contains(systemLocale)) { debugPrint('System locale supported.'); return systemLocale; } // otherwise use default locale debugPrint('System locale not supported, using default locale:' '${defaultLocale.languageCode} / ${defaultLocale.countryCode}'); return L10n.defaultLocale; } static double getConversionRate(Locale locale) { switch (locale.languageCode) { case 'en': return 1; case 'lg': return 4000; case 'kn': return 80; default: return 1; } } }
0
mirrored_repositories/financial_literacy_game
mirrored_repositories/financial_literacy_game/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:financial_literacy_game/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/flutter_whatsapp_clone
mirrored_repositories/flutter_whatsapp_clone/lib/main.dart
import 'package:animated_splash_screen/animated_splash_screen.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:whatsapp_clone/Utils/routes.dart'; import 'Providers/theme_provider.dart'; import 'Screens/number_login.dart'; void main() { runApp(ChangeNotifierProvider<ThemeProvider>( create: (_) => ThemeProvider(), child: const MyApp(), )); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is the root of your application. @override Widget build(BuildContext context) { return Consumer<ThemeProvider>( builder: (context, state, child) => MaterialApp( debugShowCheckedModeBanner: false, title: 'Flutter Demo', theme: state.getTheme(), onGenerateRoute: Routes.generateRoute, home: AnimatedSplashScreen( nextScreen: const LoginScreen(), splash: Center( child: Container( alignment: Alignment.center, //TODO add dark mode check for splash screen color: Theme.of(context).splashColor, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const Spacer( flex: 1, ), Image.asset( 'lib/Assets/wpicon.png', width: 100, height: 100, ), const Spacer( flex: 1, ), Column( children: [ const Text( 'from', style: TextStyle(color: Colors.grey), ), Image.asset( 'lib/Assets/metalogo.png', width: 80, height: 50, ), ], ), ], ), ), ), duration: 2000, splashIconSize: 1000, ), ), ); } }
0
mirrored_repositories/flutter_whatsapp_clone/lib
mirrored_repositories/flutter_whatsapp_clone/lib/Providers/shared_preferences_helper.dart
import 'package:shared_preferences/shared_preferences.dart'; class SharedPreferencesHelper { static SharedPreferences? _instance; static SharedPreferences get instance => _instance!; static Future<SharedPreferences> init() async { _instance ??= await SharedPreferences.getInstance(); return _instance!; } }
0
mirrored_repositories/flutter_whatsapp_clone/lib
mirrored_repositories/flutter_whatsapp_clone/lib/Providers/theme_provider.dart
import 'package:flutter/material.dart'; import 'package:hexcolor/hexcolor.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:whatsapp_clone/Providers/shared_preferences_helper.dart'; class ThemeProvider with ChangeNotifier { SharedPreferences? sharedPreferences; final darkTheme = ThemeData( splashColor: Colors.black, // Text and Icon color secondaryHeaderColor: Colors.white, dividerTheme: DividerThemeData(color: Colors.grey), cardTheme: CardTheme(color: HexColor('#1c1c1e'), elevation: 0), //Text Button textButtonTheme: TextButtonThemeData( style: TextButton.styleFrom( primary: Colors.blue, )), // Scaffold Background scaffoldBackgroundColor: HexColor('#1B262C'), brightness: Brightness.dark, // Appbar appBarTheme: AppBarTheme( elevation: 0, shadowColor: Colors.grey, color: HexColor('#1B262C'), ), // Elevated Button elevatedButtonTheme: ElevatedButtonThemeData( style: ElevatedButton.styleFrom( primary: Colors.white, onPrimary: Colors.black, )), ); final lightTheme = ThemeData( splashColor: Colors.white, // Text color secondaryHeaderColor: Colors.black, // Divider color dividerTheme: DividerThemeData(color: Colors.grey), dividerColor: Colors.blue, cardTheme: CardTheme(color: Colors.white, elevation: 0), primaryColor: Colors.white, navigationBarTheme: NavigationBarThemeData(backgroundColor: HexColor('#EFEFF4')), appBarTheme: AppBarTheme( elevation: 0, color: HexColor('#EFEFF4'), titleTextStyle: TextStyle(color: Colors.black, fontSize: 16)), brightness: Brightness.light, iconTheme: const IconThemeData(color: Colors.black), scaffoldBackgroundColor: HexColor('#EFEFF4'), textButtonTheme: TextButtonThemeData( style: TextButton.styleFrom( primary: Colors.blue, )), colorScheme: ColorScheme.light(primary: Colors.black, secondary: Colors.black)); ThemeData? _themeData; ThemeData? getTheme() => _themeData; // methods for shared preferences void initSharedPreferences() async { // sharedPreferences = await SharedPreferences.getInstance(); await SharedPreferencesHelper.init(); sharedPreferences = SharedPreferencesHelper.instance; notifyListeners(); } static void saveData(String key, dynamic value) async { final prefs = await SharedPreferences.getInstance(); if (value is int) { prefs.setInt(key, value); } else if (value is String) { prefs.setString(key, value); } else if (value is bool) { prefs.setBool(key, value); } else { print("Invalid Type"); } } Future<dynamic> readData(String key) async { final prefs = await SharedPreferences.getInstance(); dynamic obj = prefs.get(key); print('obj : $obj'); return obj; } static Future<bool> deleteData(String key) async { final prefs = await SharedPreferences.getInstance(); return prefs.remove(key); } ThemeProvider() { readData('themeMode').then((value) { print('Selected Theme Data from Local Storage : ${value.toString()}'); var themeMode = value ?? 'light'; if (themeMode == 'light') { _themeData = lightTheme; } else { print('setting dark theme'); _themeData = darkTheme; } notifyListeners(); }); } void setDarkMode() async { _themeData = darkTheme; saveData('themeMode', 'dark'); notifyListeners(); } void setLightMode() async { _themeData = lightTheme; saveData('themeMode', 'light'); notifyListeners(); } }
0
mirrored_repositories/flutter_whatsapp_clone/lib
mirrored_repositories/flutter_whatsapp_clone/lib/Utils/routes.dart
import 'package:flutter/material.dart'; import 'package:whatsapp_clone/Screens/number_login.dart'; import '../Screens/home_page.dart'; class Routes { static const loginRoute = '/login'; static const homePageRoute = '/home'; static Route<dynamic> generateRoute(RouteSettings settings) { switch (settings.name) { case '/login': return MaterialPageRoute(builder: (_) => const LoginScreen()); case '/home': return MaterialPageRoute(builder: (_) => const HomePage()); default: return MaterialPageRoute( builder: (_) => Scaffold( body: Center( child: Text('No route defined for ${settings.name}'), ), )); } } }
0
mirrored_repositories/flutter_whatsapp_clone/lib
mirrored_repositories/flutter_whatsapp_clone/lib/Screens/home_page.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:hexcolor/hexcolor.dart'; import 'package:whatsapp_clone/Screens/call_screen.dart'; import 'package:whatsapp_clone/Screens/camera_screen.dart'; import 'package:whatsapp_clone/Screens/chatscreen.dart'; import 'package:whatsapp_clone/Screens/settings_screen.dart'; import 'package:whatsapp_clone/Screens/status_screen.dart'; class HomePage extends StatefulWidget { const HomePage({Key? key}) : super(key: key); @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { static const List<Widget> _pages = <Widget>[ StatusScreen(), CallScreen(), CameraScreen(), ChatScreen(), SettingsScreen(), ]; int selectedIndex = 3; @override Widget build(BuildContext context) { return Scaffold( bottomNavigationBar: BottomNavigationBar( type: BottomNavigationBarType.fixed, landscapeLayout: BottomNavigationBarLandscapeLayout.centered, currentIndex: selectedIndex, onTap: _onItemTapped, selectedItemColor: Colors.blue, items: [ BottomNavigationBarItem( icon: SvgPicture.asset( 'lib/Assets/statusicon.svg', height: 30, color: selectedIndex == 0 ? Colors.blue : Colors.grey, ), label: 'Status'), BottomNavigationBarItem( icon: selectedIndex == 1 ? SvgPicture.asset( 'lib/Assets/phoneselected.svg', height: 30, ) : SvgPicture.asset( 'lib/Assets/phoneicon.svg', height: 30, color: HexColor('#979797'), ), label: 'Calls'), BottomNavigationBarItem( icon: SvgPicture.asset( 'lib/Assets/cameraicon.svg', height: 30, color: HexColor('#979797'), ), label: 'Camera'), BottomNavigationBarItem( icon: selectedIndex == 3 ? SvgPicture.asset( 'lib/Assets/chatselected.svg', height: 30, ) : SvgPicture.asset( 'lib/Assets/chaticon.svg', height: 30, color: HexColor('#979797'), ), label: 'Chat'), BottomNavigationBarItem( icon: selectedIndex == 4 ? SvgPicture.asset( 'lib/Assets/settingsselected.svg', height: 30, ) : SvgPicture.asset( 'lib/Assets/settingsicon.svg', height: 30, color: HexColor('#979797'), ), label: 'Settings'), ], ), body: _pages[selectedIndex], ); } void _onItemTapped(int index) { setState(() { selectedIndex = index; }); } }
0
mirrored_repositories/flutter_whatsapp_clone/lib
mirrored_repositories/flutter_whatsapp_clone/lib/Screens/number_login.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class LoginScreen extends StatefulWidget { const LoginScreen({Key? key}) : super(key: key); @override _LoginScreenState createState() => _LoginScreenState(); } class _LoginScreenState extends State<LoginScreen> { var numbers = const <Widget>[ Text('+90'), Text('+61'), Text('+16'), Text('+645'), Text('+86'), Text('+786'), ]; String? selectedValue; var numberController = TextEditingController(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Enter Your Phone Number'), centerTitle: true, elevation: 2, shadowColor: Colors.white, actions: [ TextButton( onPressed: () { Navigator.pushReplacementNamed(context, '/home'); }, //numberController.text.contains('') ? null : () {}, child: const Text('Done')) ], ), body: Column( children: [ const Padding( padding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 20), child: Text( 'WhatsApp will send an SMS message to verify your phone number (carrier changes may apply).', style: TextStyle(fontWeight: FontWeight.w600, fontSize: 15), textAlign: TextAlign.center, ), ), // TODO Buraya numara kontrolü ekle ve done butonunun aktifleşme olayına bak Padding( padding: EdgeInsets.symmetric(horizontal: 10), child: TextField( keyboardType: TextInputType.number, controller: numberController, decoration: InputDecoration(hintText: 'Your phone number'), textAlign: TextAlign.center, ), ) //ElevatedButton(onPressed: () {}, child: const Text('Select Number')), ], ), ); } }
0
mirrored_repositories/flutter_whatsapp_clone/lib
mirrored_repositories/flutter_whatsapp_clone/lib/Screens/status_screen.dart
import 'package:flutter/material.dart'; import 'package:whatsapp_clone/Widgets/Status%20Page/mystatus.dart'; class StatusScreen extends StatelessWidget { const StatusScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( toolbarHeight: 40, leadingWidth: 100, leading: TextButton( child: Text( 'Privacy', style: TextStyle(fontSize: 18), ), onPressed: () {}, ), ), body: Column( crossAxisAlignment: CrossAxisAlignment.start, children: const [ Padding( padding: EdgeInsets.only(left: 15, top: 5), child: Text( 'Status', style: TextStyle(fontSize: 40, fontWeight: FontWeight.bold), ), ), MyStatus(), Padding( padding: EdgeInsets.only(top: 20.0), child: Card( child: Center( child: Padding( padding: EdgeInsets.only(top: 20.0, bottom: 20.0), child: Text( 'No recent updates to show right now', ), )), ), ) ], ), ); } }
0
mirrored_repositories/flutter_whatsapp_clone/lib
mirrored_repositories/flutter_whatsapp_clone/lib/Screens/call_screen.dart
import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; import 'package:hexcolor/hexcolor.dart'; import 'package:provider/provider.dart'; import 'package:toggle_switch/toggle_switch.dart'; import 'package:whatsapp_clone/Widgets/Call%20Screen/call_list.dart'; import '../Providers/theme_provider.dart'; class CallScreen extends StatelessWidget { const CallScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: ToggleSwitch( customWidths: [100, 100], minHeight: 37, initialLabelIndex: 0, cornerRadius: 10, borderWidth: 1.5, activeBgColor: [HexColor('#007AFF')], totalSwitches: 2, labels: ['All', 'Missed'], customTextStyles: [ TextStyle(color: Colors.white, fontSize: 16), TextStyle(color: Colors.white, fontSize: 16) ], onToggle: (index) { print('$index selected!'); }, ), toolbarHeight: 50, leading: TextButton( child: const Text( 'Edit', style: TextStyle(fontSize: 18), ), onPressed: () {}, ), actions: [ Consumer<ThemeProvider>(builder: (context, theme, child) { return IconButton( onPressed: () { ThemeProvider().readData('themeMode').then((value) { value == 'light' ? theme.setDarkMode() : theme.setLightMode(); }); }, icon: SvgPicture.asset('lib/Assets/callicon.svg'), color: Colors.black, ); }) ]), body: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Padding( padding: EdgeInsets.only(left: 10), child: Text( 'Calls', style: TextStyle(fontSize: 40, fontWeight: FontWeight.bold), ), ), Column( children: const [ Divider( color: Colors.grey, thickness: 0.5, ) ], ), CallList(), ], ), ); } }
0
mirrored_repositories/flutter_whatsapp_clone/lib
mirrored_repositories/flutter_whatsapp_clone/lib/Screens/chatscreen.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; import '../Widgets/ChatScreen/messageslist.dart'; class ChatScreen extends StatelessWidget { const ChatScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( toolbarHeight: 50, leading: TextButton( child: Text( 'Edit', style: TextStyle(fontSize: 18), ), onPressed: () {}, ), actions: [ IconButton( onPressed: () {}, icon: SvgPicture.asset('lib/Assets/editicon.svg'), color: Colors.black, ), ]), body: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Padding( padding: EdgeInsets.only(left: 10), child: Text( 'Chats', style: TextStyle(fontSize: 40, fontWeight: FontWeight.bold), ), ), Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.only(left: 5.0), child: TextButton( child: const Text( 'Broadcast Lists', style: TextStyle(fontSize: 17), ), onPressed: () {}, ), ), Padding( padding: const EdgeInsets.only(left: 150.0), child: TextButton( child: const Text( 'New Group', style: TextStyle(fontSize: 17), ), onPressed: () {}, ), ), ], ), const Divider( color: Colors.grey, thickness: 0.5, ) ], ), MessagesList(), ], ), ); } }
0
mirrored_repositories/flutter_whatsapp_clone/lib
mirrored_repositories/flutter_whatsapp_clone/lib/Screens/camera_screen.dart
import 'package:flutter/material.dart'; class CameraScreen extends StatelessWidget { const CameraScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold(); } }
0
mirrored_repositories/flutter_whatsapp_clone/lib
mirrored_repositories/flutter_whatsapp_clone/lib/Screens/settings_screen.dart
import 'package:flutter/material.dart'; import 'package:whatsapp_clone/Widgets/Settings%20Screen/settings_title.dart'; import '../Widgets/Settings Screen/setting_card.dart'; class SettingsScreen extends StatelessWidget { const SettingsScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( body: Padding( padding: const EdgeInsets.only(top: 50.0), child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ const Padding( padding: EdgeInsets.only(left: 10.0), child: Text( 'Settings', style: TextStyle(fontSize: 30, fontWeight: FontWeight.bold), ), ), SettingsTitle(), Padding( padding: const EdgeInsets.only(top: 30.0), child: Container( color: Theme.of(context).primaryColor, child: Column( children: [ SettingCard( title: 'Starred Messages', iconsvg: 'lib/Assets/starredicon.svg', ), SettingCard( title: 'WhatsApp Web/Desktop', iconsvg: 'lib/Assets/wpdesktopicon.svg', ), ], )), ), Padding( padding: const EdgeInsets.only(top: 30.0), child: Container( color: Theme.of(context).primaryColor, child: Column( children: [ SettingCard( title: 'Account', iconsvg: 'lib/Assets/accounticon.svg', ), SettingCard( title: 'Chats', iconsvg: 'lib/Assets/chatsicon.svg', ), SettingCard( title: 'Notifications', iconsvg: 'lib/Assets/notificons.svg', ), SettingCard( title: 'Data and Storage Usage', iconsvg: 'lib/Assets/dataicon.svg', ), ], )), ), Padding( padding: const EdgeInsets.only(top: 30.0), child: Container( color: Theme.of(context).primaryColor, child: Column( children: [ SettingCard( title: 'Help', iconsvg: 'lib/Assets/helpicon.svg', ), SettingCard( title: 'Tell a Friend', iconsvg: 'lib/Assets/friendicon.svg', ), ], )), ), ], ), ), ); } }
0
mirrored_repositories/flutter_whatsapp_clone/lib/Widgets
mirrored_repositories/flutter_whatsapp_clone/lib/Widgets/ChatScreen/messageslist.dart
import 'package:flutter/material.dart'; import 'package:whatsapp_clone/Widgets/ChatScreen/message_card.dart'; class MessagesList extends StatelessWidget { const MessagesList({Key? key}) : super(key: key); @override Widget build(BuildContext context) { var screenSize = MediaQuery.of(context).size; return SizedBox( height: screenSize.height / 1.51, child: ListView( children: [ MessageCard( name: 'Yılmaz Yağız Dokumacı', message: 'PLUS ULTRA!!', time: '13.31', profilepic: 'lib/Assets/yagophoto.jpg', ), MessageCard( name: 'Oğuzhan İnce', message: 'Abi bizim şirkete gelsene', time: '00.31', profilepic: 'lib/Assets/oguzprofile.jpeg', ), MessageCard( name: 'Ecem Bostancıoğlu', message: 'We are dream team', time: '14.45', profilepic: 'lib/Assets/ecemprofile.jpeg', ), MessageCard( name: 'Pala', message: 'Sadece ölüler görür..', time: '19.32', profilepic: 'lib/Assets/pala.jpg', ), MessageCard( name: 'Elon Musk', message: 'Yağız abi kripto para tavsiyesi var mı?', time: '20.08', profilepic: 'lib/Assets/elonmusk.jpg', ), MessageCard( name: 'Michael Jordan', message: 'Ben bile 1v1\'de seni yenemem..', time: '20.08', profilepic: 'lib/Assets/jordan.jpg', ), MessageCard( name: 'Kobe Bryant', message: 'Rest in Peace..', time: '08.24', profilepic: 'lib/Assets/kobebryant.jpg', ), ], ), ); } }
0
mirrored_repositories/flutter_whatsapp_clone/lib/Widgets
mirrored_repositories/flutter_whatsapp_clone/lib/Widgets/ChatScreen/message_card.dart
import 'package:flutter/material.dart'; import 'package:flutter_slidable/flutter_slidable.dart'; import 'package:hexcolor/hexcolor.dart'; class MessageCard extends StatelessWidget { MessageCard( {Key? key, required this.name, required this.time, required this.message, required this.profilepic}) : super(key: key); String name; String time; String message; String profilepic; @override Widget build(BuildContext context) { return Row( children: [ Expanded( child: Slidable( endActionPane: ActionPane( motion: ScrollMotion(), children: [ SlidableAction( backgroundColor: HexColor('#C6C6CC'), foregroundColor: Colors.white, label: 'More', icon: Icons.more_horiz, onPressed: (context) {}), SlidableAction( backgroundColor: HexColor('#3E70A7'), label: 'Archive', icon: Icons.archive, onPressed: (context) {}), ], ), child: ListTile( title: Text(name), subtitle: Text(message), minVerticalPadding: 15, leading: CircleAvatar( radius: 30, backgroundImage: AssetImage( profilepic, ), ), trailing: Column( mainAxisAlignment: MainAxisAlignment.center, children: [Text(time)], ), ), ), ) ], ); ; } }
0
mirrored_repositories/flutter_whatsapp_clone/lib/Widgets
mirrored_repositories/flutter_whatsapp_clone/lib/Widgets/Settings Screen/settings_title.dart
import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; import 'package:provider/provider.dart'; import 'package:whatsapp_clone/Providers/theme_provider.dart'; class SettingsTitle extends StatelessWidget { const SettingsTitle({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.only(top: 20.0), child: SizedBox( width: MediaQuery.of(context).size.width / 1, child: Card( child: Row( children: [ const Padding( padding: EdgeInsets.only(left: 20.0, top: 10, bottom: 10), child: CircleAvatar( radius: 35, backgroundImage: AssetImage( 'lib/Assets/yagophoto.jpg', ), ), ), Padding( padding: const EdgeInsets.only(left: 5.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: const [ Text( 'Yılmaz Yağız', style: TextStyle(fontWeight: FontWeight.bold), ), Padding( padding: EdgeInsets.only(top: 5.0), child: Text( 'www.yagizdokumaci.com', style: TextStyle(color: Colors.grey), ), ) ], ), ), Padding( padding: const EdgeInsets.only(left: 30.0), child: GestureDetector( onTap: () {}, child: SvgPicture.asset('lib/Assets/camerabuttonicon.svg')), ), Padding( padding: const EdgeInsets.only(left: 30.0), child: Consumer<ThemeProvider>(builder: (context, theme, child) { return GestureDetector( onTap: () { ThemeProvider().readData('themeMode').then((value) { value == 'light' ? theme.setDarkMode() : theme.setLightMode(); }); }, child: SvgPicture.asset( 'lib/Assets/darkmodeicon.svg', width: 20, color: Theme.of(context).secondaryHeaderColor, )); }), ), ], ), ), ), ); } }
0
mirrored_repositories/flutter_whatsapp_clone/lib/Widgets
mirrored_repositories/flutter_whatsapp_clone/lib/Widgets/Settings Screen/setting_card.dart
import 'package:cupertino_list_tile/cupertino_list_tile.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; class SettingCard extends StatelessWidget { SettingCard({Key? key, required this.iconsvg, required this.title}) : super(key: key); String title; String iconsvg; @override Widget build(BuildContext context) { return CupertinoListTile( title: Text( title, style: TextStyle(color: Theme.of(context).secondaryHeaderColor), ), leading: SvgPicture.asset(iconsvg), ); } }
0
mirrored_repositories/flutter_whatsapp_clone/lib/Widgets
mirrored_repositories/flutter_whatsapp_clone/lib/Widgets/Status Page/mystatus.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; class MyStatus extends StatefulWidget { const MyStatus({Key? key}) : super(key: key); @override State<MyStatus> createState() => _MyStatusState(); } class _MyStatusState extends State<MyStatus> { var themeMode; @override void initState() { super.initState(); } @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.only(top: 40.0), child: Card( child: Row( children: [ const Padding( padding: EdgeInsets.only(left: 20.0, top: 10, bottom: 10), child: CircleAvatar( radius: 35, backgroundImage: AssetImage( 'lib/Assets/yagophoto.jpg', ), ), ), Padding( padding: const EdgeInsets.only(left: 10.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: const [ Text( 'My Status', style: TextStyle(fontWeight: FontWeight.bold), ), Padding( padding: EdgeInsets.only(top: 5.0), child: Text( 'Add to my status', style: TextStyle(color: Colors.grey), ), ) ], ), ), Padding( padding: const EdgeInsets.only(left: 60.0, right: 30), child: GestureDetector( onTap: () {}, child: SvgPicture.asset('lib/Assets/camerabuttonicon.svg')), ), GestureDetector( onTap: () {}, child: SvgPicture.asset('lib/Assets/penbuttonicon.svg')), ], ), ), ); } }
0
mirrored_repositories/flutter_whatsapp_clone/lib/Widgets
mirrored_repositories/flutter_whatsapp_clone/lib/Widgets/Call Screen/call_card.dart
import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; class CallCard extends StatelessWidget { CallCard( {Key? key, required this.name, required this.counter, required this.info, required this.time, required this.imageasset}) : super(key: key); String name; int counter; String info; String time; String imageasset; @override Widget build(BuildContext context) { return Row( children: [ Expanded( child: ListTile( title: Text( '$name ${counter == 0 ? '' : '($counter)'}', style: TextStyle(fontSize: 14), ), subtitle: Row( children: [ SvgPicture.asset('lib/Assets/littlephoneicon.svg'), Padding( padding: EdgeInsets.only(left: 10.0), child: Text(info), ) ], ), minVerticalPadding: 15, leading: CircleAvatar( radius: 30, backgroundImage: AssetImage( imageasset, ), ), trailing: SizedBox( width: MediaQuery.of(context).size.width / 3.83, child: Row( children: [ Text( time, style: TextStyle(fontSize: 12.5), ), IconButton( onPressed: () {}, icon: SvgPicture.asset('lib/Assets/infoicon.svg')) ], ), ), )) ], ); } }
0
mirrored_repositories/flutter_whatsapp_clone/lib/Widgets
mirrored_repositories/flutter_whatsapp_clone/lib/Widgets/Call Screen/call_list.dart
import 'package:flutter/material.dart'; import 'package:whatsapp_clone/Widgets/Call%20Screen/call_card.dart'; class CallList extends StatelessWidget { const CallList({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return SizedBox( height: MediaQuery.of(context).size.height / 1.4, child: ListView( children: [ CallCard( name: 'Yılmaz Yağız Dokumacı', counter: 2, info: 'Missed', time: '12.41', imageasset: 'lib/Assets/yagophoto.jpg'), CallCard( name: 'Oğuzhan İnce', counter: 31, info: 'Outgoing', time: 'Yesterday', imageasset: 'lib/Assets/oguzprofile.jpeg'), CallCard( name: 'Ecem Bostancıoğlu', counter: 0, info: 'Missed', time: '11.30', imageasset: 'lib/Assets/ecemprofile.jpeg'), CallCard( name: 'Elon Musk', counter: 90, info: 'Incoming', time: '00.20', imageasset: 'lib/Assets/elonmusk.jpg'), CallCard( name: 'Kobe Bryant', counter: 0, info: 'Missed', time: '08.24', imageasset: 'lib/Assets/kobebryant.jpg'), CallCard( name: 'Michael Jordan', counter: 4, info: 'Outgoing', time: '17.32', imageasset: 'lib/Assets/jordan.jpg'), CallCard( name: 'Dash', counter: 10, info: 'Missed', time: '20.18', imageasset: 'lib/Assets/dartdash.jpg'), CallCard( name: 'Pala', counter: 999, info: 'Incoming', time: '12.41', imageasset: 'lib/Assets/pala.jpg'), ], ), ); } }
0
mirrored_repositories/flutter_whatsapp_clone
mirrored_repositories/flutter_whatsapp_clone/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:whatsapp_clone/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/to_do_app
mirrored_repositories/to_do_app/lib/firebase.dart
import 'dart:math'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:shared_preferences/shared_preferences.dart'; class dataFirebase { static RegisterUser(String email, String username) async { CollectionReference users = FirebaseFirestore.instance.collection('users'); await users.add({ 'email': email, // John Doe 'username': username, // Stokes and Sons }).catchError((error) => print("Failed to add user: $error")); } static getTaks() { CollectionReference task = FirebaseFirestore.instance.collection('task'); } static getuser() async { final prefs = await SharedPreferences.getInstance(); FirebaseAuth auth = FirebaseAuth.instance; Stream _stateChange = auth.authStateChanges(); _stateChange.listen((event) async { await prefs.setString('email', event.email); print(event); }); } static Future<String?> getemail() async { final prefs = await SharedPreferences.getInstance(); final String? email = prefs.getString('email'); return email; } static getusername() async { final prefs = await SharedPreferences.getInstance(); final String? username = await prefs.getString('username'); print(username); return username; } static Future<List> getAllData() async { List productModelList = []; var data = await FirebaseFirestore.instance.collection("task").get(); final allData = data.docs.map((doc) => productModelList.add(doc.data())).toList(); return productModelList; } }
0
mirrored_repositories/to_do_app
mirrored_repositories/to_do_app/lib/main.dart
import 'dart:async'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:get/get_navigation/src/root/get_material_app.dart'; import 'package:to_do_app/Screen/homepage.dart'; import 'package:to_do_app/Screen/login.dart'; import 'package:to_do_app/Widget/bottombar.dart'; import 'package:to_do_app/utils/app_style.dart'; import 'Screen/register.dart'; void main() async { //to make sure that firebase has been Initialized WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(MyApp()); } MaterialColor buildMaterialColor(Color color) { List strengths = <double>[.05]; Map<int, Color> swatch = {}; final int r = color.red, g = color.green, b = color.blue; for (int i = 1; i < 10; i++) { strengths.add(0.1 * i); } strengths.forEach((strength) { final double ds = 0.5 - strength; swatch[(strength * 1000).round()] = Color.fromRGBO( r + ((ds < 0 ? r : (255 - r)) * ds).round(), g + ((ds < 0 ? g : (255 - g)) * ds).round(), b + ((ds < 0 ? b : (255 - b)) * ds).round(), 1, ); }); return MaterialColor(color.value, swatch); } class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { late StreamSubscription<User?> user; @override void initState() { super.initState(); user = FirebaseAuth.instance.authStateChanges().listen((user) { if (user == null) { print('User is currently signed out!'); } else { print('User is signed in!'); } }); } @override void dispose() { user.cancel(); super.dispose(); } @override Widget build(BuildContext context) { return GetMaterialApp( debugShowCheckedModeBanner: false, title: 'To do app', theme: ThemeData( primarySwatch: buildMaterialColor(const Color(0xFF064F60)), ), home: FirebaseAuth.instance.currentUser == null ? Login() : BottomBar(), routes: { 'login': (context) => Login(), 'register': (context) => Register(), 'homepage': (context) => HomePage(), }, ); } }
0
mirrored_repositories/to_do_app/lib
mirrored_repositories/to_do_app/lib/Screen/register.dart
import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:to_do_app/Screen/homepage.dart'; import 'package:to_do_app/Screen/login.dart'; import 'package:to_do_app/Widget/bottombar.dart'; import '../Model/user.dart'; import '../Widget/Texffieldform.dart'; import '../Widget/button.dart'; import '../utils/app_style.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import '../firebase.dart'; class Register extends StatefulWidget { const Register({super.key}); @override State<Register> createState() => _RegisterState(); } class _RegisterState extends State<Register> { final TextEditingController _email = TextEditingController(); final TextEditingController _username = TextEditingController(); final TextEditingController _password = TextEditingController(); bool loading = false; String? error; final _formKey = GlobalKey<FormState>(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: SingleChildScrollView( child: Form( key: _formKey, child: Column( mainAxisAlignment: MainAxisAlignment.start, children: [ Image.asset( 'asset/images/register.jpg', height: 300, fit: BoxFit.cover, ), Text( 'Register', style: style.textStyle, ), Container( margin: const EdgeInsets.only(right: 10, left: 10), padding: const EdgeInsets.all(10), child: TextFormField( validator: (value) { if (value!.isEmpty) { return 'E-mail is required'; } else if (value.isEmail == false) { return 'Please Enter an E-mail'; } return null; }, controller: _email, keyboardType: TextInputType.emailAddress, decoration: const InputDecoration( suffixIcon: Icon(Icons.email_outlined), hintText: 'Enter your Email', border: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(15.0))), ), ), ), Container( margin: const EdgeInsets.only(right: 10, left: 10), padding: const EdgeInsets.all(10), child: TextFormField( validator: (value) { if (value!.isEmpty) { return 'UserName is required'; } return null; }, controller: _username, decoration: const InputDecoration( suffixIcon: Icon(Icons.person_outlined), hintText: 'Enter your UserName', border: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(15.0))), ), ), ), Container( margin: const EdgeInsets.only(right: 10, left: 10), padding: const EdgeInsets.all(10), child: TextFormField( obscureText: true, validator: (value) { if (value!.isEmpty) { return 'Password is required'; } else if (value.length < 8) { return 'Password must be at least 8 chr '; } return null; }, controller: _password, keyboardType: TextInputType.emailAddress, decoration: const InputDecoration( suffixIcon: Icon(Icons.lock), hintText: 'Enter your password', border: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(15.0))), ), ), ), Container( width: double.infinity, height: 50, margin: const EdgeInsets.only(left: 20, right: 20), child: ElevatedButton( style: ButtonStyle( fixedSize: MaterialStateProperty.all( const Size.fromWidth(double.infinity), ), padding: MaterialStateProperty.all( const EdgeInsets.all(10), ), shape: MaterialStateProperty.all( RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), ), ), onPressed: () async { // if (_formKey.currentState!.validate()) { // FirebaseAuth.instance // .createUserWithEmailAndPassword( // email: _email.text, password: _password.text) // .then((value) { // //loading spinier // Get.off(() => const BottomBar()); // }).onError((error, stackTrace) { // ScaffoldMessenger.of(context).showSnackBar( // SnackBar( // backgroundColor: Colors.white, // behavior: SnackBarBehavior.floating, // elevation: 0, // content: Container( // margin: const EdgeInsets.all(10), // padding: const EdgeInsets.all(10), // decoration: const BoxDecoration( // color: Colors.redAccent, // borderRadius: // BorderRadius.all(Radius.circular(10)), // ), // height: 80, // child: Text(error.toString() == // '[firebase_auth/email-already-in-use] The email address is already in use by another account.' // ? ' The email address is already used, please enter other E-mail.' // : 'Something went wrong, please try agin.'), // ), // ), // ); // ; // }); // } if (_formKey.currentState!.validate()) { try { await FirebaseAuth.instance .createUserWithEmailAndPassword( email: _email.text, password: _password.text); await dataFirebase.RegisterUser( _email.text, _username.text); dataFirebase.getuser(); Get.off(() => const BottomBar()); } on FirebaseAuthException catch (e) { if (e.code == 'weak-password') { error = 'The password is weak'; } else if (e.code == 'email-already-in-use') { error = 'The email address is already used, please enter other E-mail'; } ScaffoldMessenger.of(context).showSnackBar( SnackBar( backgroundColor: Colors.white, behavior: SnackBarBehavior.floating, elevation: 0, content: Container( margin: const EdgeInsets.all(10), padding: const EdgeInsets.all(10), decoration: const BoxDecoration( color: Colors.redAccent, borderRadius: BorderRadius.all(Radius.circular(10)), ), height: 80, child: Text(error!), ), ), ); } catch (e) { print(e); } } }, child: const Text( 'Register', style: TextStyle( fontSize: 20, ), ), ), ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text('Already have an account,'), TextButton( onPressed: () { Get.off(() => const Login()); }, child: Text( 'Login from here', style: TextStyle( color: style.lightgreen, ), ), ), ], ), ], ), ), ), ); } }
0
mirrored_repositories/to_do_app/lib
mirrored_repositories/to_do_app/lib/Screen/profile.dart
import 'package:flutter/material.dart'; import '../utils/app_style.dart'; class ProfileManagement extends StatefulWidget { const ProfileManagement({super.key}); @override State<ProfileManagement> createState() => _ProfileManagementState(); } class _ProfileManagementState extends State<ProfileManagement> { @override Widget build(BuildContext context) { var size = MediaQuery.of(context).size; return Column( children: [ Container( height: size.height * 0.18, width: double.infinity, decoration: BoxDecoration( color: style.green, borderRadius: BorderRadius.circular(20), ), child: Center( child: Text( 'Seeings', style: style.textStyleWhite, ), ), ), ], ); } }
0
mirrored_repositories/to_do_app/lib
mirrored_repositories/to_do_app/lib/Screen/add.dart
import 'package:firebase_database/firebase_database.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:intl/intl.dart'; import 'package:to_do_app/utils/app_style.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:awesome_dialog/awesome_dialog.dart'; import '../Widget/bottombar.dart'; class AddToDo extends StatefulWidget { const AddToDo({super.key}); @override State<AddToDo> createState() => _AddToDoState(); } class _AddToDoState extends State<AddToDo> { final _formKey = GlobalKey<FormState>(); //title, subtitle, due date, proirity, notfication before due date, final _title = TextEditingController(); final _subtitle = TextEditingController(); final _date = TextEditingController(); String? _propriety; String Selected = 'At the same day'; List<String> notification = [ 'At the same day', 'A day before ', 'Two days before', ]; //default value final String status = 'New'; late DatabaseReference dbref; @override void dispose() { _title.dispose(); _subtitle.dispose(); _date.dispose(); //childe is name of database dbref = FirebaseDatabase.instance.ref().child('Tasks'); super.dispose(); } CollectionReference task = FirebaseFirestore.instance.collection('task'); Future<void> addtask(String title, String subtitle, String date, String not, String propriety) { // Calling the collection to add a new user return task //adding to firebase collection .add({ //Data added in the form of a dictionary into the document. 'title': title, 'subtitle': subtitle, 'date': date, 'propriety': propriety, 'not': not }).then((value) { AwesomeDialog( context: context, animType: AnimType.scale, dialogType: DialogType.success, body: const Center( child: Text( 'Task has been added successfully. ', style: TextStyle(fontStyle: FontStyle.italic), ), ), btnOkOnPress: () { Get.off(() => const BottomBar()); }, ).show(); }).catchError((error) { AwesomeDialog( context: context, animType: AnimType.scale, dialogType: DialogType.error, body: const Center( child: Text( 'Something went wrong, please try agin', style: TextStyle(fontStyle: FontStyle.italic), ), ), btnOkOnPress: () {}, ).show(); }); } bool submit = false; @override Widget build(BuildContext context) { var size = MediaQuery.of(context).size; return Form( key: _formKey, child: SingleChildScrollView( child: Column( mainAxisAlignment: MainAxisAlignment.start, children: [ Container( height: size.height * 0.18, width: double.infinity, decoration: BoxDecoration( color: style.green, borderRadius: BorderRadius.circular(20), ), child: Center( child: Text( 'Add new Task', style: style.textStyleWhite, ), ), ), textForm('Title', _title), textForm('Subtitle', _subtitle), Container( margin: const EdgeInsets.only(top: 5.0), padding: const EdgeInsets.all(20.0), child: TextFormField( controller: _date, validator: (value) { if (value == null || value.isEmpty) { return 'Please Select a due date'; } return null; }, decoration: const InputDecoration( label: Text('Select due date'), border: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(20)), ), ), readOnly: true, onTap: () async { DateTime? pickedDate = await showDatePicker( context: context, initialDate: DateTime.now(), firstDate: DateTime(2020), lastDate: DateTime(2030)); if (pickedDate != null) { String formattedDate = DateFormat('yyyy-MM-dd').format(pickedDate); _date.text = formattedDate; } }, ), ), DropdownButton( value: Selected, hint: const Text( 'Send a reminder', ), items: notification.map((String items) { return DropdownMenuItem( value: items, child: Text(items), ); }).toList(), onChanged: (String? value) { setState(() { Selected = value!; }); }, ), Column( children: [ Padding( padding: const EdgeInsets.all(8.0), child: Text( 'Propriety', style: style.headLinelgray, ), ), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ propriety('High', Colors.redAccent), propriety('Medium', Colors.orange), propriety('Low', Colors.greenAccent), ], ), ], ), //save Container( height: 90, width: double.infinity, padding: const EdgeInsets.all(20.0), child: ElevatedButton( style: ButtonStyle( shape: MaterialStateProperty.all( RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), )), onPressed: () async { if (_formKey.currentState!.validate()) { if (_propriety == '' || _propriety == null) _propriety = 'Low'; //save data in firebase await addtask(_title.text, _subtitle.text, _date.text, Selected, _propriety!); } }, child: const Text( 'Add new task', ), ), ), ], ), ), ); } Widget propriety(String text, Color color) { return Container( padding: const EdgeInsets.all(5.0), child: OutlinedButton( style: ButtonStyle( backgroundColor: MaterialStateProperty.all( _propriety == text ? color : Colors.white), shape: MaterialStateProperty.all( RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), )), onPressed: () { setState(() { _propriety = text; }); }, child: Text( text, style: TextStyle(color: _propriety == text ? Colors.white : style.green), ), ), ); } } Widget textForm(String type, TextEditingController controller) { return Container( margin: const EdgeInsets.only(top: 5.0), padding: const EdgeInsets.all(20.0), child: TextFormField( controller: controller, validator: (value) { if (value == null || value.isEmpty) { return 'Please enter a ${type}'; } return null; }, decoration: InputDecoration( label: Text(type), border: const OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(20)), ), ), ), ); }
0
mirrored_repositories/to_do_app/lib
mirrored_repositories/to_do_app/lib/Screen/calnder.dart
import 'package:flutter/material.dart'; import 'package:syncfusion_flutter_calendar/calendar.dart'; import '../utils/app_style.dart'; import '../firebase.dart'; class Calander extends StatefulWidget { const Calander({super.key}); @override State<Calander> createState() => _CalanderState(); } class _CalanderState extends State<Calander> { Map tasks = {}; List<Meeting> meetings = <Meeting>[]; @override void initState() { super.initState(); var taks = dataFirebase.getAllData(); taks.then((value) { tasks = value.asMap(); }); } List<Meeting> _getDataSource() { DateTime today = DateTime.now(); DateTime startTime = DateTime(today.year, today.month, today.day, 9, 0, 0); DateTime endTime = startTime.add(const Duration(hours: 2)); meetings.add( Meeting('Conference', startTime, endTime, Colors.redAccent, false)); meetings.add( Meeting('Conference2', startTime, endTime, Colors.greenAccent, false)); meetings .add(Meeting('Conference2', startTime, endTime, Colors.orange, false)); for (int i = 0; tasks.length >= i; i++) { DateTime today = DateTime.now(); print(tasks[i]['title']); DateTime startTime = DateTime(today.year, today.month, today.day, 9, 0, 0); DateTime endTime = startTime.add(const Duration(hours: 2)); Color temp; if (tasks[i]['propriety'] == 'High') temp = Colors.redAccent; else if (tasks[i]['propriety'] == 'Medium') temp = Colors.orange; else temp = Colors.greenAccent; meetings.add(Meeting(tasks[i]['title'], startTime, endTime, temp, false)); } return meetings; } Widget build(BuildContext context) { var size = MediaQuery.of(context).size; return Column( children: [ Container( height: size.height * 0.18, width: double.infinity, decoration: BoxDecoration( color: style.green, borderRadius: BorderRadius.circular(20), ), child: Center( child: Text( 'Calendar', style: style.textStyleWhite, ), ), ), Expanded( child: SfCalendar( view: CalendarView.month, monthViewSettings: MonthViewSettings(showAgenda: true), //bring data from firebase as a list dataSource: MeetingDataSource(_getDataSource()), ), ), ], ); } } class MeetingDataSource extends CalendarDataSource { MeetingDataSource(List<Meeting> source) { appointments = source; } @override DateTime getStartTime(int index) { return appointments![index].from; } @override DateTime getEndTime(int index) { return appointments![index].to; } @override String getSubject(int index) { return appointments![index].eventName; } @override Color getColor(int index) { return appointments![index].background; } @override bool isAllDay(int index) { return appointments![index].isAllDay; } } class Meeting { Meeting(this.eventName, this.from, this.to, this.background, this.isAllDay); String eventName; DateTime from; DateTime to; Color background; bool isAllDay; }
0
mirrored_repositories/to_do_app/lib
mirrored_repositories/to_do_app/lib/Screen/sellall.dart
import 'package:flutter/material.dart'; import 'package:to_do_app/utils/app_style.dart'; class SeeAll extends StatefulWidget { const SeeAll({super.key}); @override State<SeeAll> createState() => _SeeAllState(); } class _SeeAllState extends State<SeeAll> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: ListView.builder( itemCount: 3, itemBuilder: ((context, index) { return ListTile( title: Text( 'Title', style: style.textStyle, ), subtitle: Text( 'Subtitle', style: style.headLine3, ), leading: Container( padding: const EdgeInsets.all(5), decoration: BoxDecoration( borderRadius: BorderRadius.circular(20), color: Colors.redAccent, ), child: const Text('Priority'), ), ); }), ), ); } }
0
mirrored_repositories/to_do_app/lib
mirrored_repositories/to_do_app/lib/Screen/homepage.dart
import 'dart:async'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:get/get.dart'; import 'package:intl/intl.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:to_do_app/Screen/login.dart'; import 'package:to_do_app/Screen/profile.dart'; import 'package:to_do_app/Screen/timer.dart'; import 'package:to_do_app/Widget/alltasks.dart'; import 'package:to_do_app/Widget/todotask.dart'; import '../utils/app_style.dart'; import '../Widget/bottombar.dart'; import 'add.dart'; import 'calnder.dart'; import '../firebase.dart'; class HomePage extends StatefulWidget { HomePage({super.key}); @override State<HomePage> createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { final List _pages = [ HomePage(), const AddToDo(), const Timer(), const Calander(), const ProfileManagement(), ]; int _pageindex = 0; @override Widget build(BuildContext context) { final size = MediaQuery.of(context).size; dataFirebase.getAllData(); return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( child: Container( height: size.height * 0.18, width: double.infinity, decoration: BoxDecoration( color: style.green, borderRadius: BorderRadius.circular(20), ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ const Padding( padding: EdgeInsets.all(8.0), child: CircleAvatar( backgroundColor: Colors.white, ), ), Text( 'Welcome', style: style.textStyleWhite, ), IconButton( icon: const Icon( Icons.login, color: Colors.white, ), onPressed: () { FirebaseAuth.instance.signOut(); Get.off(() => const Login()); }, ), ], ), ), ), Padding( padding: const EdgeInsets.all(8.0), child: Text( DateFormat.MMMMEEEEd().format(DateTime.now()).toString(), style: style.textStyleBlack, ), ), AllTasks(), ], ); } } Widget taskRow(String text, String text2, String type) { return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Padding( padding: const EdgeInsets.all(8.0), child: Text( text, style: style.textStyle, ), ), Padding( padding: const EdgeInsets.all(8.0), child: InkWell( onTap: () {}, child: Text( text2, style: style.headLine3, ), ), ), ], ); }
0
mirrored_repositories/to_do_app/lib
mirrored_repositories/to_do_app/lib/Screen/login.dart
import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:to_do_app/Screen/register.dart'; import 'package:to_do_app/Widget/bottombar.dart'; import '../Widget/Texffieldform.dart'; import '../Widget/button.dart'; import '../utils/app_style.dart'; import 'homepage.dart'; import '../firebase.dart'; class Login extends StatefulWidget { const Login({super.key}); @override State<Login> createState() => _LoginState(); } class _LoginState extends State<Login> { final TextEditingController _email = TextEditingController(); final TextEditingController _password = TextEditingController(); final _formKey = GlobalKey<FormState>(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: SingleChildScrollView( child: Form( key: _formKey, child: Column( mainAxisAlignment: MainAxisAlignment.start, children: [ Image.asset( 'asset/images/login.jpg', height: 300, fit: BoxFit.cover, ), Text( 'Login', style: style.textStyle, ), Container( margin: const EdgeInsets.only(right: 10, left: 10), padding: const EdgeInsets.all(10), child: TextFormField( validator: (value) { if (value!.isEmpty) { return 'E-mail / username is required'; } return null; }, controller: _email, keyboardType: TextInputType.emailAddress, decoration: const InputDecoration( suffixIcon: Icon(Icons.person_outline), hintText: 'Enter your E-mail', border: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(15.0))), ), ), ), Container( margin: const EdgeInsets.only(right: 10, left: 10), padding: const EdgeInsets.all(10), child: TextFormField( obscureText: true, validator: (value) { if (value!.isEmpty) { return 'password is required'; } else if (value.length < 8) { return 'password must be at least 8 chr '; } return null; }, controller: _password, keyboardType: TextInputType.emailAddress, decoration: const InputDecoration( suffixIcon: Icon(Icons.lock), hintText: 'Enter your password', border: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(15.0))), ), ), ), Container( width: double.infinity, height: 50, margin: const EdgeInsets.only(left: 20, right: 20), child: ElevatedButton( style: ButtonStyle( fixedSize: MaterialStateProperty.all( const Size.fromWidth(double.infinity), ), padding: MaterialStateProperty.all( const EdgeInsets.all(10), ), shape: MaterialStateProperty.all( RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), ), ), onPressed: () async { if (_formKey.currentState!.validate()) { try { await FirebaseAuth.instance .signInWithEmailAndPassword( email: _email.text, password: _password.text) .then((value) async { await dataFirebase.getuser(); Get.off(() => const BottomBar()); }).onError((error, stackTrace) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( backgroundColor: Colors.white, behavior: SnackBarBehavior.floating, elevation: 0, content: Container( margin: const EdgeInsets.all(10), padding: const EdgeInsets.all(10), decoration: const BoxDecoration( color: Colors.redAccent, borderRadius: BorderRadius.all(Radius.circular(10)), ), height: 80, child: Text( 'The Email or password is/are wrong, please try again'), ), ), ); ; }); } catch (e) { print(e); } } }, child: const Text( 'login', style: TextStyle( fontSize: 20, ), ), ), ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text('Do not have an account,'), TextButton( onPressed: () { Get.off(() => const Register()); }, child: Text( 'Register from here', style: TextStyle( color: style.lightgreen, ), ), ), ], ), ], ), ), ), ); } }
0
mirrored_repositories/to_do_app/lib
mirrored_repositories/to_do_app/lib/Screen/timer.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:get/state_manager.dart'; import 'package:to_do_app/utils/app_style.dart'; import 'package:flutter_ringtone_player/flutter_ringtone_player.dart'; import '../utils/app_style.dart'; class Timer extends StatefulWidget { const Timer({super.key}); @override State<Timer> createState() => _TimerState(); } class _TimerState extends State<Timer> with TickerProviderStateMixin { late AnimationController controller; bool play = false; String get count { Duration count = controller.duration! * controller.value; return controller.isDismissed ? '${(controller.duration!.inHours % 60).toString().padLeft(2, '0')}:${(controller.duration!.inMinutes % 60).toString().padLeft(2, '0')}:${(controller.duration!.inSeconds % 60).toString().padLeft(2, '0')}' : '${(count.inHours % 60).toString().padLeft(2, '0')}:${(count.inMinutes % 60).toString().padLeft(2, '0')}:${(count.inSeconds % 60).toString().padLeft(2, '0')}'; } void not() { if (controller == '0:00:00') { FlutterRingtonePlayer.playNotification(); } } double progrss = 1.0; @override void initState() { super.initState(); controller = AnimationController(vsync: this, duration: Duration(seconds: 60)); //run when controller value change controller.addListener(() { not(); if (controller.isAnimating) { setState(() { progrss = controller.value; }); } else { progrss = 1.0; play = false; } }); } @override void dispose() { controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { var size = MediaQuery.of(context).size; return Column( children: [ Container( margin: const EdgeInsets.only(bottom: 10), height: size.height * 0.18, width: double.infinity, decoration: BoxDecoration( color: style.green, borderRadius: BorderRadius.circular(20), ), child: Center( child: Text( 'Set timer', style: style.textStyleWhite, ), ), ), Stack( alignment: AlignmentDirectional.center, children: [ SizedBox( width: size.width * 0.8, height: size.height * 0.4, child: CircularProgressIndicator( backgroundColor: Colors.grey[400], value: progrss, color: style.yellow, strokeWidth: 5, ), ), GestureDetector( onTap: (() { if (controller.isDismissed || play == false) { showModalBottomSheet( context: context, builder: (context) => SizedBox( height: size.height * 0.3, child: CupertinoTimerPicker( initialTimerDuration: controller.duration!, onTimerDurationChanged: (value) { setState(() { controller.duration = value; }); }, ), ), ); } }), child: AnimatedBuilder( animation: controller, builder: (context, child) => Text( count, style: style.textStyleBlack, ), ), ), ], ), const SizedBox( height: 20, ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ timerbutton(const Duration(minutes: 30)), timerbutton(const Duration(minutes: 15)), timerbutton(const Duration(minutes: 5)), ], ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ ElevatedButton( style: ButtonStyle( shape: MaterialStateProperty.all( RoundedRectangleBorder( borderRadius: BorderRadius.circular(20.0), ), ), ), onPressed: () { if (controller.isAnimating) { controller.stop(); setState(() { play = false; }); } else { controller.reverse( from: controller.value == 0 ? 1.0 : controller.value); setState(() { play = true; }); } }, child: Icon(play == false ? Icons.play_arrow_outlined : Icons.pause), ), const SizedBox( width: 20, ), ElevatedButton( style: ButtonStyle( shape: MaterialStateProperty.all( RoundedRectangleBorder( borderRadius: BorderRadius.circular(20.0), ), ), backgroundColor: MaterialStateProperty.all(style.yellow), ), onPressed: () { controller.reset(); setState(() { play = false; }); }, child: const Icon(Icons.restore_outlined), ), ], ), ], ); } Widget timerbutton(Duration text) { return Container( padding: const EdgeInsets.all(10), margin: const EdgeInsets.all(10), child: OutlinedButton( onPressed: () { setState(() { controller.duration = text; }); }, child: Text( '${text.inMinutes} min', ), ), ); } }
0
mirrored_repositories/to_do_app/lib
mirrored_repositories/to_do_app/lib/Widget/Texffieldform.dart
import 'package:flutter/material.dart'; class MyTextFormField extends StatelessWidget { final String hintText; final Function validator; final Function onSaved; final bool isPassword; final bool isEmail; final Icon icons; final TextEditingController controller; MyTextFormField({ required this.hintText, required this.validator, required this.onSaved, this.isPassword = false, this.isEmail = false, required this.icons, required this.controller, }); @override Widget build(BuildContext context) { return Container( margin: const EdgeInsets.only(right: 10, left: 10), padding: const EdgeInsets.all(10), child: TextFormField( controller: controller, keyboardType: isEmail == true ? TextInputType.emailAddress : TextInputType.text, decoration: InputDecoration( suffixIcon: icons, hintText: hintText, border: const OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(15.0))), ), ), ); } }
0
mirrored_repositories/to_do_app/lib
mirrored_repositories/to_do_app/lib/Widget/button.dart
// ignore_for_file: public_member_api_docs, sort_constructors_first import 'package:flutter/material.dart'; class Button extends StatelessWidget { const Button({ Key? key, required this.text, required this.ontap, }) : super(key: key); final String text; final Function ontap; @override Widget build(BuildContext context) { return Container( width: double.infinity, height: 50, margin: const EdgeInsets.only(left: 20, right: 20), child: ElevatedButton( style: ButtonStyle( fixedSize: MaterialStateProperty.all( const Size.fromWidth(double.infinity), ), padding: MaterialStateProperty.all( const EdgeInsets.all(10), ), shape: MaterialStateProperty.all( RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), ), ), onPressed: () { //check firebase then go to homepage, or register ontap; }, child: Text( text, style: const TextStyle( fontSize: 20, ), ), ), ); } }
0
mirrored_repositories/to_do_app/lib
mirrored_repositories/to_do_app/lib/Widget/bottombar.dart
import 'package:flutter/material.dart'; import 'package:to_do_app/Screen/add.dart'; import 'package:to_do_app/Screen/calnder.dart'; import 'package:to_do_app/Screen/homepage.dart'; import 'package:to_do_app/Screen/profile.dart'; import 'package:to_do_app/Screen/timer.dart'; import 'package:to_do_app/utils/app_style.dart'; class BottomBar extends StatefulWidget { const BottomBar({super.key}); @override State<BottomBar> createState() => _BottomBarState(); } class _BottomBarState extends State<BottomBar> { final List _pages = [ HomePage(), const Calander(), const AddToDo(), const Timer(), const ProfileManagement(), ]; int _pageindex = 0; @override Widget build(BuildContext context) { return Scaffold( //for not shown FloatingActionButton when keyboard is active resizeToAvoidBottomInset: false, floatingActionButton: FloatingActionButton( backgroundColor: style.yellow, child: const Icon(Icons.add), onPressed: () { setState(() { _pageindex = 2; }); }, ), floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked, body: _pages[_pageindex], bottomNavigationBar: BottomAppBar( shape: const CircularNotchedRectangle(), notchMargin: 8, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ icon(const Icon(Icons.home), 0), icon(const Icon(Icons.calendar_month), 1), icon(const Icon(Icons.timer), 3), icon(const Icon(Icons.settings), 4), ], ), ), ); } Widget icon(Icon icon, int page) { return Container( padding: const EdgeInsets.all(5), child: IconButton( color: _pageindex == page ? style.green : const Color.fromARGB(255, 35, 134, 156), onPressed: () { setState(() { _pageindex = page; }); }, icon: icon, ), ); } } // bottomNavigationBar: BottomNavigationBar( // items: const <BottomNavigationBarItem>[ // BottomNavigationBarItem( // icon: Icon(Icons.home), // label: 'Home', // ), // BottomNavigationBarItem( // icon: Icon(Icons.calendar_month), // label: 'Calendar', // ), // BottomNavigationBarItem( // icon: Icon(Icons.add_circle), // label: 'Add', // ), // BottomNavigationBarItem( // icon: Icon(Icons.timer), // label: 'Timer', // ), // BottomNavigationBarItem( // icon: Icon(Icons.settings), // label: 'Settings', // ), // ], // currentIndex: _pageindex, // unselectedItemColor: Color.fromARGB(255, 35, 134, 156), // selectedItemColor: const Color(0xFF064F60), // onTap: (index) { // setState(() { // _pageindex = index; // }); // }, // ),
0
mirrored_repositories/to_do_app/lib
mirrored_repositories/to_do_app/lib/Widget/todotask.dart
import 'package:awesome_dialog/awesome_dialog.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:get/state_manager.dart'; import 'package:intl/intl.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:to_do_app/Widget/rowtask.dart'; import 'package:to_do_app/firebase.dart'; import 'package:to_do_app/utils/app_style.dart'; import '../utils/app_style.dart'; import 'bottombar.dart'; class ToDoTask extends StatefulWidget { const ToDoTask({super.key}); @override State<ToDoTask> createState() => _ToDoTaskState(); } class _ToDoTaskState extends State<ToDoTask> { Map tasks = {}; @override void initState() { super.initState(); var taks = dataFirebase.getAllData(); taks.then((value) { tasks = value.asMap(); }); } Widget build(BuildContext context) { var size = MediaQuery.of(context).size; Color pro = Colors.grey; return GridView.builder( padding: const EdgeInsets.all(10), scrollDirection: Axis.horizontal, gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 1, ), itemCount: tasks.length, itemBuilder: (BuildContext context, int index) { if (tasks[index]['propriety'] == 'High') { pro = Colors.redAccent; } else if (tasks[index]['propriety'] == 'Medium') pro = Colors.orange; else if (tasks[index]['propriety'] == 'Low') pro = Colors.greenAccent; return tasks.length == 0 ? Text( 'No tasks has been added yet, please add a new task', style: style.textStyleBlack, ) : InkWell( onTap: () { showDialog<String>( context: context, builder: (BuildContext context) => AlertDialog( shape: const RoundedRectangleBorder( borderRadius: BorderRadius.all( Radius.circular(32.0), ), ), title: Center( child: Text( tasks[index]['title'], style: style.textStyleBlack, ), ), content: SizedBox( height: size.height * 0.2, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Padding( padding: const EdgeInsets.all(10.0), child: Text(tasks[index]['subtitle'], style: style.headLinelgray), ), Padding( padding: const EdgeInsets.all(10), child: Text(tasks[index]['date'], style: style.headLinelgray), ), Container( padding: const EdgeInsets.all(10), decoration: BoxDecoration( borderRadius: BorderRadius.circular(20), color: pro, ), child: Text(tasks[index]['propriety']), ), ], ), ), actions: <Widget>[ TextButton( onPressed: () => Navigator.pop(context, 'OK'), child: const Text('OK'), ), ], ), ); }, child: Card( clipBehavior: Clip.hardEdge, borderOnForeground: false, child: SizedBox( width: size.width * 0.2, height: size.height * 0.2, child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Column( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Text( tasks[index]['title'], style: style.textStyle, ), Container( width: size.width * 0.25, child: Text( tasks[index]['subtitle'], style: style.headLine3, softWrap: false, maxLines: 1, overflow: TextOverflow.ellipsis, ), ), Container( padding: const EdgeInsets.all(5), child: Text(tasks[index]['propriety']), decoration: BoxDecoration( borderRadius: BorderRadius.circular(20), color: pro, ), ), ], ), Column( mainAxisAlignment: MainAxisAlignment.center, children: [ IconButton( onPressed: () { //pop up AwesomeDialog( context: context, dialogType: DialogType.warning, animType: AnimType.rightSlide, title: 'Delete task', desc: 'Are you sure that you want to delete ${tasks[index]['title']} task?', btnCancelColor: Colors.grey, btnOkColor: Colors.redAccent, btnOkText: 'Delete', btnCancelOnPress: () {}, btnOkOnPress: () async { var documentID; //delete task CollectionReference Firebasetask = await FirebaseFirestore.instance .collection('task'); var querySnapshots = await Firebasetask.get(); for (var snapshot in querySnapshots.docs) { documentID = snapshot.id; } Firebasetask.doc(documentID).delete().then( (value) => print('task has been deleted')); Get.off(() => const BottomBar()); }, ).show(); }, icon: const Icon( Icons.delete, color: Color.fromARGB(255, 122, 122, 122), ), ), IconButton( onPressed: () {}, icon: const Icon( Icons.edit, color: Color.fromARGB(255, 122, 122, 122), ), ), ], ) ], ), ), ), ); }, ); } }
0
mirrored_repositories/to_do_app/lib
mirrored_repositories/to_do_app/lib/Widget/alltasks.dart
import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:get/utils.dart'; import 'package:to_do_app/Screen/sellall.dart'; import 'package:to_do_app/Widget/rowtask.dart'; import '../utils/app_style.dart'; import 'ToDotask.dart'; class AllTasks extends StatefulWidget { const AllTasks({super.key}); @override State<AllTasks> createState() => _AllTasksState(); } class _AllTasksState extends State<AllTasks> { @override Widget build(BuildContext context) { final size = MediaQuery.of(context).size; return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.all(8.0), child: Text( 'Numbers of task 10', style: style.headLinelightgreen, ), ), const RowTask( text: 'Tasks To do', text2: 'See All', type: 'To do', ), SizedBox( height: size.height * 0.25, width: size.width, child: ToDoTask(), ), const SizedBox( height: 20, ), const RowTask( text: 'Tasks in progress', text2: 'See All', type: 'progress'), SizedBox( height: size.height * 0.25, width: size.width, child: const ToDoTask(), ), ], ); } }
0
mirrored_repositories/to_do_app/lib
mirrored_repositories/to_do_app/lib/Widget/donetasks.dart
import 'package:flutter/material.dart'; class DoneTasks extends StatefulWidget { const DoneTasks({super.key}); @override State<DoneTasks> createState() => _DoneTasksState(); } class _DoneTasksState extends State<DoneTasks> { @override Widget build(BuildContext context) { return Container(); } }
0
mirrored_repositories/to_do_app/lib
mirrored_repositories/to_do_app/lib/Widget/rowtask.dart
import 'package:flutter/material.dart'; import 'package:get/get.dart'; import 'package:to_do_app/Screen/sellall.dart'; import '../utils/app_style.dart'; class RowTask extends StatelessWidget { const RowTask({ super.key, required this.text, required this.text2, required this.type, }); final String text; final String text2; final String type; @override Widget build(BuildContext context) { return Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Padding( padding: const EdgeInsets.all(8.0), child: Text( text, style: style.textStyle, ), ), Padding( padding: const EdgeInsets.all(8.0), child: InkWell( onTap: () { //send type Get.to(() => const SeeAll()); }, child: Text( text2, style: style.headLine3, ), ), ), ], ); } }
0
mirrored_repositories/to_do_app/lib
mirrored_repositories/to_do_app/lib/Model/user.dart
import 'package:flutter/material.dart'; class User { String username; String email; String password; User({required this.username, required this.email, required this.password}); }
0
mirrored_repositories/to_do_app/lib
mirrored_repositories/to_do_app/lib/utils/app_style.dart
import 'package:flutter/material.dart'; Color primary = const Color(0xFFFAFAFA); class style { static Color primaryColor = primary; static Color yellow = const Color(0xFFFFAD47); static Color green = const Color(0xFF064F60); static Color lightgreen = Color.fromARGB(255, 25, 100, 117); static Color bgColor = const Color(0xFFeeedf2); static Color darkGray = const Color.fromARGB(255, 46, 46, 46); static TextStyle textStyleBlack = TextStyle(fontSize: 26, color: darkGray, fontWeight: FontWeight.w500); static TextStyle textStyle = TextStyle(fontSize: 26, color: green, fontWeight: FontWeight.w500); static TextStyle textStyleWhite = TextStyle(fontSize: 26, color: Colors.white, fontWeight: FontWeight.w500); static TextStyle textStyleyellow = TextStyle(fontSize: 26, color: yellow, fontWeight: FontWeight.w500); static TextStyle headLine2 = const TextStyle( fontSize: 21, color: Colors.white, fontWeight: FontWeight.bold); static TextStyle headLine3 = TextStyle( fontSize: 17, color: Colors.grey.shade500, fontWeight: FontWeight.w500); static TextStyle headLinelightgreen = TextStyle(fontSize: 17, color: lightgreen, fontWeight: FontWeight.w500); static TextStyle headLinelgray = TextStyle(fontSize: 17, color: darkGray, fontWeight: FontWeight.w500); }
0
mirrored_repositories/to_do_app
mirrored_repositories/to_do_app/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility 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:to_do_app/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/flutter_simple_counter
mirrored_repositories/flutter_simple_counter/lib/main.dart
import 'package:flutter/material.dart'; import 'package:simple_counter/screens/home_screen.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return const MaterialApp( debugShowCheckedModeBanner: false, home: HomeScreen(), ); } }
0