repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/Illusion
mirrored_repositories/Illusion/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:smai/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/Music_Player
mirrored_repositories/Music_Player/lib/global.dart
import 'package:assets_audio_player/assets_audio_player.dart'; class Global { static Map playSong = {}; static int index = 0; static List songs = [ { 'name': 'Akull - Laal Bindi (Official Video) _ New Song _ VYRL Originals(MP3_320K)', 'path': 'assets/audio/Akull - Laal Bindi (Official Video) _ New Song _ VYRL Originals(MP3_320K).mp3', 'player': AssetsAudioPlayer(), 'totalDuration': Duration.zero, 'image': 'https://mrjatt.fm/covers/thumbs/lcoai.jpg', }, { 'name': 'Coke Studio _ Season 14 _ Pasoori _ Ali Sethi x Shae Gill(MP3_320K)', 'path': 'assets/audio/Coke Studio _ Season 14 _ Pasoori _ Ali Sethi x Shae Gill(MP3_320K).mp3', 'player': AssetsAudioPlayer(), 'totalDuration': Duration.zero, 'image': 'https://snoidcdnems07.cdnsrv.jio.com/c.saavncdn.com/663/Pasoori-Punjabi-2022-20220203181058-500x500.jpg', }, { 'name': 'Daaru Party ( Lyrical Video ) _ Millind Gaba _ Punjabi Lyricai Videos _ Speed Records(MP3_320K)', 'path': 'assets/audio/Daaru Party ( Lyrical Video ) _ Millind Gaba _ Punjabi Lyricai Videos _ Speed Records(MP3_320K).mp3', 'player': AssetsAudioPlayer(), 'totalDuration': Duration.zero, 'image': 'https://snoidcdnems04.cdnsrv.jio.com/c.saavncdn.com/941/Daaru-Party-Remix-Punjabi-2019-20191128180705-500x500.jpg', }, { 'name': 'Desi Kalakaar Full AUDIO Song _ Yo Yo Honey Singh _ Desi Kalakaar_ Honey Singh New Songs 2014(MP3_320K)', 'path': 'assets/audio/Desi Kalakaar Full AUDIO Song _ Yo Yo Honey Singh _ Desi Kalakaar_ Honey Singh New Songs 2014(MP3_320K).mp3', 'player': AssetsAudioPlayer(), 'totalDuration': Duration.zero, 'image': 'https://m.media-amazon.com/images/I/618NBd2d4xL.jpg', }, { 'name': 'Dhuni Re Dhakhavi _ Sachin-Jigar_ Sachin Sanghvi _ Nishant Thacker(MP3_320K)', 'path': 'assets/audio/Dhuni Re Dhakhavi _ Sachin-Jigar_ Sachin Sanghvi _ Nishant Thacker(MP3_320K).mp3', 'player': AssetsAudioPlayer(), 'totalDuration': Duration.zero, 'image': 'https://i.scdn.co/image/ab67616d0000b273b7301991c590e81bcb18b441', }, { 'name': 'Harrdy Sandhu - Kya Baat Ay _ Jaani _ B Praak _ Arvindr Khaira _ Official Music Video(MP3_320K)', 'path': 'assets/audio/Harrdy Sandhu - Kya Baat Ay _ Jaani _ B Praak _ Arvindr Khaira _ Official Music Video(MP3_320K).mp3', 'player': AssetsAudioPlayer(), 'totalDuration': Duration.zero, 'image': 'https://a10.gaanacdn.com/images/albums/35/2234135/crop_480x480_2234135.jpg', }, { 'name': 'Makhna - Drive_ Sushant Singh Rajput_ Jacqueline Fernandez_ Tanishk Bagchi_ Asees Kaur(MP3_320K)', 'path': 'assets/audio/Makhna - Drive_ Sushant Singh Rajput_ Jacqueline Fernandez_ Tanishk Bagchi_ Asees Kaur(MP3_320K).mp3', 'player': AssetsAudioPlayer(), 'totalDuration': Duration.zero, 'image': 'https://i.scdn.co/image/ab67616d0000b27390cd58ed82e4e15bc7a2d3de', }, { 'name': 'Naah - Harrdy Sandhu Feat. Nora Fatehi _ Jaani _ B Praak _Official Music Video-Latest Hit Song 2017(MP3_320K)', 'path': 'assets/audio/Naah - Harrdy Sandhu Feat. Nora Fatehi _ Jaani _ B Praak _Official Music Video-Latest Hit Song 2017(MP3_320K).mp3', 'player': AssetsAudioPlayer(), 'totalDuration': Duration.zero, 'image': 'https://c-fa.cdn.smule.com/rs-s80/arr/e9/c4/0f738989-0c71-41a6-84fa-51e6bd573677_1024.jpg', }, { 'name': 'She Don_t Know_ Millind Gaba Song _ Shabby _ New Hindi Song 2019 _ Latest Hindi Songs(MP3_320K)', 'path': 'assets/audio/She Don_t Know_ Millind Gaba Song _ Shabby _ New Hindi Song 2019 _ Latest Hindi Songs(MP3_320K).mp3', 'player': AssetsAudioPlayer(), 'totalDuration': Duration.zero, 'image': 'https://a10.gaanacdn.com/gn_img/song/dwN39y83DP/N39a9GaN3D/size_l_1546943511.jpg', }, ]; }
0
mirrored_repositories/Music_Player
mirrored_repositories/Music_Player/lib/main.dart
import 'package:flutter/material.dart'; import 'package:music_player/screens/home_page.dart'; import 'package:music_player/screens/player_page.dart'; void main() { runApp( MaterialApp( theme: ThemeData(primarySwatch: Colors.amber), debugShowCheckedModeBanner: false, routes: { "/": (context) => const HomePage(), "player_page": (context) => const PlayerPage(), }, ), ); }
0
mirrored_repositories/Music_Player/lib
mirrored_repositories/Music_Player/lib/screens/home_page.dart
import 'package:flutter/material.dart'; import '../global.dart'; class HomePage extends StatefulWidget { const HomePage({Key? key}) : super(key: key); @override State<HomePage> createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.black, appBar: AppBar( backgroundColor: Colors.black, elevation: 0, centerTitle: true, title: const Text( "Music Player", style: TextStyle( color: Colors.amber, fontSize: 25, fontWeight: FontWeight.bold, ), ), ), body: ListView.builder( itemCount: Global.songs.length, itemBuilder: (context, i) => Container( margin: const EdgeInsets.symmetric(horizontal: 10), decoration: BoxDecoration( border: Border( top: (i == 0) ? const BorderSide(color: Colors.amber) : BorderSide.none, bottom: const BorderSide(color: Colors.amber), ), ), padding: const EdgeInsets.symmetric(vertical: 13), child: ListTile( onTap: () { setState(() { Global.index = i; Global.playSong = Global.songs[i]; }); Navigator.of(context).pushNamed("player_page"); }, leading: Image.network( "${Global.songs[i]["image"]}", ), title: SizedBox( height: 20, child: Text( "${Global.songs[i]["name"]}", style: const TextStyle(color: Colors.white), ), ), ), ), ), ); } }
0
mirrored_repositories/Music_Player/lib
mirrored_repositories/Music_Player/lib/screens/player_page.dart
import 'package:assets_audio_player/assets_audio_player.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import '../global.dart'; class PlayerPage extends StatefulWidget { const PlayerPage({Key? key}) : super(key: key); @override State<PlayerPage> createState() => _PlayerPageState(); } class _PlayerPageState extends State<PlayerPage> { initAudio() async { await Global.playSong['player'].open( Audio(Global.playSong['path']), autoStart: false, ); setState(() { Global.playSong['totalDuration'] = Global.playSong['player'].current.value!.audio.duration; }); } @override void initState() { super.initState(); initAudio(); } @override void dispose() async { // TODO: implement dispose super.dispose(); await Global.playSong["player"].pause(); } bool isPlay = false; @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.black, appBar: AppBar( leading: IconButton( onPressed: () { Navigator.of(context).pop(); }, icon: const Icon( Icons.arrow_back_ios, color: Colors.amber, ), ), backgroundColor: Colors.black, elevation: 0, centerTitle: true, title: const Text( "Now Playing", style: TextStyle( color: Colors.amber, ), ), ), body: Container( padding: const EdgeInsets.all(20), child: Column( children: [ Text( "${Global.playSong["name"]}", style: const TextStyle(color: Colors.white, fontSize: 16), ), const SizedBox(height: 15), const Divider(color: Colors.amber), const Spacer(), Container( height: 250, width: 250, decoration: BoxDecoration( color: Colors.grey.shade600, borderRadius: BorderRadius.circular(20), image: DecorationImage( fit: BoxFit.cover, image: NetworkImage("${Global.playSong["image"]}"), ), boxShadow: const [ BoxShadow( color: Colors.amber, blurRadius: 20, ), ], ), ), const SizedBox(height: 40), StreamBuilder( stream: Global.playSong['player'].currentPosition, builder: (context, AsyncSnapshot<Duration> snapshot) { Duration? currentPosition = snapshot.data; return Column( children: [ Text( "${"$currentPosition".split(".")[0]} / ${"${Global.playSong['totalDuration']}".split(".")[0]}", style: const TextStyle(color: Colors.white, fontSize: 16), ), Slider( min: 0, max: Global.playSong['totalDuration'].inSeconds.toDouble(), value: (currentPosition != null) ? currentPosition.inSeconds.toDouble() : 0, onChanged: (val) async { await Global.playSong['player'] .seek(Duration(seconds: val.toInt())); }, ), ], ); }, ), // SizedBox(height: 30) const Spacer(), Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ IconButton( iconSize: 25, onPressed: () { showModalBottomSheet( context: context, backgroundColor: Colors.black.withOpacity(0.95), shape: const OutlineInputBorder( borderSide: BorderSide(color: Colors.amber), borderRadius: BorderRadius.only( topRight: Radius.circular(25), topLeft: Radius.circular(25), ), ), builder: (context) { return ListView.builder( itemCount: Global.songs.length, itemBuilder: (context, i) => Container( margin: const EdgeInsets.symmetric(horizontal: 25), decoration: const BoxDecoration( border: Border( bottom: BorderSide(color: Colors.amber), ), ), padding: const EdgeInsets.symmetric(vertical: 7), child: ListTile( onTap: () { Navigator.of(context).pop(); setState(() { Global.playSong["player"].pause(); Global.index = i; Global.playSong = Global.songs[i]; }); Navigator.of(context) .pushReplacementNamed("player_page"); }, leading: Image.network( "${Global.songs[i]["image"]}", ), title: SizedBox( height: 20, child: Text( "${Global.songs[i]["name"]}", style: TextStyle( color: (Global.songs[i] == Global.playSong) ? Colors.amber : Colors.white, ), ), ), ), ), ); }, ); }, icon: const Icon( Icons.filter_list, color: Colors.amber, ), ), IconButton( iconSize: 35, onPressed: () { if (Global.index > 0) { setState(() { Global.playSong["player"].pause(); Global.index--; Global.playSong = Global.songs[Global.index]; }); Navigator.of(context).pushReplacementNamed("player_page"); } }, icon: const Icon(Icons.skip_previous, color: Colors.white), ), IconButton( // padding: EdgeInsets.all(10), iconSize: 55, icon: Icon( (isPlay) ? Icons.pause : Icons.play_arrow, color: Colors.amber, ), onPressed: () async { setState(() { isPlay = (isPlay) ? false : true; }); (isPlay) ? await Global.playSong['player'].play() : await Global.playSong['player'].pause(); }, ), IconButton( iconSize: 35, onPressed: () { if (Global.index < Global.songs.length - 1) { setState(() { Global.playSong["player"].pause(); Global.index++; Global.playSong = Global.songs[Global.index]; }); Navigator.of(context).pushReplacementNamed("player_page"); } }, icon: const Icon(Icons.skip_next, color: Colors.white), ), IconButton( iconSize: 25, icon: const Icon(Icons.stop, color: Colors.amber), onPressed: () async { setState(() { isPlay = false; }); await Global.playSong['player'].stop(); }, ), ], ), ], ), ), ); } }
0
mirrored_repositories/Music_Player
mirrored_repositories/Music_Player/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:music_player/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/easy_localization
mirrored_repositories/easy_localization/lib/easy_localization.dart
library easy_localization; export 'package:easy_localization/src/easy_localization_app.dart'; export 'package:easy_localization/src/asset_loader.dart'; export 'package:easy_localization/src/public.dart'; export 'package:easy_localization/src/public_ext.dart'; export 'package:intl/intl.dart';
0
mirrored_repositories/easy_localization/lib
mirrored_repositories/easy_localization/lib/src/exceptions.dart
class LocalizationNotFoundException implements Exception { const LocalizationNotFoundException(); @override String toString() => 'Localization not found for current context'; }
0
mirrored_repositories/easy_localization/lib
mirrored_repositories/easy_localization/lib/src/localization.dart
import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/widgets.dart'; import 'plural_rules.dart'; import 'translations.dart'; class Localization { Translations? _translations, _fallbackTranslations; late Locale _locale; final RegExp _replaceArgRegex = RegExp('{}'); final RegExp _linkKeyMatcher = RegExp(r'(?:@(?:\.[a-z]+)?:(?:[\w\-_|.]+|\([\w\-_|.]+\)))'); final RegExp _linkKeyPrefixMatcher = RegExp(r'^@(?:\.([a-z]+))?:'); final RegExp _bracketsMatcher = RegExp('[()]'); final _modifiers = <String, String Function(String?)>{ 'upper': (String? val) => val!.toUpperCase(), 'lower': (String? val) => val!.toLowerCase(), 'capitalize': (String? val) => '${val![0].toUpperCase()}${val.substring(1)}' }; Localization(); static Localization? _instance; static Localization get instance => _instance ?? (_instance = Localization()); static Localization? of(BuildContext context) => Localizations.of<Localization>(context, Localization); static bool load( Locale locale, { Translations? translations, Translations? fallbackTranslations, }) { instance._locale = locale; instance._translations = translations; instance._fallbackTranslations = fallbackTranslations; return translations == null ? false : true; } String tr( String key, { List<String>? args, Map<String, String>? namedArgs, String? gender, }) { late String res; if (gender != null) { res = _gender(key, gender: gender); } else { res = _resolve(key); } res = _replaceLinks(res); res = _replaceNamedArgs(res, namedArgs); return _replaceArgs(res, args); } String _replaceLinks(String res, {bool logging = true}) { // TODO: add recursion detection and a resolve stack. final matches = _linkKeyMatcher.allMatches(res); var result = res; for (final match in matches) { final link = match[0]!; final linkPrefixMatches = _linkKeyPrefixMatcher.allMatches(link); final linkPrefix = linkPrefixMatches.first[0]!; final formatterName = linkPrefixMatches.first[1]; // Remove the leading @:, @.case: and the brackets final linkPlaceholder = link.replaceAll(linkPrefix, '').replaceAll(_bracketsMatcher, ''); var translated = _resolve(linkPlaceholder); if (formatterName != null) { if (_modifiers.containsKey(formatterName)) { translated = _modifiers[formatterName]!(translated); } else { if (logging) { EasyLocalization.logger.warning( 'Undefined modifier $formatterName, available modifiers: ${_modifiers.keys.toString()}'); } } } result = translated.isEmpty ? result : result.replaceAll(link, translated); } return result; } String _replaceArgs(String res, List<String>? args) { if (args == null || args.isEmpty) return res; for (var str in args) { res = res.replaceFirst(_replaceArgRegex, str); } return res; } String _replaceNamedArgs(String res, Map<String, String>? args) { if (args == null || args.isEmpty) return res; args.forEach((String key, String value) => res = res.replaceAll(RegExp('{$key}'), value)); return res; } static PluralRule? _pluralRule(String? locale, num howMany) { startRuleEvaluation(howMany); return pluralRules[locale]; } static PluralCase _pluralCaseFallback(num value) { switch (value) { case 0: return PluralCase.ZERO; case 1: return PluralCase.ONE; case 2: return PluralCase.TWO; default: return PluralCase.OTHER; } } String plural( String key, num value, { List<String>? args, Map<String, String>? namedArgs, String? name, NumberFormat? format, }) { late String res; final pluralRule = _pluralRule(_locale.languageCode, value); final pluralCase = pluralRule != null ? pluralRule() : _pluralCaseFallback(value); switch (pluralCase) { case PluralCase.ZERO: res = _resolvePlural(key, 'zero'); break; case PluralCase.ONE: res = _resolvePlural(key, 'one'); break; case PluralCase.TWO: res = _resolvePlural(key, 'two'); break; case PluralCase.FEW: res = _resolvePlural(key, 'few'); break; case PluralCase.MANY: res = _resolvePlural(key, 'many'); break; case PluralCase.OTHER: res = _resolvePlural(key, 'other'); break; default: throw ArgumentError.value(value, 'howMany', 'Invalid plural argument'); } final formattedValue = format == null ? '$value' : format.format(value); if (name != null) { namedArgs = {...?namedArgs, name: formattedValue}; } res = _replaceNamedArgs(res, namedArgs); return _replaceArgs(res, args ?? [formattedValue]); } String _gender(String key, {required String gender}) { return _resolve('$key.$gender'); } String _resolvePlural(String key, String subKey) { if (subKey == 'other') return _resolve('$key.other'); final tag = '$key.$subKey'; var resource = _resolve(tag, logging: false, fallback: _fallbackTranslations != null); if (resource == tag) { resource = _resolve('$key.other'); } return resource; } String _resolve(String key, {bool logging = true, bool fallback = true}) { var resource = _translations?.get(key); if (resource == null) { if (logging) { EasyLocalization.logger.warning('Localization key [$key] not found'); } if (_fallbackTranslations == null || !fallback) { return key; } else { resource = _fallbackTranslations?.get(key); if (resource == null) { if (logging) { EasyLocalization.logger .warning('Fallback localization key [$key] not found'); } return key; } } } return resource; } bool exists(String key){ return _translations?.get(key) != null; } }
0
mirrored_repositories/easy_localization/lib
mirrored_repositories/easy_localization/lib/src/public_ext.dart
import 'package:easy_localization/src/exceptions.dart'; import 'package:easy_localization/src/localization.dart'; import 'package:flutter/widgets.dart'; import 'package:intl/intl.dart'; import 'easy_localization_app.dart'; import 'public.dart' as ez; /// Text widget extension method for access to [tr()] and [plural()] /// Example : /// ```dart /// Text('title').tr() /// Text('day').plural(21) /// ``` extension TextTranslateExtension on Text { /// {@macro tr} Text tr( {List<String>? args, BuildContext? context, Map<String, String>? namedArgs, String? gender}) => Text( ez.tr( data ?? '', context: context, args: args, namedArgs: namedArgs, gender: gender, ), key: key, style: style, strutStyle: strutStyle, textAlign: textAlign, textDirection: textDirection, locale: locale, softWrap: softWrap, overflow: overflow, textScaleFactor: textScaleFactor, maxLines: maxLines, semanticsLabel: semanticsLabel, textWidthBasis: textWidthBasis); /// {@macro plural} Text plural( num value, { BuildContext? context, List<String>? args, Map<String, String>? namedArgs, String? name, NumberFormat? format, }) => Text( ez.plural( data ?? '', value, context: context, args: args, namedArgs: namedArgs, name: name, format: format, ), key: key, style: style, strutStyle: strutStyle, textAlign: textAlign, textDirection: textDirection, locale: locale, softWrap: softWrap, overflow: overflow, textScaleFactor: textScaleFactor, maxLines: maxLines, semanticsLabel: semanticsLabel, textWidthBasis: textWidthBasis); } /// Strings extension method for access to [tr()] and [plural()] /// Example : /// ```dart /// 'title'.tr() /// 'day'.plural(21) /// ``` extension StringTranslateExtension on String { /// {@macro tr} String tr({ List<String>? args, Map<String, String>? namedArgs, String? gender, BuildContext? context, }) => ez.tr(this, context: context, args: args, namedArgs: namedArgs, gender: gender); bool trExists() => ez.trExists(this); /// {@macro plural} String plural( num value, { List<String>? args, BuildContext? context, Map<String, String>? namedArgs, String? name, NumberFormat? format, }) => ez.plural( this, value, context: context, args: args, namedArgs: namedArgs, name: name, format: format, ); } /// BuildContext extension method for access to [locale], [supportedLocales], [fallbackLocale], [delegates] and [deleteSaveLocale()] /// /// Example : /// /// ```dart /// context.locale = Locale('en', 'US'); /// print(context.locale.toString()); /// /// context.deleteSaveLocale(); /// /// print(context.supportedLocales); // output: [en_US, ar_DZ, de_DE, ru_RU] /// print(context.fallbackLocale); // output: en_US /// ``` extension BuildContextEasyLocalizationExtension on BuildContext { /// Get current locale Locale get locale => EasyLocalization.of(this)!.locale; /// Change app locale Future<void> setLocale(Locale val) async => EasyLocalization.of(this)!.setLocale(val); /// Old Change app locale @Deprecated( 'This is the func used in the old version of EasyLocalization. The modern func is `setLocale(val)` . ' 'This feature was deprecated after v3.0.0') set locale(Locale val) => EasyLocalization.of(this)!.setLocale(val); /// Get List of supported locales. List<Locale> get supportedLocales => EasyLocalization.of(this)!.supportedLocales; /// Get fallback locale Locale? get fallbackLocale => EasyLocalization.of(this)!.fallbackLocale; /// {@macro flutter.widgets.widgetsApp.localizationsDelegates} /// return /// ```dart /// delegates = [ /// delegate /// GlobalMaterialLocalizations.delegate, /// GlobalWidgetsLocalizations.delegate, /// GlobalCupertinoLocalizations.delegate /// ], /// ``` List<LocalizationsDelegate> get localizationDelegates => EasyLocalization.of(this)!.delegates; /// Clears a saved locale from device storage Future<void> deleteSaveLocale() => EasyLocalization.of(this)!.deleteSaveLocale(); /// Getting device locale from platform Locale get deviceLocale => EasyLocalization.of(this)!.deviceLocale; /// Reset locale to platform locale Future<void> resetLocale() => EasyLocalization.of(this)!.resetLocale(); /// An extension method for translating your language keys. /// Subscribes the widget on current [Localization] that provided from context. /// Throws exception if [Localization] was not found. /// /// [key] Localization key /// [args] List of localized strings. Replaces {} left to right /// [namedArgs] Map of localized strings. Replaces the name keys {key_name} according to its name /// [gender] Gender switcher. Changes the localized string based on gender string /// /// Example: /// /// ```json /// { /// "msg":"{} are written in the {} language", /// "msg_named":"Easy localization is written in the {lang} language", /// "msg_mixed":"{} are written in the {lang} language", /// "gender":{ /// "male":"Hi man ;) {}", /// "female":"Hello girl :) {}", /// "other":"Hello {}" /// } /// } /// ``` /// ```dart /// Text(context.tr('msg', args: ['Easy localization', 'Dart']), // args /// Text(context.tr('msg_named', namedArgs: {'lang': 'Dart'}), // namedArgs /// Text(context.tr('msg_mixed', args: ['Easy localization'], namedArgs: {'lang': 'Dart'}), // args and namedArgs /// Text(context.tr('gender', gender: _gender ? "female" : "male"), // gender /// ``` String tr( String key, { List<String>? args, Map<String, String>? namedArgs, String? gender, }) { final localization = Localization.of(this); if (localization == null) { throw const LocalizationNotFoundException(); } return localization.tr( key, args: args, namedArgs: namedArgs, gender: gender, ); } String plural( String key, num number, { List<String>? args, Map<String, String>? namedArgs, String? name, NumberFormat? format, }) { final localization = Localization.of(this); if (localization == null) { throw const LocalizationNotFoundException(); } return localization.plural( key, number, args: args, namedArgs: namedArgs, name: name, format: format, ); } }
0
mirrored_repositories/easy_localization/lib
mirrored_repositories/easy_localization/lib/src/public.dart
import 'package:flutter/widgets.dart'; import 'package:intl/intl.dart'; import 'localization.dart'; /// {@template tr} /// Main function for translate your language keys /// [key] Localization key /// [BuildContext] The location in the tree where this widget builds /// [args] List of localized strings. Replaces {} left to right /// [namedArgs] Map of localized strings. Replaces the name keys {key_name} according to its name /// [gender] Gender switcher. Changes the localized string based on gender string /// /// Example: /// /// ```json /// { /// "msg":"{} are written in the {} language", /// "msg_named":"Easy localization is written in the {lang} language", /// "msg_mixed":"{} are written in the {lang} language", /// "gender":{ /// "male":"Hi man ;) {}", /// "female":"Hello girl :) {}", /// "other":"Hello {}" /// } /// } /// ``` /// ```dart /// Text('msg').tr(args: ['Easy localization', 'Dart']), // args /// Text('msg_named').tr(namedArgs: {'lang': 'Dart'}), // namedArgs /// Text('msg_mixed').tr(args: ['Easy localization'], namedArgs: {'lang': 'Dart'}), // args and namedArgs /// Text('gender').tr(gender: _gender ? "female" : "male"), // gender /// ``` /// {@endtemplate} String tr( String key, { BuildContext? context, List<String>? args, Map<String, String>? namedArgs, String? gender, }) { return context != null ? Localization.of(context)! .tr(key, args: args, namedArgs: namedArgs, gender: gender) : Localization.instance .tr(key, args: args, namedArgs: namedArgs, gender: gender); } bool trExists(String key) { return Localization.instance .exists(key); } /// {@template plural} /// function translate with pluralization /// [key] Localization key /// [value] Number value for pluralization /// [BuildContext] The location in the tree where this widget builds /// [args] List of localized strings. Replaces {} left to right /// [namedArgs] Map of localized strings. Replaces the name keys {key_name} according to its name /// [name] Name of number value. Replaces {$name} to value /// [format] Formats a numeric value using a [NumberFormat](https://pub.dev/documentation/intl/latest/intl/NumberFormat-class.html) class /// /// Example: ///```json /// { /// "day": { /// "zero":"{} дней", /// "one": "{} день", /// "two": "{} дня", /// "few": "{} дня", /// "many": "{} дней", /// "other": "{} дней" /// }, /// "money": { /// "zero": "You not have money", /// "one": "You have {} dollar", /// "many": "You have {} dollars", /// "other": "You have {} dollars" /// }, /// "money_args": { /// "zero": "{} has no money", /// "one": "{} has {} dollar", /// "many": "{} has {} dollars", /// "other": "{} has {} dollars" /// }, /// "money_named_args": { /// "zero": "{name} has no money", /// "one": "{name} has {money} dollar", /// "many": "{name} has {money} dollars", /// "other": "{name} has {money} dollars" /// } /// } /// ``` /// ///```dart /// Text('money').plural(1000000, format: NumberFormat.compact(locale: context.locale.toString())) // output: You have 1M dollars /// print('day'.plural(21)); // output: 21 день /// var money = plural('money', 10.23) // output: You have 10.23 dollars /// var money = plural('money_args', 10.23, args: ['John', '10.23']) // output: John has 10.23 dollars /// var money = plural('money_named_args', 10.23, namedArgs: {'name': 'Jane'}, name: 'money') // output: Jane has 10.23 dollars /// ``` /// {@endtemplate} String plural( String key, num value, { List<String>? args, BuildContext? context, Map<String, String>? namedArgs, String? name, NumberFormat? format, }) { return context != null ? Localization.of(context)!.plural(key, value, args: args, namedArgs: namedArgs, name: name, format: format) : Localization.instance.plural(key, value, args: args, namedArgs: namedArgs, name: name, format: format); }
0
mirrored_repositories/easy_localization/lib
mirrored_repositories/easy_localization/lib/src/asset_loader.dart
import 'dart:convert'; import 'dart:ui'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/services.dart'; /// abstract class used to building your Custom AssetLoader /// Example: /// ``` ///class FileAssetLoader extends AssetLoader { /// @override /// Future<Map<String, dynamic>> load(String path, Locale locale) async { /// final file = File(path); /// return json.decode(await file.readAsString()); /// } ///} /// ``` abstract class AssetLoader { const AssetLoader(); Future<Map<String, dynamic>?> load(String path, Locale locale); } /// /// default used is RootBundleAssetLoader which uses flutter's assetloader /// class RootBundleAssetLoader extends AssetLoader { const RootBundleAssetLoader(); String getLocalePath(String basePath, Locale locale) { return '$basePath/${locale.toStringWithSeparator(separator: "-")}.json'; } @override Future<Map<String, dynamic>?> load(String path, Locale locale) async { var localePath = getLocalePath(path, locale); EasyLocalization.logger.debug('Load asset from $path'); return json.decode(await rootBundle.loadString(localePath)); } }
0
mirrored_repositories/easy_localization/lib
mirrored_repositories/easy_localization/lib/src/widgets.dart
import 'package:flutter/material.dart'; class FutureErrorWidget extends StatelessWidget { final String msg; const FutureErrorWidget({Key? key, this.msg = 'Loading ...'}) : super(key: key); @override Widget build(BuildContext context) { return Container( color: Colors.white, child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [ const Icon( Icons.error_outline, color: Colors.red, size: 64, textDirection: TextDirection.ltr, ), const SizedBox(height: 20), const Text( 'Easy Localization:', textAlign: TextAlign.center, textDirection: TextDirection.ltr, style: TextStyle( fontWeight: FontWeight.w700, color: Colors.red, fontSize: 25.0), ), const SizedBox(height: 10), Text( '"$msg"', textAlign: TextAlign.center, textDirection: TextDirection.ltr, style: const TextStyle( fontWeight: FontWeight.w500, color: Colors.red, fontSize: 14.0), ), const SizedBox(height: 30), // Center( // child: CircularProgressIndicator() // ), ]), ); } }
0
mirrored_repositories/easy_localization/lib
mirrored_repositories/easy_localization/lib/src/easy_localization_app.dart
import 'dart:async'; import 'package:easy_localization/easy_localization.dart'; import 'package:easy_localization/src/easy_localization_controller.dart'; import 'package:easy_logger/easy_logger.dart'; import 'package:flutter/material.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'asset_loader.dart'; import 'localization.dart'; part 'utils.dart'; /// EasyLocalization /// example: /// ``` /// void main(){ /// runApp(EasyLocalization( /// child: MyApp(), /// supportedLocales: [Locale('en', 'US'), Locale('ar', 'DZ')], /// path: 'resources/langs/langs.csv', /// assetLoader: CsvAssetLoader() /// )); /// } /// ``` class EasyLocalization extends StatefulWidget { /// Place for your main page widget. final Widget child; /// List of supported locales. /// {@macro flutter.widgets.widgetsApp.supportedLocales} final List<Locale> supportedLocales; /// Locale when the locale is not in the list final Locale? fallbackLocale; /// Overrides device locale. final Locale? startLocale; /// Trigger for using only language code for reading localization files. /// @Default value false /// Example: /// ``` /// en.json //useOnlyLangCode: true /// en-US.json //useOnlyLangCode: false /// ``` final bool useOnlyLangCode; /// If a localization key is not found in the locale file, try to use the fallbackLocale file. /// @Default value false /// Example: /// ``` /// useFallbackTranslations: true /// ``` final bool useFallbackTranslations; /// Path to your folder with localization files. /// Example: /// ```dart /// path: 'assets/translations', /// path: 'assets/translations/lang.csv', /// ``` final String path; /// Class loader for localization files. /// You can use custom loaders from [Easy Localization Loader](https://github.com/aissat/easy_localization_loader) or create your own class. /// @Default value `const RootBundleAssetLoader()` // ignore: prefer_typing_uninitialized_variables final AssetLoader assetLoader; /// Class loader for localization files that belong to other packages. /// You can use custom loaders from [Easy Localization Loader](https://github.com/aissat/easy_localization_loader) or create your own class. /// Example: /// ```dart // runApp( // EasyLocalization( // supportedLocales: const <Locale>[ // Locale('en'), // ], // fallbackLocale: const Locale('en'), // assetLoader: const RootBundleAssetLoader(), // extraAssetLoaders: [ // TranslationsLoader(packageName: 'package_example_1'), // TranslationsLoader(packageName: 'package_example_2'), // ], // path: 'lib/l10n/translations', // child: const MainApp(), // ), // ); /// @Default value `null` final List<AssetLoader>? extraAssetLoaders; /// Save locale in device storage. /// @Default value true final bool saveLocale; /// Shows a custom error widget when an error is encountered instead of the default error widget. /// @Default value `errorWidget = ErrorWidget()` final Widget Function(FlutterError? message)? errorWidget; EasyLocalization({ Key? key, required this.child, required this.supportedLocales, required this.path, this.fallbackLocale, this.startLocale, this.useOnlyLangCode = false, this.useFallbackTranslations = false, this.assetLoader = const RootBundleAssetLoader(), this.extraAssetLoaders, this.saveLocale = true, this.errorWidget, }) : assert(supportedLocales.isNotEmpty), assert(path.isNotEmpty), super(key: key) { EasyLocalization.logger.debug('Start'); } @override // ignore: library_private_types_in_public_api _EasyLocalizationState createState() => _EasyLocalizationState(); // ignore: library_private_types_in_public_api static _EasyLocalizationProvider? of(BuildContext context) => _EasyLocalizationProvider.of(context); /// ensureInitialized needs to be called in main /// so that savedLocale is loaded and used from the /// start. static Future<void> ensureInitialized() async => await EasyLocalizationController.initEasyLocation(); /// Customizable logger static EasyLogger logger = EasyLogger(name: '🌎 Easy Localization'); } class _EasyLocalizationState extends State<EasyLocalization> { _EasyLocalizationDelegate? delegate; EasyLocalizationController? localizationController; FlutterError? translationsLoadError; @override void initState() { EasyLocalization.logger.debug('Init state'); localizationController = EasyLocalizationController( saveLocale: widget.saveLocale, fallbackLocale: widget.fallbackLocale, supportedLocales: widget.supportedLocales, startLocale: widget.startLocale, assetLoader: widget.assetLoader, extraAssetLoaders: widget.extraAssetLoaders, useOnlyLangCode: widget.useOnlyLangCode, useFallbackTranslations: widget.useFallbackTranslations, path: widget.path, onLoadError: (FlutterError e) { setState(() { translationsLoadError = e; }); }, ); // causes localization to rebuild with new language localizationController!.addListener(() { if (mounted) setState(() {}); }); super.initState(); } @override void dispose() { localizationController!.dispose(); super.dispose(); } @override Widget build(BuildContext context) { EasyLocalization.logger.debug('Build'); if (translationsLoadError != null) { return widget.errorWidget != null ? widget.errorWidget!(translationsLoadError) : ErrorWidget(translationsLoadError!); } return _EasyLocalizationProvider( widget, localizationController!, delegate: _EasyLocalizationDelegate( localizationController: localizationController, supportedLocales: widget.supportedLocales, ), ); } } class _EasyLocalizationProvider extends InheritedWidget { final EasyLocalization parent; final EasyLocalizationController _localeState; final Locale? currentLocale; final _EasyLocalizationDelegate delegate; /// {@macro flutter.widgets.widgetsApp.localizationsDelegates} /// /// ```dart /// delegates = [ /// delegate /// GlobalMaterialLocalizations.delegate, /// GlobalWidgetsLocalizations.delegate, /// GlobalCupertinoLocalizations.delegate /// ], /// ``` List<LocalizationsDelegate> get delegates => [ delegate, GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, GlobalCupertinoLocalizations.delegate, ]; /// Get List of supported locales List<Locale> get supportedLocales => parent.supportedLocales; // _EasyLocalizationDelegate get delegate => parent.delegate; _EasyLocalizationProvider(this.parent, this._localeState, {Key? key, required this.delegate}) : currentLocale = _localeState.locale, super(key: key, child: parent.child) { EasyLocalization.logger.debug('Init provider'); } /// Get current locale Locale get locale => _localeState.locale; /// Get fallback locale Locale? get fallbackLocale => parent.fallbackLocale; // Locale get startLocale => parent.startLocale; /// Change app locale Future<void> setLocale(Locale locale) async { // Check old locale if (locale != _localeState.locale) { assert(parent.supportedLocales.contains(locale)); await _localeState.setLocale(locale); } } /// Clears a saved locale from device storage Future<void> deleteSaveLocale() async { await _localeState.deleteSaveLocale(); } /// Getting device locale from platform Locale get deviceLocale => _localeState.deviceLocale; /// Reset locale to platform locale Future<void> resetLocale() => _localeState.resetLocale(); @override bool updateShouldNotify(_EasyLocalizationProvider oldWidget) { return oldWidget.currentLocale != locale; } static _EasyLocalizationProvider? of(BuildContext context) => context.dependOnInheritedWidgetOfExactType<_EasyLocalizationProvider>(); } class _EasyLocalizationDelegate extends LocalizationsDelegate<Localization> { final List<Locale>? supportedLocales; final EasyLocalizationController? localizationController; /// * use only the lang code to generate i18n file path like en.json or ar.json // final bool useOnlyLangCode; _EasyLocalizationDelegate( {this.localizationController, this.supportedLocales}) { EasyLocalization.logger.debug('Init Localization Delegate'); } @override bool isSupported(Locale locale) => supportedLocales!.contains(locale); @override Future<Localization> load(Locale value) async { EasyLocalization.logger.debug('Load Localization Delegate'); if (localizationController!.translations == null) { await localizationController!.loadTranslations(); } Localization.load(value, translations: localizationController!.translations, fallbackTranslations: localizationController!.fallbackTranslations); return Future.value(Localization.instance); } @override bool shouldReload(LocalizationsDelegate<Localization> old) => false; }
0
mirrored_repositories/easy_localization/lib
mirrored_repositories/easy_localization/lib/src/plural_rules.dart
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. /// Provides locale-specific plural rules. Based on pluralrules.js from Closure. /// /// Each function does the calculation for one or more locales. These are done in terms of /// various values used by the CLDR syntax and defined by UTS #35 /// http://unicode.org/reports/tr35/tr35-numbers.html#Plural_rules_syntax /// /// * n - absolute value of the source number (integer and decimals). /// * i - integer digits of n. /// * v - number of visible fraction digits in n, with trailing zeros. /// * w - number of visible fraction digits in n, without trailing zeros. /// * f - visible fractional digits in n, with trailing zeros. /// * t - visible fractional digits in n, without trailing zeros. // Suppress naming issues as changing them might be breaking. // ignore_for_file: constant_identifier_names, non_constant_identifier_names import 'dart:math' as math; typedef PluralRule = PluralCase Function(); /// The possible cases used in a plural rule. enum PluralCase { ZERO, ONE, TWO, FEW, MANY, OTHER } /// The default rule in case we don't have anything more specific for a locale. PluralCase _default_rule() => OTHER; /// This must be called before evaluating a new rule, because we're using /// library-global state to both keep the rules terse and minimize space. void startRuleEvaluation(num howMany, [int? precision = 0]) { _n = howMany; _precision = precision; _i = _n.round(); _updateVF(_n); _updateWT(_f, _v); } /// The number whose [PluralCase] we are trying to find. /// // This is library-global state, along with the other variables. This allows us // to avoid calculating parameters that the functions don't need and also // not introduce a subclass per locale or have instance tear-offs which // we can't cache. This is fine as long as these methods aren't async, which // they should never be. num _n = 0; /// The integer part of [_n] int _i = 0; int? _precision; /// Returns the number of digits in the fractional part of a number /// (3.1416 => 4) /// /// Takes the item count [n] and uses [_precision]. /// That's because a just looking at the value of a number is not enough to /// decide the plural form. For example "1 dollar" vs "1.00 dollars", the /// value is 1, but how it is formatted also matters. int _decimals(num n) { var str = _precision == null ? '$n' : n.toStringAsFixed(_precision!); var result = str.indexOf('.'); return (result == -1) ? 0 : str.length - result - 1; } /// Calculates and sets the _v and _f as per CLDR plural rules. /// /// The short names for parameters / return match the CLDR syntax and UTS #35 /// (https://unicode.org/reports/tr35/tr35-numbers.html#Plural_rules_syntax) /// Takes the item count [n] and a [precision]. void _updateVF(num n) { var defaultDigits = 3; _v = _precision ?? math.min(_decimals(n), defaultDigits); var base = math.pow(10, _v) as int; _f = (n * base).floor() % base; } /// Calculates and sets _w and _t as per CLDR plural rules. /// /// The short names for parameters / return match the CLDR syntax and UTS #35 /// (https://unicode.org/reports/tr35/tr35-numbers.html#Plural_rules_syntax) /// @param v Calculated previously. /// @param f Calculated previously. void _updateWT(int v, int f) { if (f == 0) { // Unused, for now _w = 0; _t = 0; return; } while ((f % 10) == 0) { f = (f / 10).floor(); v--; } // Unused, for now _w = v; _t = f; } /// Number of visible fraction digits. int _v = 0; /// Number of visible fraction digits without trailing zeros. // Unused, for now int _w = 0; /// The visible fraction digits in n, with trailing zeros. int _f = 0; /// The visible fraction digits in n, without trailing zeros. int _t = 0; // An example, for precision n = 3.1415 and precision = 7) // n : 3.1415 // str n: 3.1415000 (the "formatted" n, 7 fractional digits) // i : 3 (the integer part of n) // f : 1415000 (the fractional part of n) // v : 7 (how many digits in f) // t : 1415 (f, without trailing 0s) // w : 4 (how many digits in t) PluralCase get ZERO => PluralCase.ZERO; PluralCase get ONE => PluralCase.ONE; PluralCase get TWO => PluralCase.TWO; PluralCase get FEW => PluralCase.FEW; PluralCase get MANY => PluralCase.MANY; PluralCase get OTHER => PluralCase.OTHER; PluralCase _fil_rule() { if (_v == 0 && (_i == 1 || _i == 2 || _i == 3) || _v == 0 && _i % 10 != 4 && _i % 10 != 6 && _i % 10 != 9 || _v != 0 && _f % 10 != 4 && _f % 10 != 6 && _f % 10 != 9) { return ONE; } return OTHER; } PluralCase _pt_PT_rule() { if (_n == 1 && _v == 0) { return ONE; } return OTHER; } PluralCase _br_rule() { if (_n % 10 == 1 && _n % 100 != 11 && _n % 100 != 71 && _n % 100 != 91) { return ONE; } if (_n % 10 == 2 && _n % 100 != 12 && _n % 100 != 72 && _n % 100 != 92) { return TWO; } if ((_n % 10 >= 3 && _n % 10 <= 4 || _n % 10 == 9) && (_n % 100 < 10 || _n % 100 > 19) && (_n % 100 < 70 || _n % 100 > 79) && (_n % 100 < 90 || _n % 100 > 99)) { return FEW; } if (_n != 0 && _n % 1000000 == 0) { return MANY; } return OTHER; } PluralCase _sr_rule() { if (_v == 0 && _i % 10 == 1 && _i % 100 != 11 || _f % 10 == 1 && _f % 100 != 11) { return ONE; } if (_v == 0 && _i % 10 >= 2 && _i % 10 <= 4 && (_i % 100 < 12 || _i % 100 > 14) || _f % 10 >= 2 && _f % 10 <= 4 && (_f % 100 < 12 || _f % 100 > 14)) { return FEW; } return OTHER; } PluralCase _ro_rule() { if (_i == 1 && _v == 0) { return ONE; } if (_v != 0 || _n == 0 || _n != 1 && _n % 100 >= 1 && _n % 100 <= 19) { return FEW; } return OTHER; } PluralCase _hi_rule() { if (_i == 0 || _n == 1) { return ONE; } return OTHER; } PluralCase _fr_rule() { if (_i == 0 || _i == 1) { return ONE; } return OTHER; } PluralCase _cs_rule() { if (_i == 1 && _v == 0) { return ONE; } if (_i >= 2 && _i <= 4 && _v == 0) { return FEW; } if (_v != 0) { return MANY; } return OTHER; } PluralCase _pl_rule() { if (_i == 1 && _v == 0) { return ONE; } if (_v == 0 && _i % 10 >= 2 && _i % 10 <= 4 && (_i % 100 < 12 || _i % 100 > 14)) { return FEW; } if (_v == 0 && _i != 1 && _i % 10 >= 0 && _i % 10 <= 1 || _v == 0 && _i % 10 >= 5 && _i % 10 <= 9 || _v == 0 && _i % 100 >= 12 && _i % 100 <= 14) { return MANY; } return OTHER; } PluralCase _lv_rule() { if (_n % 10 == 0 || _n % 100 >= 11 && _n % 100 <= 19 || _v == 2 && _f % 100 >= 11 && _f % 100 <= 19) { return ZERO; } if (_n % 10 == 1 && _n % 100 != 11 || _v == 2 && _f % 10 == 1 && _f % 100 != 11 || _v != 2 && _f % 10 == 1) { return ONE; } return OTHER; } PluralCase _he_rule() { if (_i == 1 && _v == 0) { return ONE; } if (_i == 2 && _v == 0) { return TWO; } if (_v == 0 && (_n < 0 || _n > 10) && _n % 10 == 0) { return MANY; } return OTHER; } PluralCase _mt_rule() { if (_n == 1) { return ONE; } if (_n == 0 || _n % 100 >= 2 && _n % 100 <= 10) { return FEW; } if (_n % 100 >= 11 && _n % 100 <= 19) { return MANY; } return OTHER; } PluralCase _si_rule() { if ((_n == 0 || _n == 1) || _i == 0 && _f == 1) { return ONE; } return OTHER; } PluralCase _cy_rule() { if (_n == 0) { return ZERO; } if (_n == 1) { return ONE; } if (_n == 2) { return TWO; } if (_n == 3) { return FEW; } if (_n == 6) { return MANY; } return OTHER; } PluralCase _da_rule() { if (_n == 1 || _t != 0 && (_i == 0 || _i == 1)) { return ONE; } return OTHER; } PluralCase _ru_rule() { if (_v == 0 && _i % 10 == 1 && _i % 100 != 11) { return ONE; } if (_v == 0 && _i % 10 >= 2 && _i % 10 <= 4 && (_i % 100 < 12 || _i % 100 > 14)) { return FEW; } if (_v == 0 && _i % 10 == 0 || _v == 0 && _i % 10 >= 5 && _i % 10 <= 9 || _v == 0 && _i % 100 >= 11 && _i % 100 <= 14) { return MANY; } return OTHER; } PluralCase _be_rule() { if (_n % 10 == 1 && _n % 100 != 11) { return ONE; } if (_n % 10 >= 2 && _n % 10 <= 4 && (_n % 100 < 12 || _n % 100 > 14)) { return FEW; } if (_n % 10 == 0 || _n % 10 >= 5 && _n % 10 <= 9 || _n % 100 >= 11 && _n % 100 <= 14) { return MANY; } return OTHER; } PluralCase _mk_rule() { if (_v == 0 && _i % 10 == 1 || _f % 10 == 1) { return ONE; } return OTHER; } PluralCase _ga_rule() { if (_n == 1) { return ONE; } if (_n == 2) { return TWO; } if (_n >= 3 && _n <= 6) { return FEW; } if (_n >= 7 && _n <= 10) { return MANY; } return OTHER; } PluralCase _pt_rule() { if (_n >= 0 && _n <= 2 && _n != 2) { return ONE; } return OTHER; } PluralCase _es_rule() { if (_n == 1) { return ONE; } return OTHER; } PluralCase _is_rule() { if (_t == 0 && _i % 10 == 1 && _i % 100 != 11 || _t != 0) { return ONE; } return OTHER; } PluralCase _ar_rule() { if (_n == 0) { return ZERO; } if (_n == 1) { return ONE; } if (_n == 2) { return TWO; } if (_n % 100 >= 3 && _n % 100 <= 10) { return FEW; } if (_n % 100 >= 11 && _n % 100 <= 99) { return MANY; } return OTHER; } PluralCase _sl_rule() { if (_v == 0 && _i % 100 == 1) { return ONE; } if (_v == 0 && _i % 100 == 2) { return TWO; } if (_v == 0 && _i % 100 >= 3 && _i % 100 <= 4 || _v != 0) { return FEW; } return OTHER; } PluralCase _lt_rule() { if (_n % 10 == 1 && (_n % 100 < 11 || _n % 100 > 19)) { return ONE; } if (_n % 10 >= 2 && _n % 10 <= 9 && (_n % 100 < 11 || _n % 100 > 19)) { return FEW; } if (_f != 0) { return MANY; } return OTHER; } PluralCase _en_rule() { if (_i == 1 && _v == 0) { return ONE; } return OTHER; } PluralCase _ak_rule() { if (_n >= 0 && _n <= 1) { return ONE; } return OTHER; } /// Selected Plural rules by locale. final pluralRules = { 'af': _es_rule, 'am': _hi_rule, 'ar': _ar_rule, 'az': _es_rule, 'be': _be_rule, 'bg': _es_rule, 'bn': _hi_rule, 'br': _br_rule, 'bs': _sr_rule, 'ca': _en_rule, 'chr': _es_rule, 'cs': _cs_rule, 'cy': _cy_rule, 'da': _da_rule, 'de': _en_rule, 'de_AT': _en_rule, 'de_CH': _en_rule, 'el': _es_rule, 'en': _en_rule, 'en_AU': _en_rule, 'en_CA': _en_rule, 'en_GB': _en_rule, 'en_IE': _en_rule, 'en_IN': _en_rule, 'en_SG': _en_rule, 'en_US': _en_rule, 'en_ZA': _en_rule, 'es': _es_rule, 'es_419': _es_rule, 'es_ES': _es_rule, 'es_MX': _es_rule, 'es_US': _es_rule, 'et': _en_rule, 'eu': _es_rule, 'fa': _hi_rule, 'fi': _en_rule, 'fil': _fil_rule, 'fr': _fr_rule, 'fr_CA': _fr_rule, 'ga': _ga_rule, 'gl': _en_rule, 'gsw': _es_rule, 'gu': _hi_rule, 'haw': _es_rule, 'he': _he_rule, 'hi': _hi_rule, 'hr': _sr_rule, 'hu': _es_rule, 'hy': _fr_rule, 'id': _default_rule, 'in': _default_rule, 'is': _is_rule, 'it': _en_rule, 'iw': _he_rule, 'ja': _default_rule, 'ka': _es_rule, 'kk': _es_rule, 'km': _default_rule, 'kn': _hi_rule, 'ko': _default_rule, 'ky': _es_rule, 'ln': _ak_rule, 'lo': _default_rule, 'lt': _lt_rule, 'lv': _lv_rule, 'mk': _mk_rule, 'ml': _es_rule, 'mn': _es_rule, 'mo': _ro_rule, 'mr': _hi_rule, 'ms': _default_rule, 'mt': _mt_rule, 'my': _default_rule, 'nb': _es_rule, 'ne': _es_rule, 'nl': _en_rule, 'no': _es_rule, 'no_NO': _es_rule, 'or': _es_rule, 'pa': _ak_rule, 'pl': _pl_rule, 'pt': _pt_rule, 'pt_BR': _pt_rule, 'pt_PT': _pt_PT_rule, 'ro': _ro_rule, 'ru': _ru_rule, 'sh': _sr_rule, 'si': _si_rule, 'sk': _cs_rule, 'sl': _sl_rule, 'sq': _es_rule, 'sr': _sr_rule, 'sr_Latn': _sr_rule, 'sv': _en_rule, 'sw': _en_rule, 'ta': _es_rule, 'te': _es_rule, 'th': _default_rule, 'tl': _fil_rule, 'tr': _es_rule, 'uk': _ru_rule, 'ur': _en_rule, 'uz': _es_rule, 'vi': _default_rule, 'zh': _default_rule, 'zh_CN': _default_rule, 'zh_HK': _default_rule, 'zh_TW': _default_rule, 'zu': _hi_rule, 'default': _default_rule }; /// Do we have plural rules specific to [locale] bool localeHasPluralRules(String locale) => pluralRules.containsKey(locale);
0
mirrored_repositories/easy_localization/lib
mirrored_repositories/easy_localization/lib/src/utils.dart
part of 'easy_localization_app.dart'; /// Convert string locale [localeString] to [Locale] @Deprecated('Deprecated on Easy Localization 3.0') Locale localeFromString(String localeString) { final localeList = localeString.split('_'); switch (localeList.length) { case 2: return localeList.last.length == 4 // scriptCode length is 4 ? Locale.fromSubtags( languageCode: localeList.first, scriptCode: localeList.last, ) : Locale(localeList.first, localeList.last); case 3: return Locale.fromSubtags( languageCode: localeList.first, scriptCode: localeList[1], countryCode: localeList.last, ); default: return Locale(localeList.first); } } /// Convert [locale] to Srting with custom [separator] @Deprecated('Deprecated on Easy Localization 3.0') String localeToString(Locale locale, {String separator = '_'}) { return locale.toString().split('_').join(separator); } /// [Easy Localization] locale helper extension LocaleToStringHelper on Locale { /// Convert [locale] to String with custom separator String toStringWithSeparator({String separator = '_'}) { return toString().split('_').join(separator); } } /// [Easy Localization] string locale helper extension StringToLocaleHelper on String { /// Convert string to [Locale] object Locale toLocale({String separator = '_'}) { final localeList = split(separator); switch (localeList.length) { case 2: return localeList.last.length == 4 // scriptCode length is 4 ? Locale.fromSubtags( languageCode: localeList.first, scriptCode: localeList.last, ) : Locale(localeList.first, localeList.last); case 3: return Locale.fromSubtags( languageCode: localeList.first, scriptCode: localeList[1], countryCode: localeList.last, ); default: return Locale(localeList.first); } } } extension MapExtension<K> on Map<K, dynamic> { void addAllRecursive(Map<K, dynamic> other) { for (final entry in other.entries) { final oldValue = this[entry.key]; final newValue = entry.value; if (oldValue is Map<K, dynamic> && newValue is Map<K, dynamic>) { oldValue.addAllRecursive(newValue); continue; } this[entry.key] = newValue; } } }
0
mirrored_repositories/easy_localization/lib
mirrored_repositories/easy_localization/lib/src/easy_localization_controller.dart
import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/material.dart'; import 'package:intl/intl_standalone.dart' if (dart.library.html) 'package:intl/intl_browser.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'translations.dart'; class EasyLocalizationController extends ChangeNotifier { static Locale? _savedLocale; static late Locale _deviceLocale; late Locale _locale; Locale? _fallbackLocale; final Function(FlutterError e) onLoadError; final AssetLoader assetLoader; final String path; final bool useFallbackTranslations; final bool saveLocale; final bool useOnlyLangCode; List<AssetLoader>? extraAssetLoaders; Translations? _translations, _fallbackTranslations; Translations? get translations => _translations; Translations? get fallbackTranslations => _fallbackTranslations; EasyLocalizationController({ required List<Locale> supportedLocales, required this.useFallbackTranslations, required this.saveLocale, required this.assetLoader, required this.path, required this.useOnlyLangCode, required this.onLoadError, this.extraAssetLoaders, Locale? startLocale, Locale? fallbackLocale, Locale? forceLocale, // used for testing }) { _fallbackLocale = fallbackLocale; if (forceLocale != null) { _locale = forceLocale; } else if (_savedLocale == null && startLocale != null) { _locale = _getFallbackLocale(supportedLocales, startLocale); EasyLocalization.logger('Start locale loaded ${_locale.toString()}'); } // If saved locale then get else if (saveLocale && _savedLocale != null) { EasyLocalization.logger('Saved locale loaded ${_savedLocale.toString()}'); _locale = selectLocaleFrom( supportedLocales, _savedLocale!, fallbackLocale: fallbackLocale, ); } else { // From Device Locale _locale = selectLocaleFrom( supportedLocales, _deviceLocale, fallbackLocale: fallbackLocale, ); } } @visibleForTesting static Locale selectLocaleFrom( List<Locale> supportedLocales, Locale deviceLocale, { Locale? fallbackLocale, }) { final selectedLocale = supportedLocales.firstWhere( (locale) => locale.supports(deviceLocale), orElse: () => _getFallbackLocale(supportedLocales, fallbackLocale), ); return selectedLocale; } //Get fallback Locale static Locale _getFallbackLocale( List<Locale> supportedLocales, Locale? fallbackLocale) { //If fallbackLocale not set then return first from supportedLocales if (fallbackLocale != null) { return fallbackLocale; } else { return supportedLocales.first; } } Future loadTranslations() async { Map<String, dynamic> data; try { data = Map.from(await loadTranslationData(_locale)); _translations = Translations(data); if (useFallbackTranslations && _fallbackLocale != null) { Map<String, dynamic>? baseLangData; if (_locale.countryCode != null && _locale.countryCode!.isNotEmpty) { baseLangData = await loadBaseLangTranslationData(Locale(locale.languageCode)); } data = Map.from(await loadTranslationData(_fallbackLocale!)); if (baseLangData != null) { try { data.addAll(baseLangData); } on UnsupportedError { data = Map.of(data)..addAll(baseLangData); } } _fallbackTranslations = Translations(data); } } on FlutterError catch (e) { onLoadError(e); } catch (e) { onLoadError(FlutterError(e.toString())); } } Future<Map<String, dynamic>?> loadBaseLangTranslationData( Locale locale) async { try { return await loadTranslationData(Locale(locale.languageCode)); } on FlutterError catch (e) { // Disregard asset not found FlutterError when attempting to load base language fallback EasyLocalization.logger.warning(e.message); } return null; } Future<Map<String, dynamic>> loadTranslationData(Locale locale) async => _combineAssetLoaders( path: path, locale: locale, assetLoader: assetLoader, useOnlyLangCode: useOnlyLangCode, extraAssetLoaders: extraAssetLoaders, ); Future<Map<String, dynamic>> _combineAssetLoaders({ required String path, required Locale locale, required AssetLoader assetLoader, required bool useOnlyLangCode, List<AssetLoader>? extraAssetLoaders, }) async { final result = <String, dynamic>{}; final loaderFutures = <Future<Map<String, dynamic>?>>[]; final Locale desiredLocale = useOnlyLangCode ? Locale(locale.languageCode) : locale; List<AssetLoader> loaders = [ assetLoader, if (extraAssetLoaders != null) ...extraAssetLoaders ]; for (final loader in loaders) { loaderFutures.add(loader.load(path, desiredLocale)); } await Future.wait(loaderFutures).then((List<Map<String, dynamic>?> value) { for (final Map<String, dynamic>? map in value) { if (map != null) { result.addAllRecursive(map); } } }); return result; } Locale get locale => _locale; Future<void> setLocale(Locale l) async { _locale = l; await loadTranslations(); notifyListeners(); EasyLocalization.logger('Locale $locale changed'); await _saveLocale(_locale); } Future<void> _saveLocale(Locale? locale) async { if (!saveLocale) return; final preferences = await SharedPreferences.getInstance(); await preferences.setString('locale', locale.toString()); EasyLocalization.logger('Locale $locale saved'); } static Future<void> initEasyLocation() async { final preferences = await SharedPreferences.getInstance(); final strLocale = preferences.getString('locale'); _savedLocale = strLocale?.toLocale(); final foundPlatformLocale = await findSystemLocale(); _deviceLocale = foundPlatformLocale.toLocale(); EasyLocalization.logger.debug('Localization initialized'); } Future<void> deleteSaveLocale() async { _savedLocale = null; final preferences = await SharedPreferences.getInstance(); await preferences.remove('locale'); EasyLocalization.logger('Saved locale deleted'); } Locale get deviceLocale => _deviceLocale; Future<void> resetLocale() async { EasyLocalization.logger('Reset locale to platform locale $_deviceLocale'); await setLocale(_deviceLocale); } } @visibleForTesting extension LocaleExtension on Locale { bool supports(Locale locale) { if (this == locale) { return true; } if (languageCode != locale.languageCode) { return false; } if (countryCode != null && countryCode!.isNotEmpty && countryCode != locale.countryCode) { return false; } if (scriptCode != null && scriptCode != locale.scriptCode) { return false; } return true; } }
0
mirrored_repositories/easy_localization/lib
mirrored_repositories/easy_localization/lib/src/translations.dart
class Translations { final Map<String, dynamic>? _translations; final Map<String?, dynamic> _nestedKeysCache; Translations(this._translations) : _nestedKeysCache = {}; String? get(String key) { String? returnValue; /// Try to look it up as a nested key if (isNestedKey(key)) { returnValue = getNested(key); } /// If we failed to find the key as a nested key, then fall back /// to looking it up like normal. returnValue ??= _translations?[key]; return returnValue; } String? getNested(String key) { if (isNestedCached(key)) return _nestedKeysCache[key]; final keys = key.split('.'); final kHead = keys.first; var value = _translations![kHead]; // print(value); for (var i = 1; i < keys.length; i++) { if (value is Map<String, dynamic>) value = value[keys[i]]; } /// If we found the value, cache it. If the value is null then /// we're not going to cache it, and returning null instead. if (value != null) { cacheNestedKey(key, value); } return value; } // bool has(String key) => isNestedKey(key) // ? getNested(key) != null // : _translations.containsKey(key); bool isNestedCached(String key) => _nestedKeysCache.containsKey(key); void cacheNestedKey(String key, String value) { if (!isNestedKey(key)) { throw Exception('Cannot cache a key that is not nested.'); } _nestedKeysCache[key] = value; } bool isNestedKey(String key) => !_translations!.containsKey(key) && key.contains('.'); }
0
mirrored_repositories/easy_localization
mirrored_repositories/easy_localization/test/easy_localization_test.dart
import 'dart:developer'; import 'package:easy_localization/easy_localization.dart'; import 'package:easy_localization/src/easy_localization_controller.dart'; import 'package:easy_localization/src/localization.dart'; import 'package:easy_logger/easy_logger.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'easy_localization_utils_test.dart'; import 'utils/test_asset_loaders.dart'; void main() { group('localization', () { var r1 = EasyLocalizationController( forceLocale: const Locale('en'), path: 'path/en.json', supportedLocales: const [Locale('en')], useOnlyLangCode: true, useFallbackTranslations: false, saveLocale: false, onLoadError: (FlutterError e) { log(e.toString()); }, assetLoader: const JsonAssetLoader()); var r2 = EasyLocalizationController( forceLocale: const Locale('en', 'us'), supportedLocales: const [Locale('en', 'us')], path: 'path/en-us.json', useOnlyLangCode: false, useFallbackTranslations: false, onLoadError: (FlutterError e) { log(e.toString()); }, saveLocale: false, assetLoader: const JsonAssetLoader()); setUpAll(() async { EasyLocalization.logger.enableLevels = <LevelMessages>[ LevelMessages.error, LevelMessages.warning, ]; await r1.loadTranslations(); await r2.loadTranslations(); Localization.load(const Locale('en'), translations: r1.translations); }); test('is a localization object', () { expect(Localization.instance, isInstanceOf<Localization>()); }); test('is a singleton', () { expect(Localization.instance, Localization.instance); }); test('is a localization object', () { expect(Localization.instance, isInstanceOf<Localization>()); }); test('load() succeeds', () async { expect( Localization.load(const Locale('en'), translations: r1.translations), true); }); test('load() with fallback succeeds', () async { expect( Localization.load(const Locale('en'), translations: r1.translations, fallbackTranslations: r2.translations), true); }); test('merge fallbackLocale with locale without country code succeeds', () async { await EasyLocalizationController( forceLocale: const Locale('es', 'AR'), supportedLocales: const [ Locale('en'), Locale('es'), Locale('es', 'AR') ], path: 'path/en-us.json', useOnlyLangCode: false, useFallbackTranslations: true, fallbackLocale: const Locale('en'), onLoadError: (FlutterError e) { throw e; }, saveLocale: false, assetLoader: const ImmutableJsonAssetLoader(), ).loadTranslations(); }); test('localeFromString() succeeds', () async { expect(const Locale('ar'), 'ar'.toLocale()); expect(const Locale('ar', 'DZ'), 'ar_DZ'.toLocale()); expect(const Locale.fromSubtags(languageCode: 'ar', scriptCode: 'Arab'), 'ar_Arab'.toLocale()); expect( const Locale.fromSubtags( languageCode: 'ar', scriptCode: 'Arab', countryCode: 'DZ'), 'ar_Arab_DZ'.toLocale()); }); test('load() Failed assertion', () async { try { Localization.load(const Locale('en'), translations: null); } on AssertionError catch (e) { // throw AssertionError('Expected ArgumentError'); expect(e, isAssertionError); } }); test('load() correctly sets locale path', () async { expect( Localization.load(const Locale('en'), translations: r1.translations), true); expect(Localization.instance.tr('path'), 'path/en.json'); }); test('load() respects useOnlyLangCode', () async { expect( Localization.load(const Locale('en'), translations: r1.translations), true); expect(Localization.instance.tr('path'), 'path/en.json'); expect( Localization.load(const Locale('en', 'us'), translations: r2.translations), true); expect(Localization.instance.tr('path'), 'path/en-us.json'); }); test('controller loads saved locale', () async { SharedPreferences.setMockInitialValues({ 'locale': 'en', }); await EasyLocalization.ensureInitialized(); final controller = EasyLocalizationController( supportedLocales: const [Locale('en'), Locale('fb')], fallbackLocale: const Locale('fb'), path: 'path', useOnlyLangCode: true, useFallbackTranslations: true, onLoadError: (FlutterError e) { log(e.toString()); }, saveLocale: true, assetLoader: const JsonAssetLoader(), ); expect(controller.locale, const Locale('en')); SharedPreferences.setMockInitialValues({}); }); /// E.g. if user saved a locale that was removed in a later version test('controller loads fallback if saved locale is not supported', () async { SharedPreferences.setMockInitialValues({ 'locale': 'de', }); await EasyLocalization.ensureInitialized(); final controller = EasyLocalizationController( supportedLocales: const [Locale('en'), Locale('fb')], fallbackLocale: const Locale('fb'), path: 'path', useOnlyLangCode: true, useFallbackTranslations: true, onLoadError: (FlutterError e) { log(e.toString()); }, saveLocale: true, assetLoader: const JsonAssetLoader(), ); expect(controller.locale, const Locale('fb')); SharedPreferences.setMockInitialValues({}); }); group('locale', () { test('locale supports device locale', () { const en = Locale('en'); const en2 = Locale('en', ''); const enUS = Locale('en', 'US'); const enGB = Locale('en', 'GB'); expect(en.supports(enUS), isTrue); expect(en2.supports(enUS), isTrue); expect(enUS.supports(enUS), isTrue); expect(enGB.supports(enUS), isFalse); const zh = Locale('zh', ''); const zh2 = Locale('zh', ''); const zhCN = Locale('zh', 'CN'); const zhHans = Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hans'); const zhHant = Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hant'); const zhHansCN = Locale.fromSubtags( languageCode: 'zh', scriptCode: 'Hans', countryCode: 'CN'); expect(zh.supports(zhHansCN), isTrue); expect(zh2.supports(zhHansCN), isTrue); expect(zhCN.supports(zhHansCN), isTrue); expect(zhHans.supports(zhHansCN), isTrue); expect(zhHant.supports(zhHansCN), isFalse); expect(zhHansCN.supports(zhHansCN), isTrue); }); test('select locale from device locale', () { const en = Locale('en', ''); const zh = Locale('zh', ''); const zhHans = Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hans'); const zhHant = Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hant'); const zhHansCN = Locale.fromSubtags( languageCode: 'zh', scriptCode: 'Hans', countryCode: 'CN'); expect( EasyLocalizationController.selectLocaleFrom([en, zh], zhHansCN), zh, ); expect( EasyLocalizationController.selectLocaleFrom( [zhHant, zhHans], zhHansCN), zhHans, ); }); }); group('tr', () { var r = EasyLocalizationController( forceLocale: const Locale('en'), supportedLocales: const [Locale('en'), Locale('fb')], fallbackLocale: const Locale('fb'), path: 'path', useOnlyLangCode: true, useFallbackTranslations: true, onLoadError: (FlutterError e) { log(e.toString()); }, saveLocale: false, assetLoader: const JsonAssetLoader()); setUpAll(() async { await r.loadTranslations(); Localization.load(const Locale('en'), translations: r.translations, fallbackTranslations: r.fallbackTranslations); }); test('finds and returns resource', () { expect(Localization.instance.tr('test'), 'test'); }); test('can resolve resource in any nest level', () { expect( Localization.instance.tr('nested.super.duper.nested'), 'nested.super.duper.nested', ); }); test('can resolve resource that has a key with dots', () { expect( Localization.instance.tr('nested.but.not.nested'), 'nested but not nested', ); }); test('won\'t fail for missing key (no periods)', () { expect( Localization.instance.tr('Processing'), 'Processing', ); }); test('won\'t fail for missing key with periods', () { expect( Localization.instance.tr('Processing.'), 'Processing.', ); }); test('can resolve linked locale messages', () { expect(Localization.instance.tr('linked'), 'this is linked'); }); test('can resolve linked locale messages and apply modifiers', () { expect(Localization.instance.tr('linkAndModify'), 'this is linked and MODIFIED'); }); test('can resolve multiple linked locale messages and apply modifiers', () { expect(Localization.instance.tr('linkMany'), 'many Locale messages'); }); test('can resolve linked locale messages with brackets', () { expect(Localization.instance.tr('linkedWithBrackets'), 'linked with brackets.'); }); test('can resolve any number of nested arguments', () { expect( Localization.instance .tr('nestedArguments', args: ['a', 'argument', '!']), 'this is a nested argument!'); }); test('can resolve nested named arguments', () { expect( Localization.instance.tr('nestedNamedArguments', namedArgs: { 'firstArg': 'this', 'secondArg': 'named argument', 'thirdArg': '!' }), 'this is a nested named argument!'); }); test('returns missing resource as provided', () { expect(Localization.instance.tr('test_missing'), 'test_missing'); }); test('reports missing resource', overridePrint(() { printLog = []; expect(Localization.instance.tr('test_missing'), 'test_missing'); final logIterator = printLog.iterator; logIterator.moveNext(); expect(logIterator.current, contains('Localization key [test_missing] not found')); logIterator.moveNext(); expect(logIterator.current, contains('Fallback localization key [test_missing] not found')); })); test('uses fallback translations', overridePrint(() { printLog = []; expect(Localization.instance.tr('test_missing_fallback'), 'fallback!'); })); test('reports missing resource with fallback', overridePrint(() { printLog = []; expect(Localization.instance.tr('test_missing_fallback'), 'fallback!'); expect(printLog.first, contains('Localization key [test_missing_fallback] not found')); })); test('returns resource and replaces argument', () { expect( Localization.instance.tr('test_replace_one', args: ['one']), 'test replace one', ); }); test('returns resource and replaces argument in any nest level', () { expect( Localization.instance .tr('nested.super.duper.nested_with_arg', args: ['what a nest']), 'nested.super.duper.nested_with_arg what a nest', ); }); test('returns resource and replaces argument sequentially', () { expect( Localization.instance.tr('test_replace_two', args: ['one', 'two']), 'test replace one two', ); }); test( 'should raise exception if provided arguments length is different from the count of {} in the resource', () { // @TODO }); test('return resource and replaces named argument', () { expect( Localization.instance.tr('test_replace_named', namedArgs: {'arg1': 'one', 'arg2': 'two'}), 'test named replace one two', ); }); test('returns resource and replaces named argument in any nest level', () { expect( Localization.instance.tr('nested.super.duper.nested_with_named_arg', namedArgs: {'arg': 'what a nest'}), 'nested.super.duper.nested_with_named_arg what a nest', ); }); test('gender returns the correct resource', () { expect( Localization.instance.tr('gender', gender: 'male'), 'Hi man ;)', ); expect( Localization.instance.tr('gender', gender: 'female'), 'Hello girl :)', ); }); test('gender returns the correct resource and replaces args', () { expect( Localization.instance .tr('gender_and_replace', gender: 'male', args: ['one']), 'Hi one man ;)', ); expect( Localization.instance .tr('gender_and_replace', gender: 'female', args: ['one']), 'Hello one girl :)', ); }); }); group('plural', () { var r = EasyLocalizationController( forceLocale: const Locale('fb'), supportedLocales: [const Locale('fb')], fallbackLocale: const Locale('fb'), path: 'path', useOnlyLangCode: true, useFallbackTranslations: true, onLoadError: (FlutterError e) { log(e.toString()); }, saveLocale: false, assetLoader: const JsonAssetLoader()); setUpAll(() async { await r.loadTranslations(); Localization.load(const Locale('fb'), translations: r.translations, fallbackTranslations: r.fallbackTranslations); }); test('zero', () { expect(Localization.instance.plural('hat', 0), 'no hats'); }); test('one', () { expect(Localization.instance.plural('hat', 1), 'one hat'); }); test('two', () { expect(Localization.instance.plural('hat', 2), 'two hats'); }); test('few', () { // @TODO not sure how this works }); test('many', () { // @TODO not sure how this works }); test('other', () { expect(Localization.instance.plural('hat', -1), 'other hats'); }); test('other as fallback', () { expect(Localization.instance.plural('hat_other', 1), 'other hats'); }); test('two as fallback and fallback translations priority', overridePrint(() { printLog = []; expect( Localization.instance.plural('test_fallback_plurals', 2), 'fallback two', ); expect(printLog, isEmpty); })); test('with number format', () { expect( Localization.instance .plural('day', 3, format: NumberFormat.currency()), 'USD3.00 other days'); }); test('zero with args', () { expect(Localization.instance.plural('money', 0, args: ['John', '0']), 'John has no money'); }); test('one with args', () { expect(Localization.instance.plural('money', 1, args: ['John', '1']), 'John has 1 dollar'); }); test('other with args', () { expect(Localization.instance.plural('money', 3, args: ['John', '3']), 'John has 3 dollars'); }); test('zero with named args', () { expect( Localization.instance.plural('money_named_args', 0, namedArgs: {'name': 'John', 'money': '0'}), 'John has no money', ); }); test('one with named args', () { expect( Localization.instance.plural('money_named_args', 1, namedArgs: {'name': 'John', 'money': '1'}), 'John has 1 dollar', ); }); test('other with named args', () { expect( Localization.instance.plural('money_named_args', 3, namedArgs: {'name': 'John', 'money': '3'}), 'John has 3 dollars', ); }); test('named args and value name', () { expect( Localization.instance.plural('money_named_args', 3, namedArgs: {'name': 'John'}, name: 'money'), 'John has 3 dollars', ); }); }); group('extensions', () { // setUpAll(() async { // await Localization.load(Locale('en'), // path: 'path', // useOnlyLangCode: true, // assetLoader: JsonAssetLoader()); // }); group('string', () { test('tr', () { expect('test'.tr(), 'test'); }); test('trExists', () { expect('test'.trExists(), true); expect('xyz'.trExists(), false); }); test('plural', () { expect('day'.plural(0), '0 days'); }); }); }); group('extensions', () { // setUpAll(() async { // await Localization.load(Locale('en'), // path: 'path', // useOnlyLangCode: true, // assetLoader: JsonAssetLoader()); // }); group('string', () { test('tr', () { expect(tr('test'), 'test'); }); test('plural', () { expect(plural('day', 0), '0 days'); }); }); }); }); }
0
mirrored_repositories/easy_localization
mirrored_repositories/easy_localization/test/easy_localization_context_test.dart
import 'dart:io'; import 'package:easy_localization/easy_localization.dart'; import 'package:easy_logger/easy_logger.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:shared_preferences/shared_preferences.dart'; late BuildContext _context; class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( locale: context.locale, supportedLocales: context.supportedLocales, localizationsDelegates: context.localizationDelegates, home: const MyWidget(), ); } } class MyWidget extends StatelessWidget { const MyWidget({Key? key}) : super(key: key); @override Widget build(context) { _context = context; return Scaffold( body: Column( children: <Widget>[ const Text('test').tr(), const Text('day').plural(1), ], ), ); } } void main() async { EasyLocalization.logger.enableLevels = <LevelMessages>[ LevelMessages.error, LevelMessages.warning, ]; SharedPreferences.setMockInitialValues({}); EasyLocalization.logger.enableLevels = <LevelMessages>[ LevelMessages.error, LevelMessages.warning, ]; await EasyLocalization.ensureInitialized(); group('BuildContext', () { testWidgets( '[EasyLocalization] _getFallbackLocale() fallbackLocale!=null test', (WidgetTester tester) async { await tester.runAsync(() async { await tester.pumpWidget(EasyLocalization( path: '../../i18n', saveLocale: false, useOnlyLangCode: true, supportedLocales: const [Locale('ar')], fallbackLocale: const Locale('ar'), child: const MyApp(), )); // await tester.idle(); // The async delegator load will require build on the next frame. Thus, pump await tester.pump(); expect(_context.supportedLocales, [const Locale('ar')]); expect(_context.locale, const Locale('ar')); expect(_context.fallbackLocale, const Locale('ar')); }); }, ); testWidgets( '[EasyLocalization] _getFallbackLocale() fallbackLocale==null test', (WidgetTester tester) async { await tester.runAsync(() async { await tester.pumpWidget(EasyLocalization( path: '../../i18n', saveLocale: false, useOnlyLangCode: true, // fallbackLocale:Locale('en') , supportedLocales: const [ Locale('ar') ], // Locale('en', 'US'), Locale('ar','DZ') child: const MyApp(), )); // await tester.idle(); // The async delegator load will require build on the next frame. Thus, pump await tester.pump(); expect(_context.supportedLocales, [const Locale('ar')]); expect(_context.locale, const Locale('ar')); expect(_context.fallbackLocale, null); }); }, ); group('SharedPreferences deleteSaveLocale()', () { setUpAll(() async { SharedPreferences.setMockInitialValues({ 'locale': 'ar_DZ', }); await EasyLocalization.ensureInitialized(); }); testWidgets( '[EasyLocalization] deleteSaveLocale test', (WidgetTester tester) async { await tester.runAsync(() async { await tester.pumpWidget(EasyLocalization( path: '../../i18n', // fallbackLocale:Locale('en') , supportedLocales: const [ Locale('en', 'US'), Locale('ar', 'DZ') ], // Locale('en', 'US'), Locale('ar','DZ') child: const MyApp(), )); // await tester.idle(); // The async delegator load will require build on the next frame. Thus, pump await tester.pump(); expect(_context.locale, const Locale('ar', 'DZ')); await _context.deleteSaveLocale(); }); }, ); testWidgets( '[EasyLocalization] after deleteSaveLocale test', (WidgetTester tester) async { await tester.runAsync(() async { await tester.pumpWidget(EasyLocalization( path: '../../i18n', // fallbackLocale:Locale('en') , supportedLocales: const [ Locale('en', 'US'), Locale('ar', 'DZ') ], // Locale('en', 'US'), Locale('ar','DZ') child: const MyApp(), )); // await tester.idle(); // The async delegator load will require build on the next frame. Thus, pump await tester.pump(); expect(_context.locale, const Locale('en', 'US')); }); }, ); testWidgets( '[EasyLocalization] device locale test', (WidgetTester tester) async { await tester.runAsync(() async { await tester.pumpWidget(EasyLocalization( path: '../../i18n', supportedLocales: const [ Locale('en', 'US'), Locale('ar', 'DZ') ], // Locale('en', 'US'), Locale('ar','DZ') child: const MyApp(), )); // await tester.idle(); // The async delegator load will require build on the next frame. Thus, pump await tester.pump(); expect(_context.deviceLocale.toString(), Platform.localeName); }); }, ); testWidgets( '[EasyLocalization] reset device locale test', (WidgetTester tester) async { await tester.runAsync(() async { await tester.pumpWidget(EasyLocalization( path: '../../i18n', supportedLocales: const [ Locale('en', 'US'), Locale('ar', 'DZ') ], // Locale('en', 'US'), Locale('ar','DZ') startLocale: const Locale('ar', 'DZ'), child: const MyApp(), )); // await tester.idle(); // The async delegator load will require build on the next frame. Thus, pump await tester.pump(); expect(_context.locale, const Locale('ar', 'DZ')); // reset to device locale await _context.resetLocale(); await tester.pump(); expect(_context.locale, const Locale('en', 'US')); }); }, ); testWidgets( '[EasyLocalization] device locale test', (WidgetTester tester) async { await tester.runAsync(() async { await tester.pumpWidget(EasyLocalization( path: '../../i18n', supportedLocales: const [ Locale('en', 'US'), Locale('ar', 'DZ') ], // Locale('en', 'US'), Locale('ar','DZ') child: const MyApp(), )); await tester.idle(); // The async delegator load will require build on the next frame. Thus, pump await tester.pumpAndSettle(); expect(_context.deviceLocale.toString(), Platform.localeName); }); }, ); testWidgets( '[EasyLocalization] reset device locale test', (WidgetTester tester) async { await tester.runAsync(() async { await tester.pumpWidget(EasyLocalization( path: '../../i18n', supportedLocales: const [ Locale('en', 'US'), Locale('ar', 'DZ') ], // Locale('en', 'US'), Locale('ar','DZ') startLocale: const Locale('ar', 'DZ'), child: const MyApp(), )); await tester.idle(); // The async delegator load will require build on the next frame. Thus, pump await tester.pumpAndSettle(); expect(_context.locale, const Locale('ar', 'DZ')); // reset to device locale await _context.resetLocale(); await tester.pumpAndSettle(); expect(_context.locale, const Locale('en', 'US')); }); }, ); }); }); }
0
mirrored_repositories/easy_localization
mirrored_repositories/easy_localization/test/easy_localization_extra_asset_loaders_test.dart
import 'dart:developer'; import 'package:easy_localization/src/easy_localization_controller.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'utils/test_asset_loaders.dart'; void main() { group('ExtraAssetLoaders', () { test('should work normal if no extraAssetLoaders is provided', () async { final EasyLocalizationController controller = EasyLocalizationController( forceLocale: const Locale('en'), path: 'path/en.json', supportedLocales: const [Locale('en')], useOnlyLangCode: true, useFallbackTranslations: false, saveLocale: false, onLoadError: (FlutterError e) { log(e.toString()); }, assetLoader: const ImmutableJsonAssetLoader(), extraAssetLoaders: null, ); var result = await controller.loadTranslationData(const Locale('en')); expect(result, {'test': 'test'}); expect(result.entries.length, 1); }); test('load assets from external loader and merge with asset loader', () async { final EasyLocalizationController controller = EasyLocalizationController( forceLocale: const Locale('en'), path: 'path/en.json', supportedLocales: const [Locale('en')], useOnlyLangCode: true, useFallbackTranslations: false, saveLocale: false, onLoadError: (FlutterError e) { log(e.toString()); }, assetLoader: const ImmutableJsonAssetLoader(), extraAssetLoaders: [const ExternalAssetLoader()], ); final Map<String, dynamic> result = await controller.loadTranslationData(const Locale('en')); expect(result, { 'test': 'test', 'package_value_01': 'package_value_01', 'package_value_02': 'package_value_02', 'package_value_03': 'package_value_03', }); expect(result.entries.length, 4); }); test( 'load assets from external loader with nested translations and merge with asset loader', () async { final EasyLocalizationController controller = EasyLocalizationController( forceLocale: const Locale('en'), path: 'path/en.json', supportedLocales: const [Locale('en')], useOnlyLangCode: true, useFallbackTranslations: false, saveLocale: false, onLoadError: (FlutterError e) { log(e.toString()); }, assetLoader: const ImmutableJsonAssetLoader(), extraAssetLoaders: [const NestedAssetLoader()], ); final Map<String, dynamic> result = await controller.loadTranslationData(const Locale('en')); expect(result, { 'test': 'test', 'nested': { 'super': { 'duper': { 'nested': 'nested.super.duper.nested', } } }, }); expect(result.entries.length, 2); }); test( 'load assets from external loader and merge duplicates with asset loader', () async { final EasyLocalizationController controller = EasyLocalizationController( forceLocale: const Locale('en'), path: 'path/en.json', supportedLocales: const [Locale('en')], useOnlyLangCode: true, useFallbackTranslations: false, saveLocale: false, onLoadError: (FlutterError e) { log(e.toString()); }, assetLoader: const ImmutableJsonAssetLoader(), extraAssetLoaders: [const ImmutableJsonAssetLoader()], ); final Map<String, dynamic> result = await controller.loadTranslationData(const Locale('en')); expect(result, {'test': 'test'}); expect(result.entries.length, 1); }); }); }
0
mirrored_repositories/easy_localization
mirrored_repositories/easy_localization/test/easy_localization_utils_test.dart
import 'dart:async'; import 'package:easy_localization/easy_localization.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; var printLog = []; dynamic overridePrint(Function() testFn) => () { var spec = ZoneSpecification(print: (_, __, ___, String msg) { // Add to log instead of printing to stdout printLog.add(msg); }); return Zone.current.fork(specification: spec).run(testFn); }; void main() { group('Utils', () { group('Locales', () { test('localeFromString only language code', () { var locale = 'en'.toLocale(); expect(locale, const Locale('en')); }); test('localeFromString language code and country code', () { var locale = 'en_US'.toLocale(); expect(locale, const Locale('en', 'US')); }); test('localeFromString language code and script code', () { var locale = 'zh_Hant'.toLocale(); expect(locale, const Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hant')); }); test('localeFromString language, country, script code', () { var locale = 'zh_Hant_HK'.toLocale(); expect( locale, const Locale.fromSubtags( languageCode: 'zh', scriptCode: 'Hant', countryCode: 'HK')); }); test('localeToString', () { var locale = const Locale.fromSubtags( languageCode: 'zh', scriptCode: 'Hant', countryCode: 'HK'); var string = locale.toStringWithSeparator(); expect(string, 'zh_Hant_HK'); }); test('localeToString custom separator', () { var locale = const Locale.fromSubtags( languageCode: 'zh', scriptCode: 'Hant', countryCode: 'HK'); var string = locale.toStringWithSeparator(separator: '|'); expect(string, 'zh|Hant|HK'); }); }); group('MapExtension', () { test('should add all key value pairs recursively', () { final Map<String, dynamic> map1 = { 'key1': 'value1', 'key2': { 'key3': 'value3', 'key4': 'value4', }, }; final Map<String, dynamic> map2 = { 'key2': { 'key4': 'new_value4', 'key5': 'value5', }, 'key6': 'value6', }; map1.addAllRecursive(map2); expect(map1, { 'key1': 'value1', 'key2': { 'key3': 'value3', 'key4': 'new_value4', 'key5': 'value5', }, 'key6': 'value6', }); }); test('should work with empty maps', () { final Map<String, dynamic> map1 = {}; final Map<String, dynamic> map2 = { 'key1': 'value1', 'key2': { 'key3': 'value3', 'key4': 'value4', }, }; map1.addAllRecursive(map2); expect(map1, { 'key1': 'value1', 'key2': { 'key3': 'value3', 'key4': 'value4', }, }); }); }); }); }
0
mirrored_repositories/easy_localization
mirrored_repositories/easy_localization/test/easy_localization_logger_test.dart
import 'package:easy_localization/easy_localization.dart'; import 'package:easy_logger/easy_logger.dart'; import 'package:flutter_test/flutter_test.dart'; import 'easy_localization_utils_test.dart'; void main() async { group('Logger testing', () { test('Logger enable', () { expect(EasyLocalization.logger, equals(EasyLocalization.logger)); expect(EasyLocalization.logger, isNotNull); }); test('Logger print', overridePrint(() { printLog = []; EasyLocalization.logger('Same print'); expect(printLog.first, contains('Same print')); expect(printLog.first, contains(EasyLocalization.logger.name)); })); test('Logger print info', overridePrint(() { printLog = []; EasyLocalization.logger('print info', level: LevelMessages.info); expect(printLog.first, contains('print info')); expect(printLog.first, contains('[INFO]')); })); test('Logger print debug', overridePrint(() { printLog = []; EasyLocalization.logger('print debug', level: LevelMessages.debug); expect(printLog.first, contains('print debug')); expect(printLog.first, contains('[DEBUG]')); })); test('Logger print warning', overridePrint(() { printLog = []; EasyLocalization.logger('print warning', level: LevelMessages.warning); expect(printLog.first, contains('print warning')); expect(printLog.first, contains('[WARNING]')); })); test('Logger print error', overridePrint(() { printLog = []; EasyLocalization.logger('print error', level: LevelMessages.error); expect(printLog.first, contains('print error')); expect(printLog.first, contains('[ERROR]')); })); test('Logger print error with StackTrace', overridePrint(() { printLog = []; StackTrace testStackTrace; testStackTrace = StackTrace.fromString('test stack'); EasyLocalization.logger('print error', level: LevelMessages.error, stackTrace: testStackTrace); expect(printLog.first, contains('print error')); expect(printLog.first, contains('[ERROR]')); expect(printLog.last, contains('test stack')); })); }); }
0
mirrored_repositories/easy_localization
mirrored_repositories/easy_localization/test/easy_localization_widget_test.dart
import 'dart:io'; import 'package:easy_localization/easy_localization.dart'; import 'package:easy_localization/src/exceptions.dart'; import 'package:easy_localization/src/localization.dart'; import 'package:easy_logger/easy_logger.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'utils/test_asset_loaders.dart'; late BuildContext _context; late String _contextTranslationValue; late String _contextPluralValue; class MyApp extends StatelessWidget { const MyApp({ this.child = const MyWidget(), Key? key, }) : super(key: key); final Widget child; @override Widget build(BuildContext context) { return MaterialApp( locale: EasyLocalization.of(context)!.locale, supportedLocales: EasyLocalization.of(context)!.supportedLocales, localizationsDelegates: EasyLocalization.of(context)!.delegates, home: child, ); } } class MyWidget extends StatelessWidget { const MyWidget({Key? key}) : super(key: key); @override Widget build(context) { _context = context; return Scaffold( body: Column( children: <Widget>[ const Text('test').tr(), const Text('day').plural(1), ], ), ); } } class MyLocalizedWidget extends StatelessWidget { const MyLocalizedWidget({Key? key}) : super(key: key); @override Widget build(context) { _context = context; _contextTranslationValue = context.tr('test'); _contextPluralValue = context.plural('day', 1); return Scaffold( body: Column( children: <Widget>[ Text(_contextTranslationValue), Text(_contextPluralValue), ], ), ); } } void main() async { SharedPreferences.setMockInitialValues({}); EasyLocalization.logger.enableLevels = <LevelMessages>[ LevelMessages.error, LevelMessages.warning, ]; await EasyLocalization.ensureInitialized(); testWidgets( '[EasyLocalization with JsonAssetLoader] test', (WidgetTester tester) async { await tester.runAsync(() async { await tester.pumpWidget(EasyLocalization( path: 'path', supportedLocales: const [Locale('en', 'US')], assetLoader: const JsonAssetLoader(), child: const MyApp(), )); // await tester.idle(); // The async delegator load will require build on the next frame. Thus, pump await tester.pump(); expect(Localization.of(_context), isInstanceOf<Localization>()); expect(Localization.instance, isInstanceOf<Localization>()); expect(Localization.instance, Localization.of(_context)); expect(EasyLocalization.of(_context)!.supportedLocales, [const Locale('en', 'US')]); expect(EasyLocalization.of(_context)!.locale, const Locale('en', 'US')); final trFinder = find.text('test'); expect(trFinder, findsOneWidget); final pluralFinder = find.text('1 day'); expect(pluralFinder, findsOneWidget); expect(tr('test'), 'test'); expect('test'.tr(), 'test'); }); }, ); testWidgets( '[EasyLocalization with RootBundleAssetLoader] test', (WidgetTester tester) async { await tester.runAsync(() async { await tester.pumpWidget(EasyLocalization( path: '../../i18n', assetLoader: const RootBundleAssetLoader(), supportedLocales: const [Locale('en', 'US')], child: const MyApp(), )); // await tester.idle(); // The async delegator load will require build on the next frame. Thus, pump await tester.pump(); expect(EasyLocalization.of(_context)!.supportedLocales, [const Locale('en', 'US')]); expect(EasyLocalization.of(_context)!.locale, const Locale('en', 'US')); final trFinder = find.text('test'); expect(trFinder, findsOneWidget); final pluralFinder = find.text('1 day'); expect(pluralFinder, findsOneWidget); expect(tr('test'), 'test'); }); }, ); testWidgets( '[EasyLocalization with Default AssetLoader] test', (WidgetTester tester) async { await tester.runAsync(() async { await tester.pumpWidget(EasyLocalization( path: '../../i18n', supportedLocales: const [Locale('en', 'US')], child: const MyApp(), )); // await tester.idle(); // The async delegator load will require build on the next frame. Thus, pump await tester.pump(); expect(EasyLocalization.of(_context)!.supportedLocales, [const Locale('en', 'US')]); expect(EasyLocalization.of(_context)!.locale, const Locale('en', 'US')); final trFinder = find.text('test'); expect(trFinder, findsOneWidget); final pluralFinder = find.text('1 day'); expect(pluralFinder, findsOneWidget); expect(tr('test'), 'test'); }); }, ); testWidgets( '[EasyLocalization with Error path] test', (WidgetTester tester) async { await tester.runAsync(() async { await tester.pumpWidget(EasyLocalization( path: 'i18', supportedLocales: const [Locale('en', 'US')], child: const MyApp(), )); // await tester.idle(); // The async delegator load will require build on the next frame. Thus, pump await tester.pump(); final trFinder = find.byWidgetPredicate((widget) => widget is ErrorWidget); expect(trFinder, findsOneWidget); await tester.pump(); }); }, ); testWidgets( '[EasyLocalization] change loacle test', (WidgetTester tester) async { await tester.runAsync(() async { await tester.pumpWidget(EasyLocalization( path: '../../i18n', supportedLocales: const [Locale('en', 'US')], child: const MyApp(), )); // await tester.idle(); // The async delegator load will require build on the next frame. Thus, pump await tester.pump(); expect(EasyLocalization.of(_context)!.supportedLocales, [const Locale('en', 'US')]); expect(EasyLocalization.of(_context)!.locale, const Locale('en', 'US')); var l = const Locale('en', 'US'); await EasyLocalization.of(_context)!.setLocale(l); await tester.pump(); expect(EasyLocalization.of(_context)!.locale, const Locale('en', 'US')); final trFinder = find.text('test'); expect(trFinder, findsOneWidget); final pluralFinder = find.text('1 day'); expect(pluralFinder, findsOneWidget); expect(tr('test'), 'test'); expect(EasyLocalization.of(_context)!.locale, const Locale('en', 'US')); l = const Locale('ar', 'DZ'); expect(() async { await EasyLocalization.of(_context)!.setLocale(l); }, throwsAssertionError); await tester.pump(); expect(EasyLocalization.of(_context)!.locale, const Locale('en', 'US')); }); }, ); testWidgets( '[EasyLocalization] change loacle test', (WidgetTester tester) async { await tester.runAsync(() async { await tester.pumpWidget(EasyLocalization( path: '../../i18n', supportedLocales: const [Locale('en', 'US'), Locale('ar', 'DZ')], child: const MyApp(), )); // await tester.idle(); // The async delegator load will require build on the next frame. Thus, pump await tester.pump(); expect(Localization.of(_context), isInstanceOf<Localization>()); expect(EasyLocalization.of(_context)!.supportedLocales, [const Locale('en', 'US'), const Locale('ar', 'DZ')]); expect(EasyLocalization.of(_context)!.locale, const Locale('en', 'US')); var trFinder = find.text('test'); expect(trFinder, findsOneWidget); var pluralFinder = find.text('1 day'); expect(pluralFinder, findsOneWidget); expect(tr('test'), 'test'); var l = const Locale('en', 'US'); await EasyLocalization.of(_context)!.setLocale(l); await tester.pump(); expect(EasyLocalization.of(_context)!.locale, l); l = const Locale('ar', 'DZ'); await EasyLocalization.of(_context)!.setLocale(l); // await tester.idle(); await tester.pump(); expect(EasyLocalization.of(_context)!.locale, l); l = const Locale('en', 'US'); await EasyLocalization.of(_context)!.setLocale(l); // await tester.idle(); await tester.pump(); expect(EasyLocalization.of(_context)!.locale, l); l = const Locale('en', 'UK'); expect(() async => {await EasyLocalization.of(_context)!.setLocale(l)}, throwsAssertionError); l = const Locale('ar', 'DZ'); await EasyLocalization.of(_context)!.setLocale(l); // await tester.idle(); await tester.pump(); expect(EasyLocalization.of(_context)!.locale, l); }); }, ); testWidgets( '[EasyLocalization] loacle ar_DZ test', (WidgetTester tester) async { await tester.runAsync(() async { await tester.pumpWidget(EasyLocalization( path: '../../i18n', supportedLocales: const [Locale('en', 'US'), Locale('ar', 'DZ')], child: const MyApp(), )); // await tester.idle(); // The async delegator load will require build on the next frame. Thus, pump await tester.pump(); await EasyLocalization.of(_context)! .setLocale(const Locale('ar', 'DZ')); await tester.pump(); expect(EasyLocalization.of(_context)!.supportedLocales, [const Locale('en', 'US'), const Locale('ar', 'DZ')]); expect(EasyLocalization.of(_context)!.locale, const Locale('ar', 'DZ')); var trFinder = find.text('اختبار'); expect(trFinder, findsOneWidget); var pluralFinder = find.text('1 يوم'); expect(pluralFinder, findsOneWidget); expect(Localization.of(_context), isInstanceOf<Localization>()); expect(tr('test'), 'اختبار'); expect(plural('day', 1), '1 يوم'); expect(plural('day', 2), '2 أيام'); expect(plural('day', 3), '3 أيام'); // var l = Locale('en', 'US'); // EasyLocalization.of(_context).locale = l; // expect(EasyLocalization.of(_context).locale, l); }); }, ); testWidgets( '[EasyLocalization] fallbackLocale with doesn\'t saveLocale test', (WidgetTester tester) async { await tester.runAsync(() async { await tester.pumpWidget(EasyLocalization( path: '../../i18n', saveLocale: false, useOnlyLangCode: true, supportedLocales: const [Locale('en'), Locale('ar')], child: const MyApp(), // Locale('en', 'US'), Locale('ar','DZ') )); // await tester.idle(); // The async delegator load will require build on the next frame. Thus, pump await tester.pump(); expect(EasyLocalization.of(_context)!.supportedLocales, [const Locale('en'), const Locale('ar')]); expect(EasyLocalization.of(_context)!.locale, const Locale('en')); var l = const Locale('en'); await EasyLocalization.of(_context)!.setLocale(l); expect(EasyLocalization.of(_context)!.locale, l); }); }, ); testWidgets( '[EasyLocalization] fallbackLocale=null with doesn\'t saveLocale test', (WidgetTester tester) async { await tester.runAsync(() async { await tester.pumpWidget(EasyLocalization( path: '../../i18n', saveLocale: false, useOnlyLangCode: true, supportedLocales: const [Locale('en'), Locale('ar')], child: const MyApp(), // Locale('en', 'US'), Locale('ar','DZ') )); // await tester.idle(); // The async delegator load will require build on the next frame. Thus, pump await tester.pump(); expect(EasyLocalization.of(_context)!.supportedLocales, [const Locale('en'), const Locale('ar')]); expect(EasyLocalization.of(_context)!.locale, const Locale('en')); var l = const Locale('en'); await EasyLocalization.of(_context)!.setLocale(l); expect(EasyLocalization.of(_context)!.locale, l); }); }, ); testWidgets( '[EasyLocalization] _getFallbackLocale() fallbackLocale!=null test', (WidgetTester tester) async { await tester.runAsync(() async { await tester.pumpWidget(EasyLocalization( path: '../../i18n', saveLocale: false, useOnlyLangCode: true, supportedLocales: const [Locale('ar')], fallbackLocale: const Locale('ar'), child: const MyApp(), )); // await tester.idle(); // The async delegator load will require build on the next frame. Thus, pump await tester.pump(); expect(EasyLocalization.of(_context)!.supportedLocales, [const Locale('ar')]); expect(EasyLocalization.of(_context)!.locale, const Locale('ar')); expect( EasyLocalization.of(_context)!.fallbackLocale, const Locale('ar')); }); }, ); testWidgets( '[EasyLocalization] _getFallbackLocale() fallbackLocale==null test', (WidgetTester tester) async { await tester.runAsync(() async { await tester.pumpWidget(EasyLocalization( path: '../../i18n', saveLocale: false, useOnlyLangCode: true, // fallbackLocale:Locale('en') , supportedLocales: const [Locale('ar')], child: const MyApp(), // Locale('en', 'US'), Locale('ar','DZ') )); // await tester.idle(); // The async delegator load will require build on the next frame. Thus, pump await tester.pump(); expect(EasyLocalization.of(_context)!.supportedLocales, [const Locale('ar')]); expect(EasyLocalization.of(_context)!.locale, const Locale('ar')); expect(EasyLocalization.of(_context)!.fallbackLocale, null); }); }, ); group('SharedPreferences SavedLocale NULL', () { setUp(() { SharedPreferences.setMockInitialValues({ 'locale': '', }); }); testWidgets( '[EasyLocalization] SavedLocale() null locale without country code', (WidgetTester tester) async { await tester.runAsync(() async { await tester.pumpWidget(EasyLocalization( path: '../../i18n', // fallbackLocale:Locale('en') , supportedLocales: const [Locale('en'), Locale('ar')], child: const MyApp(), // )); // await tester.idle(); await tester.pump(const Duration(seconds: 2)); // The async delegator load will require build on the next frame. Thus, pump await tester.pump(); expect(EasyLocalization.of(_context)!.supportedLocales, [const Locale('en'), const Locale('ar')]); expect(EasyLocalization.of(_context)!.locale, const Locale('en')); expect(EasyLocalization.of(_context)!.fallbackLocale, null); }); }, ); testWidgets( '[EasyLocalization] SavedLocale() test', (WidgetTester tester) async { await tester.runAsync(() async { await tester.pumpWidget(EasyLocalization( path: '../../i18n', // fallbackLocale:Locale('en') , supportedLocales: const [Locale('en', 'US'), Locale('ar', 'DZ')], child: const MyApp(), // )); // await tester.idle(); await tester.pump(const Duration(seconds: 2)); // The async delegator load will require build on the next frame. Thus, pump await tester.pump(); expect(EasyLocalization.of(_context)!.supportedLocales, [const Locale('en', 'US'), const Locale('ar', 'DZ')]); expect( EasyLocalization.of(_context)!.locale, const Locale('en', 'US')); expect(EasyLocalization.of(_context)!.fallbackLocale, null); }); }, ); testWidgets( '[EasyLocalization] startLocale test', (WidgetTester tester) async { await tester.runAsync(() async { await tester.pumpWidget(EasyLocalization( path: '../../i18n', startLocale: const Locale('ar', 'DZ'), // fallbackLocale:Locale('en') , supportedLocales: const [Locale('en', 'US'), Locale('ar', 'DZ')], child: const MyApp(), // )); // await tester.idle(); await tester.pump(const Duration(seconds: 2)); // The async delegator load will require build on the next frame. Thus, pump await tester.pump(); expect(EasyLocalization.of(_context)!.supportedLocales, [const Locale('en', 'US'), const Locale('ar', 'DZ')]); expect( EasyLocalization.of(_context)!.locale, const Locale('ar', 'DZ')); expect(EasyLocalization.of(_context)!.fallbackLocale, null); }); }, ); }); group('SharedPreferences saveLocale', () { setUpAll(() async { SharedPreferences.setMockInitialValues({ 'locale': 'ar', }); await EasyLocalization.ensureInitialized(); }); testWidgets( '[EasyLocalization] useOnlyLangCode true test', (WidgetTester tester) async { await tester.runAsync(() async { await tester.pumpWidget(EasyLocalization( path: '../../i18n', saveLocale: true, // fallbackLocale:Locale('en') , useOnlyLangCode: true, supportedLocales: const [Locale('en'), Locale('ar')], child: const MyApp(), // Locale('en', 'US'), Locale('ar','DZ') )); // await tester.idle(); // The async delegator load will require build on the next frame. Thus, pump await tester.pump(); expect(EasyLocalization.of(_context)!.supportedLocales, [const Locale('en'), const Locale('ar')]); expect(EasyLocalization.of(_context)!.locale, const Locale('ar')); expect(EasyLocalization.of(_context)!.fallbackLocale, null); }); }, ); }); group('SharedPreferences saveLocale', () { setUpAll(() async { SharedPreferences.setMockInitialValues({ 'locale': 'ar_DZ', }); await EasyLocalization.ensureInitialized(); }); testWidgets( '[EasyLocalization] saveLocale true test', (WidgetTester tester) async { await tester.runAsync(() async { await tester.pumpWidget(EasyLocalization( path: '../../i18n', saveLocale: true, // fallbackLocale:Locale('en') , supportedLocales: const [Locale('en', 'US'), Locale('ar', 'DZ')], child: const MyApp(), // Locale('en', 'US'), Locale('ar','DZ') )); // await tester.idle(); // The async delegator load will require build on the next frame. Thus, pump await tester.pump(); expect(EasyLocalization.of(_context)!.supportedLocales, [const Locale('en', 'US'), const Locale('ar', 'DZ')]); expect( EasyLocalization.of(_context)!.locale, const Locale('ar', 'DZ')); expect(EasyLocalization.of(_context)!.fallbackLocale, null); }); }, ); testWidgets( '[EasyLocalization] saveLocale false test', (WidgetTester tester) async { await tester.runAsync(() async { await tester.pumpWidget(EasyLocalization( path: '../../i18n', saveLocale: false, // fallbackLocale:Locale('en') , supportedLocales: const [Locale('en', 'US'), Locale('ar', 'DZ')], child: const MyApp(), // Locale('en', 'US'), Locale('ar','DZ') )); // await tester.idle(); // The async delegator load will require build on the next frame. Thus, pump await tester.pump(); expect(EasyLocalization.of(_context)!.supportedLocales, [const Locale('en', 'US'), const Locale('ar', 'DZ')]); expect( EasyLocalization.of(_context)!.locale, const Locale('en', 'US')); await EasyLocalization.of(_context)! .setLocale(const Locale('en', 'US')); }); }, ); }); group('SharedPreferences deleteSaveLocale()', () { setUpAll(() async { SharedPreferences.setMockInitialValues({ 'locale': 'ar_DZ', }); await EasyLocalization.ensureInitialized(); }); testWidgets( '[EasyLocalization] deleteSaveLocale test', (WidgetTester tester) async { await tester.runAsync(() async { await tester.pumpWidget(EasyLocalization( path: '../../i18n', // fallbackLocale:Locale('en') , supportedLocales: const [Locale('en', 'US'), Locale('ar', 'DZ')], child: const MyApp(), // Locale('en', 'US'), Locale('ar','DZ') )); // await tester.idle(); // The async delegator load will require build on the next frame. Thus, pump await tester.pump(); expect( EasyLocalization.of(_context)!.locale, const Locale('ar', 'DZ')); await EasyLocalization.of(_context)!.deleteSaveLocale(); }); }, ); testWidgets( '[EasyLocalization] after deleteSaveLocale test', (WidgetTester tester) async { await tester.runAsync(() async { await tester.pumpWidget(EasyLocalization( path: '../../i18n', // fallbackLocale:Locale('en') , supportedLocales: const [Locale('en', 'US'), Locale('ar', 'DZ')], child: const MyApp(), // Locale('en', 'US'), Locale('ar','DZ') )); // await tester.idle(); // The async delegator load will require build on the next frame. Thus, pump await tester.pump(); expect( EasyLocalization.of(_context)!.locale, const Locale('en', 'US')); }); }, ); testWidgets( '[EasyLocalization] device locale test', (WidgetTester tester) async { await tester.runAsync(() async { await tester.pumpWidget(EasyLocalization( path: '../../i18n', supportedLocales: const [Locale('en', 'US'), Locale('ar', 'DZ')], child: const MyApp(), // Locale('en', 'US'), Locale('ar','DZ') )); // await tester.idle(); // The async delegator load will require build on the next frame. Thus, pump await tester.pump(); expect(EasyLocalization.of(_context)!.deviceLocale.toString(), Platform.localeName); }); }, ); testWidgets( '[EasyLocalization] reset device locale test', (WidgetTester tester) async { await tester.runAsync(() async { await tester.pumpWidget(EasyLocalization( path: '../../i18n', supportedLocales: const [ Locale('en', 'US'), Locale('ar', 'DZ') ], // Locale('en', 'US'), Locale('ar','DZ') startLocale: const Locale('ar', 'DZ'), child: const MyApp(), )); // await tester.idle(); // The async delegator load will require build on the next frame. Thus, pump await tester.pump(); expect( EasyLocalization.of(_context)!.locale, const Locale('ar', 'DZ')); // reset to device locale await _context.resetLocale(); await tester.pump(); expect( EasyLocalization.of(_context)!.locale, const Locale('en', 'US')); }); }, ); testWidgets( '[EasyLocalization] device locale test', (WidgetTester tester) async { await tester.runAsync(() async { await tester.pumpWidget(EasyLocalization( path: '../../i18n', supportedLocales: const [Locale('en', 'US'), Locale('ar', 'DZ')], child: const MyApp(), // Locale('en', 'US'), Locale('ar','DZ') )); await tester.idle(); // The async delegator load will require build on the next frame. Thus, pump await tester.pumpAndSettle(); expect(EasyLocalization.of(_context)!.deviceLocale.toString(), Platform.localeName); }); }, ); testWidgets( '[EasyLocalization] reset device locale test', (WidgetTester tester) async { await tester.runAsync(() async { await tester.pumpWidget(EasyLocalization( path: '../../i18n', supportedLocales: const [ Locale('en', 'US'), Locale('ar', 'DZ') ], // Locale('en', 'US'), Locale('ar','DZ') startLocale: const Locale('ar', 'DZ'), child: const MyApp(), )); await tester.idle(); // The async delegator load will require build on the next frame. Thus, pump await tester.pumpAndSettle(); expect( EasyLocalization.of(_context)!.locale, const Locale('ar', 'DZ')); // reset to device locale await _context.resetLocale(); await tester.pumpAndSettle(); expect( EasyLocalization.of(_context)!.locale, const Locale('en', 'US')); }); }, ); }); group('Context extensions tests', () { final testWidget = EasyLocalization( path: '../../i18n', supportedLocales: const [ Locale('en', 'US'), Locale('ar', 'DZ') ], // Locale('en', 'US'), Locale('ar','DZ') startLocale: const Locale('en', 'US'), child: const MyApp( child: MyLocalizedWidget(), ), ); testWidgets( '[EasyLocalization] Throws LocalizationNotFoundException without EasyLocalization widget', (WidgetTester tester) async { await tester.pumpWidget(const MyLocalizedWidget()); final exception = tester.takeException(); expect( exception, isA<LocalizationNotFoundException>(), ); }, ); testWidgets( '[EasyLocalization] context.translate and context.plural text widgets are in the tree', (WidgetTester tester) async { await tester.runAsync(() async { await tester.pumpWidget(testWidget); await tester.idle(); // The async delegator load will require build on the next frame. Thus, pump await tester.pumpAndSettle(); expect( find.text(_contextTranslationValue), findsOneWidget, ); expect( find.text(_contextPluralValue), findsOneWidget, ); }); }, ); testWidgets( '[EasyLocalization] context.translate and context.plural provide relevant texts', (WidgetTester tester) async { await tester.runAsync(() async { await tester.pumpWidget(testWidget); const expectedEnTranslateTextWidgetValue = 'test'; const expectedArTranslateTextWidgetValue = 'اختبار'; const expectedEnPluralTextWidgetValue = '1 day'; const expectedArPluralTextWidgetValue = '1 يوم'; const arabyLocale = Locale('ar', 'DZ'); await tester.idle(); // The async delegator load will require build on the next frame. Thus, pump await tester.pumpAndSettle(); final initialTranslationValue = _contextTranslationValue; final initialPluralValue = _contextPluralValue; expect( initialTranslationValue == expectedEnTranslateTextWidgetValue, true, ); expect( initialPluralValue == expectedEnPluralTextWidgetValue, true, ); EasyLocalization.of(_context)?.setLocale(arabyLocale); await tester.pumpAndSettle(); expect( initialTranslationValue != _contextTranslationValue && _contextTranslationValue == expectedArTranslateTextWidgetValue, true, ); expect( initialPluralValue != _contextPluralValue && _contextPluralValue == expectedArPluralTextWidgetValue, true, ); }); }, ); }); }
0
mirrored_repositories/easy_localization
mirrored_repositories/easy_localization/test/easy_localization_language_specific_test.dart
import 'dart:developer'; import 'package:easy_localization/src/easy_localization_controller.dart'; import 'package:easy_localization/src/localization.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'utils/test_asset_loaders.dart'; void main() { group('language-specific-plurals', () { var r = EasyLocalizationController( forceLocale: const Locale('fb'), supportedLocales: [const Locale('en'), const Locale('ru'), const Locale('fb')], fallbackLocale: const Locale('fb'), path: 'path', useOnlyLangCode: true, useFallbackTranslations: true, onLoadError: (FlutterError e) { log(e.toString()); }, saveLocale: false, assetLoader: const JsonAssetLoader()); setUpAll(() async { await r.loadTranslations(); }); test('english one', () async { Localization.load(const Locale('en'), translations: r.translations, fallbackTranslations: r.fallbackTranslations); expect(Localization.instance.plural('hat', 1), 'one hat'); }); test('english other', () async { Localization.load(const Locale('en'), translations: r.translations, fallbackTranslations: r.fallbackTranslations); expect(Localization.instance.plural('hat', 2), 'other hats'); expect(Localization.instance.plural('hat', 0), 'other hats'); expect(Localization.instance.plural('hat', 3), 'other hats'); }); test('russian one', () async { Localization.load(const Locale('ru'), translations: r.translations, fallbackTranslations: r.fallbackTranslations); expect(Localization.instance.plural('hat', 1), 'one hat'); }); test('russian few', () async { Localization.load(const Locale('ru'), translations: r.translations, fallbackTranslations: r.fallbackTranslations); expect(Localization.instance.plural('hat', 2), 'few hats'); expect(Localization.instance.plural('hat', 3), 'few hats'); }); test('russian many', () async { Localization.load(const Locale('ru'), translations: r.translations, fallbackTranslations: r.fallbackTranslations); expect(Localization.instance.plural('hat', 0), 'many hats'); expect(Localization.instance.plural('hat', 5), 'many hats'); }); }); }
0
mirrored_repositories/easy_localization/test
mirrored_repositories/easy_localization/test/utils/test_asset_loaders.dart
import 'dart:ui'; import 'package:easy_localization/src/asset_loader.dart'; class ImmutableJsonAssetLoader extends AssetLoader { const ImmutableJsonAssetLoader(); @override Future<Map<String, dynamic>> load(String fullPath, Locale locale) { return Future.value(const { 'test': 'test', }); } } class JsonAssetLoader extends AssetLoader { const JsonAssetLoader(); @override Future<Map<String, dynamic>> load(String fullPath, Locale locale) { return Future.value({ 'test': 'test', 'test_replace_one': 'test replace {}', 'test_replace_two': 'test replace {} {}', 'test_replace_named': 'test named replace {arg1} {arg2}', 'gender': {'male': 'Hi man ;)', 'female': 'Hello girl :)'}, 'gender_and_replace': { 'male': 'Hi {} man ;)', 'female': 'Hello {} girl :)' }, 'day': { 'zero': '{} days', 'one': '{} day', 'two': '{} days', 'few': '{} few days', 'many': '{} many days', 'other': '{} other days' }, 'hat': { 'zero': 'no hats', 'one': 'one hat', 'two': 'two hats', 'few': 'few hats', 'many': 'many hats', 'other': 'other hats' }, 'hat_other': {'other': 'other hats'}, 'money': { 'zero': '{} has no money', 'one': '{} has {} dollar', 'other': '{} has {} dollars', }, 'money_named_args': { 'zero': '{name} has no money', 'one': '{name} has {money} dollar', 'other': '{name} has {money} dollars', }, 'nested_periods': { 'Processing': 'Processing', 'Processing.': 'Processing.', }, 'nested.but.not.nested': 'nested but not nested', 'linked': 'this @:isLinked', 'isLinked': 'is linked', 'linkAndModify': 'this is linked and @.upper:modified', 'modified': 'modified', 'linkMany': '@:many @.capitalize:locale @:messages', 'many': 'many', 'locale': 'locale', 'messages': 'messages', 'linkedWithBrackets': 'linked with @.lower:(brackets).', 'brackets': 'Brackets', 'nestedArguments': 'this is {} @.undefiend:nestedArg', 'nestedArg': 'nested {}{}', 'nestedNamedArguments': '{firstArg} is a @:nestedNamedArg', 'nestedNamedArg': 'nested {secondArg}{thirdArg}', 'nested': { 'super': { 'duper': { 'nested': 'nested.super.duper.nested', 'nested_with_arg': 'nested.super.duper.nested_with_arg {}', 'nested_with_named_arg': 'nested.super.duper.nested_with_named_arg {arg}' } } }, 'path': fullPath, 'test_missing_fallback': (locale.languageCode == 'fb' ? 'fallback!' : null), 'test_fallback_plurals': (locale.languageCode == 'fb' ? { 'zero': 'fallback zero', 'one': 'fallback one', 'two': 'fallback two', 'few': 'fallback few', 'many': 'fallback many', 'other': 'fallback other', } : { 'one': '{} second', 'other': '{} seconds', }), }); } } class ExternalAssetLoader extends AssetLoader { const ExternalAssetLoader(); @override Future<Map<String, dynamic>> load(String fullPath, Locale locale) => Future.value(const { 'package_value_01': 'package_value_01', 'package_value_02': 'package_value_02', 'package_value_03': 'package_value_03', }); } class NestedAssetLoader extends AssetLoader { const NestedAssetLoader(); @override Future<Map<String, dynamic>> load(String fullPath, Locale locale) => Future.value({ 'nested': { 'super': { 'duper': {'nested': 'nested.super.duper.nested'} } }, }); }
0
mirrored_repositories/easy_localization
mirrored_repositories/easy_localization/bin/generate.dart
import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:args/args.dart'; import 'package:path/path.dart' as path; const _preservedKeywords = [ 'few', 'many', 'one', 'other', 'two', 'zero', 'male', 'female', ]; void main(List<String> args) { if (_isHelpCommand(args)) { _printHelperDisplay(); } else { handleLangFiles(_generateOption(args)); } } bool _isHelpCommand(List<String> args) { return args.length == 1 && (args[0] == '--help' || args[0] == '-h'); } void _printHelperDisplay() { var parser = _generateArgParser(null); stdout.writeln(parser.usage); } GenerateOptions _generateOption(List<String> args) { var generateOptions = GenerateOptions(); var parser = _generateArgParser(generateOptions); parser.parse(args); return generateOptions; } ArgParser _generateArgParser(GenerateOptions? generateOptions) { var parser = ArgParser(); parser.addOption('source-dir', abbr: 'S', defaultsTo: 'resources/langs', callback: (String? x) => generateOptions!.sourceDir = x, help: 'Folder containing localization files'); parser.addOption('source-file', abbr: 's', callback: (String? x) => generateOptions!.sourceFile = x, help: 'File to use for localization'); parser.addOption('output-dir', abbr: 'O', defaultsTo: 'lib/generated', callback: (String? x) => generateOptions!.outputDir = x, help: 'Output folder stores for the generated file'); parser.addOption('output-file', abbr: 'o', defaultsTo: 'codegen_loader.g.dart', callback: (String? x) => generateOptions!.outputFile = x, help: 'Output file name'); parser.addOption('format', abbr: 'f', defaultsTo: 'json', callback: (String? x) => generateOptions!.format = x, help: 'Support json or keys formats', allowed: ['json', 'keys']); parser.addFlag( 'skip-unnecessary-keys', abbr: 'u', defaultsTo: false, callback: (bool? x) => generateOptions!.skipUnnecessaryKeys = x, help: 'If true - Skip unnecessary keys of nested objects.', ); return parser; } class GenerateOptions { String? sourceDir; String? sourceFile; String? templateLocale; String? outputDir; String? outputFile; String? format; bool? skipUnnecessaryKeys; @override String toString() { return 'format: $format sourceDir: $sourceDir sourceFile: $sourceFile outputDir: $outputDir outputFile: $outputFile skipUnnecessaryKeys: $skipUnnecessaryKeys'; } } void handleLangFiles(GenerateOptions options) async { final current = Directory.current; final source = Directory.fromUri(Uri.parse(options.sourceDir!)); final output = Directory.fromUri(Uri.parse(options.outputDir!)); final sourcePath = Directory(path.join(current.path, source.path)); final outputPath = Directory(path.join(current.path, output.path, options.outputFile)); if (!await sourcePath.exists()) { stderr.writeln('Source path does not exist'); return; } var files = await dirContents(sourcePath); if (options.sourceFile != null) { final sourceFile = File(path.join(source.path, options.sourceFile)); if (!await sourceFile.exists()) { stderr.writeln('Source file does not exist (${sourceFile.toString()})'); return; } files = [sourceFile]; } else { //filtering format files = files.where((f) => f.path.contains('.json')).toList(); } if (files.isNotEmpty) { generateFile(files, outputPath, options); } else { stderr.writeln('Source path empty'); } } Future<List<FileSystemEntity>> dirContents(Directory dir) { var files = <FileSystemEntity>[]; var completer = Completer<List<FileSystemEntity>>(); var lister = dir.list(recursive: false); lister.listen((file) => files.add(file), onDone: () => completer.complete(files)); return completer.future; } void generateFile(List<FileSystemEntity> files, Directory outputPath, GenerateOptions options) async { var generatedFile = File(outputPath.path); if (!generatedFile.existsSync()) { generatedFile.createSync(recursive: true); } var classBuilder = StringBuffer(); switch (options.format) { case 'json': await _writeJson(classBuilder, files); break; case 'keys': await _writeKeys(classBuilder, files, options.skipUnnecessaryKeys); break; // case 'csv': // await _writeCsv(classBuilder, files); // break; default: stderr.writeln('Format not supported'); } classBuilder.writeln('}'); generatedFile.writeAsStringSync(classBuilder.toString()); stdout.writeln('All done! File generated in ${outputPath.path}'); } Future _writeKeys(StringBuffer classBuilder, List<FileSystemEntity> files, bool? skipUnnecessaryKeys) async { var file = ''' // DO NOT EDIT. This is code generated via package:easy_localization/generate.dart abstract class LocaleKeys { '''; final fileData = File(files.first.path); Map<String, dynamic> translations = json.decode(await fileData.readAsString()); file += _resolve(translations, skipUnnecessaryKeys); classBuilder.writeln(file); } String _resolve(Map<String, dynamic> translations, bool? skipUnnecessaryKeys, [String? accKey]) { var fileContent = ''; final sortedKeys = translations.keys.toList(); final canIgnoreKeys = skipUnnecessaryKeys == true; bool containsPreservedKeywords(Map<String, dynamic> map) => map.keys.any((element) => _preservedKeywords.contains(element)); for (var key in sortedKeys) { var ignoreKey = false; if (translations[key] is Map) { // If key does not contain keys for plural(), gender() etc. and option is enabled -> ignore it ignoreKey = !containsPreservedKeywords( translations[key] as Map<String, dynamic>) && canIgnoreKeys; var nextAccKey = key; if (accKey != null) { nextAccKey = '$accKey.$key'; } fileContent += _resolve(translations[key], skipUnnecessaryKeys, nextAccKey); } if (!_preservedKeywords.contains(key)) { accKey != null && !ignoreKey ? fileContent += ' static const ${accKey.replaceAll('.', '_')}_$key = \'$accKey.$key\';\n' : !ignoreKey ? fileContent += ' static const $key = \'$key\';\n' : null; } } return fileContent; } Future _writeJson( StringBuffer classBuilder, List<FileSystemEntity> files) async { var gFile = ''' // DO NOT EDIT. This is code generated via package:easy_localization/generate.dart // ignore_for_file: prefer_single_quotes, avoid_renaming_method_parameters import 'dart:ui'; import 'package:easy_localization/easy_localization.dart' show AssetLoader; class CodegenLoader extends AssetLoader{ const CodegenLoader(); @override Future<Map<String, dynamic>?> load(String path, Locale locale) { return Future.value(mapLocales[locale.toString()]); } '''; final listLocales = []; for (var file in files) { final localeName = path.basename(file.path).replaceFirst('.json', '').replaceAll('-', '_'); listLocales.add('"$localeName": $localeName'); final fileData = File(file.path); Map<String, dynamic>? data = json.decode(await fileData.readAsString()); final mapString = const JsonEncoder.withIndent(' ').convert(data); gFile += 'static const Map<String,dynamic> $localeName = $mapString;\n'; } gFile += 'static const Map<String, Map<String,dynamic>> mapLocales = {${listLocales.join(', ')}};'; classBuilder.writeln(gFile); } // _writeCsv(StringBuffer classBuilder, List<FileSystemEntity> files) async { // List<String> listLocales = List(); // final fileData = File(files.first.path); // // CSVParser csvParser = CSVParser(await fileData.readAsString()); // // List listLangs = csvParser.getLanguages(); // for(String localeName in listLangs){ // listLocales.add('"$localeName": $localeName'); // String mapString = JsonEncoder.withIndent(" ").convert(csvParser.getLanguageMap(localeName)) ; // classBuilder.writeln( // ' static const Map<String,dynamic> $localeName = ${mapString};\n'); // } // classBuilder.writeln( // ' static const Map<String, Map<String,dynamic>> mapLocales = \{${listLocales.join(', ')}\};'); // }
0
mirrored_repositories/easy_localization/packages/easy_logger
mirrored_repositories/easy_localization/packages/easy_logger/lib/easy_logger.dart
export 'src/logger.dart'; export 'src/enums.dart'; export 'src/logger_printer.dart';
0
mirrored_repositories/easy_localization/packages/easy_logger/lib
mirrored_repositories/easy_localization/packages/easy_logger/lib/src/enums.dart
/// Build mode enum used in [EasyLogger]. enum BuildMode { /// Release build mode release, /// Profile build mode profile, /// Debug build mode debug } /// Levels messages enum used in [EasyLogger]. enum LevelMessages { ///Debug level message debug, ///Information level message info, ///Warning level message warning, ///Error level message error, }
0
mirrored_repositories/easy_localization/packages/easy_logger/lib
mirrored_repositories/easy_localization/packages/easy_logger/lib/src/logger.dart
import 'package:flutter/foundation.dart'; import 'enums.dart'; import 'logger_printer.dart'; /// Easy Logger callable class class EasyLogger { /// Customized logger, part of [EasyLocalization](https://github.com/aissat/easy_localization) ecosystem. /// Callable class, [more info](https://dart.dev/guides/language/language-tour#callable-classes) EasyLogger({ this.name = '', this.enableBuildModes = const <BuildMode>[ BuildMode.profile, BuildMode.debug, ], this.enableLevels = const <LevelMessages>[ LevelMessages.debug, LevelMessages.info, LevelMessages.error, LevelMessages.warning, ], EasyLogPrinter? printer, this.defaultLevel = LevelMessages.info, }) { this.printer = printer ?? easyLogDefaultPrinter; _currentBuildMode = _getCurrentBuildMode(); } BuildMode? _currentBuildMode; /// Name prefix in the logging line. /// @Default value `''` empty string. /// Example: /// ``` /// [YourName] same log text /// ``` String name; /// List of available build modes in which logging is enabled. /// @Default value `const <LevelMessages>[BuildMode.profile, BuildMode.debug]` List<BuildMode> enableBuildModes; /// List of available levels messages in which logging is enabled. /// @Default value `const <LevelMessages>[LevelMessages.debug, LevelMessages.info, LevelMessages.error, LevelMessages.warning]` List<LevelMessages> enableLevels; /// Default message level if no level is set when call [EasyLogger]. /// @Default value `LevelMessages.info` LevelMessages defaultLevel; /// Printer function instance. /// You can change the standard print function to a custom one. /// Example: /// ```dart /// EasyLogPrinter customLogPrinter = ( /// Object object, { /// String name, /// StackTrace stackTrace, /// LevelMessages level, /// }) { /// print('$name: ${object.toString()}'); /// }; /// /// logger.printer = customLogPrinter; /// ``` EasyLogPrinter? printer; BuildMode _getCurrentBuildMode() { if (kReleaseMode) { return BuildMode.release; } else if (kProfileMode) { return BuildMode.profile; } return BuildMode.debug; } /// Check [enableBuildModes] and [enableLevels] bool isEnabled(LevelMessages level) { if (!enableBuildModes.contains(_currentBuildMode)) { return false; } if (!enableLevels.contains(level)) { return false; } return true; } /// The main callable function for handling log messages. void call(Object object, {StackTrace? stackTrace, LevelMessages? level}) { level ??= defaultLevel; if (isEnabled(level)) { printer!(object, stackTrace: stackTrace, level: level, name: name); } } /// Helper for main callable function. /// Call logger function with level [LevelMessages.debug] void debug(Object object, {StackTrace? stackTrace}) => call(object, stackTrace: stackTrace, level: LevelMessages.debug); /// Helper for main callable function. /// Call logger function with level [LevelMessages.info] void info(Object object, {StackTrace? stackTrace}) => call(object, stackTrace: stackTrace, level: LevelMessages.info); /// Helper for main callable function. /// Call logger function with level [LevelMessages.warning] void warning(Object object, {StackTrace? stackTrace}) => call(object, stackTrace: stackTrace, level: LevelMessages.warning); /// Helper for main callable function. /// Call logger function with level [LevelMessages.error] void error(Object object, {StackTrace? stackTrace}) => call(object, stackTrace: stackTrace, level: LevelMessages.error); }
0
mirrored_repositories/easy_localization/packages/easy_logger/lib
mirrored_repositories/easy_localization/packages/easy_logger/lib/src/logger_printer.dart
import 'package:flutter/foundation.dart'; import '../easy_logger.dart'; /// Type for function printing/logging in [EasyLogger]. typedef EasyLogPrinter = Function(Object object, {String? name, LevelMessages? level, StackTrace? stackTrace}); /// Default debug-mode function printing. EasyLogPrinter easyLogDefaultPrinter = (Object object, {String? name, StackTrace? stackTrace, LevelMessages? level}) { final String levelName = level?.name != null ? '[${level?.name}] ' : ''; final String tag = name != null ? '[$name] ' : ''; if (kDebugMode) { print(_getColoredString(level, '$tag$levelName${object.toString()}')); if (stackTrace != null) { print(_getColoredString(level, '__________________________________')); print(_getColoredString(level, stackTrace.toString())); } } }; String _getColoredString(LevelMessages? level, String string) { switch (level) { case LevelMessages.debug: // gray return '\u001b[90m$string\u001b[0m'; case LevelMessages.info: // green return '\u001b[32m$string\u001b[0m'; case LevelMessages.warning: // blue return '\u001B[34m$string\u001b[0m'; case LevelMessages.error: // red return '\u001b[31m$string\u001b[0m'; default: // gray return '\u001b[90m$string\u001b[0m'; } } extension _LevelMessagesExtension on LevelMessages { String get name { switch (this) { case LevelMessages.debug: return 'DEBUG'; case LevelMessages.info: return 'INFO'; case LevelMessages.warning: return 'WARNING'; case LevelMessages.error: return 'ERROR'; } } }
0
mirrored_repositories/easy_localization/packages/easy_logger
mirrored_repositories/easy_localization/packages/easy_logger/test/easy_logger_test.dart
import 'dart:async'; import 'package:easy_logger/easy_logger.dart'; import 'package:flutter_test/flutter_test.dart'; List<String> printLog = <String>[]; ZoneSpecification? spec; dynamic Function() overridePrint(Function() testFn) => () { spec = ZoneSpecification( print: (_, __, ___, String msg) { // Add to log instead of printing to stdout printLog.add(msg); }, ); return Zone.current.fork(specification: spec).run(testFn); }; late EasyLogger logger; void main() { group('Logger testing print', () { logger = EasyLogger(name: 'test logger'); test('Logger print', overridePrint(() { printLog = <String>[]; logger('Same print'); expect(printLog.first, contains('Same print')); expect(printLog.first, contains(logger.name)); })); test('Logger print info', overridePrint(() { printLog = <String>[]; logger('print info', level: LevelMessages.info); expect(printLog.first, contains('print info')); expect(printLog.first, contains('[INFO]')); })); test('Logger print debug', overridePrint(() { printLog = <String>[]; logger('print debug', level: LevelMessages.debug); expect(printLog.first, contains('print debug')); expect(printLog.first, contains('[DEBUG]')); })); test('Logger print warning', overridePrint(() { printLog = <String>[]; logger('print warning', level: LevelMessages.warning); expect(printLog.first, contains('print warning')); expect(printLog.first, contains('[WARNING]')); })); test('Logger print error', overridePrint(() { printLog = <String>[]; logger('print error', level: LevelMessages.error); expect(printLog.first, contains('print error')); expect(printLog.first, contains('[ERROR]')); })); test('Logger print error with StackTrace', overridePrint(() { printLog = <String>[]; StackTrace testStackTrace; testStackTrace = StackTrace.fromString('test stack'); logger('print error', level: LevelMessages.error, stackTrace: testStackTrace); expect(printLog.first, contains('print error')); expect(printLog.first, contains('[ERROR]')); expect(printLog.last, contains('test stack')); })); }); group('Logger BuildModes', () { logger = EasyLogger(name: 'test logger'); test('Logger BuildModes is not null', () { expect(logger.enableBuildModes, isNotNull); expect(logger.enableBuildModes, isNotEmpty); }); test('Logger default enable', () { expect(logger.isEnabled(LevelMessages.debug), true); }); }); }
0
mirrored_repositories/easy_localization/example
mirrored_repositories/easy_localization/example/lib/lang_view.dart
import 'dart:developer'; import 'package:flutter/material.dart'; import 'package:easy_localization/easy_localization.dart'; class LanguageView extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text( '', style: TextStyle(color: Colors.black), ), backgroundColor: Colors.white, iconTheme: IconThemeData(color: Colors.black), elevation: 0, ), body: Container( color: Colors.white, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( padding: EdgeInsets.only(top: 26), margin: EdgeInsets.symmetric( horizontal: 24, ), child: Text( 'Choose language', style: TextStyle( color: Colors.blue, fontFamily: 'Montserrat', fontWeight: FontWeight.w700, fontSize: 18, ), ), ), _SwitchListTileMenuItem( title: 'عربي', subtitle: 'عربي', locale: context.supportedLocales[1] //BuildContext extension method ), _Divider(), _SwitchListTileMenuItem( title: 'English', subtitle: 'English', locale: context.supportedLocales[0]), _Divider(), _SwitchListTileMenuItem( title: 'German', subtitle: 'German', locale: context.supportedLocales[2]), _Divider(), _SwitchListTileMenuItem( title: 'Русский', subtitle: 'Русский', locale: context.supportedLocales[3]), _Divider(), ], ), ), ); } } class _Divider extends StatelessWidget { const _Divider({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Container( margin: EdgeInsets.symmetric( horizontal: 24, ), child: Divider( color: Colors.grey, ), ); } } class _SwitchListTileMenuItem extends StatelessWidget { const _SwitchListTileMenuItem({ Key? key, required this.title, required this.subtitle, required this.locale, }) : super(key: key); final String title; final String subtitle; final Locale locale; bool isSelected(BuildContext context) => locale == context.locale; @override Widget build(BuildContext context) { return Container( margin: EdgeInsets.only(left: 10, right: 10, top: 5), decoration: BoxDecoration( border: isSelected(context) ? Border.all(color: Colors.blueAccent) : null, ), child: ListTile( dense: true, // isThreeLine: true, title: Text( title, ), subtitle: Text( subtitle, ), onTap: () async { log(locale.toString(), name: toString()); await context.setLocale(locale); //BuildContext extension method Navigator.pop(context); }), ); } }
0
mirrored_repositories/easy_localization/example
mirrored_repositories/easy_localization/example/lib/main.dart
import 'package:easy_localization/easy_localization.dart'; //import 'package:easy_localization_loader/easy_localization_loader.dart'; // import custom loaders import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'generated/locale_keys.g.dart'; import 'lang_view.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await EasyLocalization.ensureInitialized(); runApp(EasyLocalization( supportedLocales: [ Locale('en', 'US'), Locale('ar', 'DZ'), Locale('de', 'DE'), Locale('ru', 'RU') ], path: 'resources/langs', child: MyApp(), // fallbackLocale: Locale('en', 'US'), // startLocale: Locale('de', 'DE'), // saveLocale: false, // useOnlyLangCode: true, // optional assetLoader default used is RootBundleAssetLoader which uses flutter's assetloader // install easy_localization_loader for enable custom loaders // assetLoader: RootBundleAssetLoader() // assetLoader: HttpAssetLoader() // assetLoader: FileAssetLoader() // assetLoader: CsvAssetLoader() // assetLoader: YamlAssetLoader() //multiple files // assetLoader: YamlSingleAssetLoader() //single file // assetLoader: XmlAssetLoader() //multiple files // assetLoader: XmlSingleAssetLoader() //single file // assetLoader: CodegenLoader() )); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( localizationsDelegates: context.localizationDelegates, supportedLocales: context.supportedLocales, locale: context.locale, theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Easy localization'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key? key, required this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int counter = 0; bool _gender = true; void incrementCounter() { setState(() { counter++; }); } void switchGender(bool val) { setState(() { _gender = val; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(LocaleKeys.title).tr(), actions: <Widget>[ TextButton( onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (_) => LanguageView(), fullscreenDialog: true), ); }, child: Icon( Icons.language, color: Colors.white, ), ), ], ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Spacer( flex: 1, ), Text( LocaleKeys.gender_with_arg, style: TextStyle( color: Colors.grey.shade600, fontSize: 19, fontWeight: FontWeight.bold), ).tr(args: ['aissat'], gender: _gender ? 'female' : 'male'), Text( tr(LocaleKeys.gender, gender: _gender ? 'female' : 'male'), style: TextStyle( color: Colors.grey.shade600, fontSize: 15, fontWeight: FontWeight.bold), ), Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ FaIcon(FontAwesomeIcons.male), Switch(value: _gender, onChanged: switchGender), FaIcon(FontAwesomeIcons.female), ], ), Spacer( flex: 1, ), Text(LocaleKeys.msg).tr(args: ['aissat', 'Flutter']), Text(LocaleKeys.msg_named) .tr(namedArgs: {'lang': 'Dart'}, args: ['Easy localization']), Text(LocaleKeys.clicked).plural(counter), TextButton( onPressed: () { incrementCounter(); }, child: Text(LocaleKeys.clickMe).tr(), ), SizedBox( height: 15, ), Text( plural(LocaleKeys.amount, counter, format: NumberFormat.currency( locale: Intl.defaultLocale, symbol: '€')), style: TextStyle( color: Colors.grey.shade900, fontSize: 18, fontWeight: FontWeight.bold)), SizedBox( height: 20, ), ElevatedButton( onPressed: () { context.resetLocale(); }, child: Text(LocaleKeys.reset_locale).tr(), ), Spacer( flex: 1, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: incrementCounter, child: Text('+1'), ), ); } }
0
mirrored_repositories/easy_localization/example/lib
mirrored_repositories/easy_localization/example/lib/generated/codegen_loader.g.dart
// DO NOT EDIT. This is code generated via package:easy_localization/generate.dart // ignore_for_file: prefer_single_quotes import 'dart:ui'; import 'package:easy_localization/easy_localization.dart' show AssetLoader; class CodegenLoader extends AssetLoader { const CodegenLoader(); @override Future<Map<String, dynamic>> load(String fullPath, Locale locale) { return Future.value(mapLocales[locale.toString()]); } static const Map<String, dynamic> ar_DZ = { "title": "السلام", "msg": "السلام عليكم يا {} في عالم {}", "msg_named": "{} مكتوبة باللغة {lang}", "clickMe": "إضغط هنا", "profile": { "reset_password": { "label": "اعادة تعين كلمة السر", "username": "المستخدم", "password": "كلمة السر" } }, "clicked": { "zero": "لم تنقر بعد!", "one": "لقد نقرت مرة واحدة!", "two": "لقد قمت بالنقر مرتين!", "few": " لقد قمت بالنقر {} مرات!", "many": "لقد قمت بالنقر {} مرة!", "other": "{} نقرة!" }, "amount": { "zero": "المبلغ : {}", "one": " المبلغ : {}", "two": " المبلغ : {}", "few": " المبلغ : {}", "many": " المبلغ : {}", "other": " المبلغ : {}" }, "gender": { "male": " مرحبا يا رجل", "female": " مرحبا بك يا فتاة", "with_arg": {"male": "{} مرحبا يا رجل", "female": "{} مرحبا بك يا فتاة"} }, "reset_locale": "إعادة ضبط اللغة" }; static const Map<String, dynamic> ar = { "title": "السلام", "msg": "السلام عليكم يا {} في عالم {}", "msg_named": "{} مكتوبة باللغة {lang}", "clickMe": "إضغط هنا", "profile": { "reset_password": { "label": "اعادة تعين كلمة السر", "username": "المستخدم", "password": "كلمة السر" } }, "clicked": { "zero": "لم تنقر بعد!", "one": "لقد نقرت مرة واحدة!", "two": "لقد قمت بالنقر مرتين!", "few": " لقد قمت بالنقر {} مرات!", "many": "لقد قمت بالنقر {} مرة!", "other": "{} نقرة!" }, "amount": { "zero": "المبلغ : {}", "one": " المبلغ : {}", "two": " المبلغ : {}", "few": " المبلغ : {}", "many": " المبلغ : {}", "other": " المبلغ : {}" }, "gender": { "male": " مرحبا يا رجل", "female": " مرحبا بك يا فتاة", "with_arg": {"male": "{} مرحبا يا رجل", "female": "{} مرحبا بك يا فتاة"} }, "reset_locale": "إعادة ضبط اللغة" }; static const Map<String, dynamic> de_DE = { "title": "Hallo", "msg": "Hallo {} in der {} welt ", "msg_named": "{} ist in {lang} geschrieben", "clickMe": "Click mich", "profile": { "reset_password": { "label": "Password zurücksetzten", "username": "Name", "password": "Password" } }, "clicked": { "zero": "Du hast {} mal geklickt", "one": "Du hast {} mal geklickt", "two": "Du hast {} mal geklickt", "few": "Du hast {} mal geklickt", "many": "Du hast {} mal geklickt", "other": "Du hast {} mal geklickt" }, "amount": { "zero": "Deine Klicks: {}", "one": "Deine Klicks: {}", "two": "Deine Klicks: {}", "few": "Deine Klicks: {}", "many": "Deine Klicks: {}", "other": "Deine Klicks: {}" }, "gender": { "male": "Hi Mann ;) ", "female": "Hallo Frau :)", "with_arg": {"male": "Hi Mann ;) {}", "female": "Hallo Frau :) {}"} }, "reset_locale": "Sprache zurücksetzen" }; static const Map<String, dynamic> de = { "title": "Hallo", "msg": "Hallo {} in der {} welt ", "msg_named": "{} ist in {lang} geschrieben", "clickMe": "Click mich", "profile": { "reset_password": { "label": "Password zurücksetzten", "username": "Name", "password": "Password" } }, "clicked": { "zero": "Du hast {} mal geklickt", "one": "Du hast {} mal geklickt", "two": "Du hast {} mal geklickt", "few": "Du hast {} mal geklickt", "many": "Du hast {} mal geklickt", "other": "Du hast {} mal geklickt" }, "amount": { "zero": "Deine Klicks: {}", "one": "Deine Klicks: {}", "two": "Deine Klicks: {}", "few": "Deine Klicks: {}", "many": "Deine Klicks: {}", "other": "Deine Klicks: {}" }, "gender": { "male": "Hi Mann ;) ", "female": "Hallo Frau :)", "with_arg": {"male": "Hi Mann ;) {}", "female": "Hallo Frau :) {}"} }, "reset_locale": "Sprache zurücksetzen" }; static const Map<String, dynamic> en_US = { "title": "Hello", "msg": "Hello {} in the {} world ", "msg_named": "{} are written in the {lang} language", "clickMe": "Click me", "profile": { "reset_password": { "label": "Reset Password", "username": "Username", "password": "password" } }, "clicked": { "zero": "You clicked {} times!", "one": "You clicked {} time!", "two": "You clicked {} times!", "few": "You clicked {} times!", "many": "You clicked {} times!", "other": "You clicked {} times!" }, "amount": { "zero": "Your amount : {} ", "one": "Your amount : {} ", "two": "Your amount : {} ", "few": "Your amount : {} ", "many": "Your amount : {} ", "other": "Your amount : {} " }, "gender": { "male": "Hi man ;) ", "female": "Hello girl :)", "with_arg": {"male": "Hi man ;) {}", "female": "Hello girl :) {}"} }, "reset_locale": "Reset Language" }; static const Map<String, dynamic> en = { "title": "Hello", "msg": "Hello {} in the {} world ", "msg_named": "{} are written in the {lang} language", "clickMe": "Click me", "profile": { "reset_password": { "label": "Reset Password", "username": "Username", "password": "password" } }, "clicked": { "zero": "You clicked {} times!", "one": "You clicked {} time!", "two": "You clicked {} times!", "few": "You clicked {} times!", "many": "You clicked {} times!", "other": "You clicked {} times!" }, "amount": { "zero": "Your amount : {} ", "one": "Your amount : {} ", "two": "Your amount : {} ", "few": "Your amount : {} ", "many": "Your amount : {} ", "other": "Your amount : {} " }, "gender": { "male": "Hi man ;) ", "female": "Hello girl :)", "with_arg": {"male": "Hi man ;) {}", "female": "Hello girl :) {}"} }, "reset_locale": "Reset Language" }; static const Map<String, dynamic> ru_RU = { "title": "Привет!", "msg": "Привет! {} добро пожаловать {} мир! ", "msg_named": "{} написан на языке {lang}", "clickMe": "Нажми на меня", "profile": { "reset_password": { "label": "Сбросить пароль", "username": "Логин", "password": "Пароль" } }, "clicked": { "zero": "Ты кликнул {} раз!", "one": "Ты кликнул {} раз!", "two": "Ты кликнул {} раза!", "few": "Ты кликнул {} раз!", "many": "Ты кликнул {} раз!", "other": "Ты кликнул {} раз!" }, "amount": { "zero": "Твой счет : {} ", "one": "Твой счет : {} ", "two": "Твой счет : {} ", "few": "Твой счет : {} ", "many": "Твой счет : {} ", "other": "Твой счет : {} " }, "gender": { "male": "Привет мужык ;) ", "female": "Привет девчуля :)", "with_arg": { "male": "Привет мужык ;) {}", "female": "Привет девчуля :) {}" } }, "reset_locale": "Сбросить язык" }; static const Map<String, dynamic> ru = { "title": "Привет!", "msg": "Привет! {} добро пожаловать {} мир! ", "msg_named": "{} написан на языке {lang}", "clickMe": "Нажми на меня", "profile": { "reset_password": { "label": "Сбросить пароль", "username": "Логин", "password": "Пароль" } }, "clicked": { "zero": "Ты кликнул {} раз!", "one": "Ты кликнул {} раз!", "two": "Ты кликнул {} раза!", "few": "Ты кликнул {} раз!", "many": "Ты кликнул {} раз!", "other": "Ты кликнул {} раз!" }, "amount": { "zero": "Твой счет : {} ", "one": "Твой счет : {} ", "two": "Твой счет : {} ", "few": "Твой счет : {} ", "many": "Твой счет : {} ", "other": "Твой счет : {} " }, "gender": { "male": "Привет мужык ;) ", "female": "Привет девчуля :)", "with_arg": { "male": "Привет мужык ;) {}", "female": "Привет девчуля :) {}" } }, "reset_locale": "Сбросить язык" }; static const Map<String, Map<String, dynamic>> mapLocales = { "ar_DZ": ar_DZ, "ar": ar, "de_DE": de_DE, "de": de, "en_US": en_US, "en": en, "ru_RU": ru_RU, "ru": ru }; }
0
mirrored_repositories/easy_localization/example/lib
mirrored_repositories/easy_localization/example/lib/generated/locale_keys.g.dart
// DO NOT EDIT. This is code generated via package:easy_localization/generate.dart abstract class LocaleKeys { static const title = 'title'; static const msg = 'msg'; static const msg_named = 'msg_named'; static const clickMe = 'clickMe'; static const reset_password_label = 'reset_password.label'; static const reset_password_username = 'reset_password.username'; static const reset_password_password = 'reset_password.password'; static const profile_reset_password = 'profile.reset_password'; static const profile = 'profile'; static const clicked = 'clicked'; static const amount = 'amount'; static const gender_with_arg = 'gender.with_arg'; static const gender = 'gender'; static const reset_locale = 'reset_locale'; }
0
mirrored_repositories/easy_localization/example
mirrored_repositories/easy_localization/example/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:example/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/Dr-Health
mirrored_repositories/Dr-Health/lib/main.dart
import 'package:dr_health/src/auth/auth.dart'; import 'package:dr_health/src/components/navigation.dart'; import 'package:dr_health/src/screens/CoronaScreen/corona_stats_screen.dart'; import 'package:dr_health/src/screens/MedicineScreen/add_new_medicine.dart'; import 'package:dr_health/src/screens/SettingsScreen/settings.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:dr_health/src/screens/index.dart'; import 'package:firebase_core/firebase_core.dart'; void main() async { await SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle( systemNavigationBarColor: Colors.black.withOpacity(0.05), statusBarColor: Colors.black.withOpacity(0.05), statusBarIconBrightness: Brightness.dark )); WidgetsFlutterBinding.ensureInitialized(); // Initialize Firebase await Firebase.initializeApp(); runApp(MedicineApp()); } class MedicineApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData( fontFamily: "Popins", ////////////////////////// primaryColor: Colors.green.shade900, //Colors.green, /////////////////////////////// //Color.fromRGBO(7, 190, 200, 1), textTheme: TextTheme( headline1: ThemeData.light().textTheme.headline1.copyWith( fontWeight: FontWeight.w700, fontSize: 38.0, fontFamily: "Popins", ), headline5: ThemeData.light().textTheme.headline1.copyWith( fontWeight: FontWeight.w400, fontSize: 17.0, fontFamily: "Popins", ), headline3: ThemeData.light().textTheme.headline3.copyWith( fontWeight: FontWeight.w600, fontSize: 20.0, fontFamily: "Popins", ))), routes: { "/": (context) => LoginPage(), "/Navigation": (context) => Navigation(), "/home": (context) => Home(), "/AddNewMedicine": (context) => AddNewMedicine(), "CoronaUpdateScreen": (context) => CoronaPage(), "SettingsScreen": (context) => SettingsPage(), }, initialRoute: "/", ); } }
0
mirrored_repositories/Dr-Health/lib
mirrored_repositories/Dr-Health/lib/src/constant.dart
// @dart=2.12 import 'package:flutter/material.dart'; var mainColor = Color(0xff1E1C61); var kBackgroundColor = Colors.indigo[100]; var kWhiteColor = Color(0xffffffff); var kOrangeColor = Color(0xffEF716B); var kBlueColor = Color(0xff4B7FFB); var kYellowColor = Color(0xffFFB167); var kTitleTextColor = Color(0xff1E1C61); var kSearchBackgroundColor = Color(0xffF2F2F2); var kSearchTextColor = Color(0xffC0C0C0); var kCategoryTextColor = Color(0xff292685); var kPrimaryBlack = Color(0xff202c36);
0
mirrored_repositories/Dr-Health/lib/src
mirrored_repositories/Dr-Health/lib/src/handlers/datasource_handler.dart
// @dart=1.12 import 'package:flutter/material.dart'; import 'package:dr_health/src/constant.dart'; Color primaryBlack = kPrimaryBlack; class DataSource { static String quote = "Nothing in life is to be feared, it is only to be understood. Now is the time to understand more, so that we may fear less."; static List licenceAndTerms = [ { "Title" : "Copyright Terms", "Body" : "Copyright 2021 University Computing Center\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", }, { "Title" : "Limitation of Liability", "Body" : "UNDER NO CIRCUMSTANCES SHALL PILL REMINDER SERVICE, OR ITS LICENSORS, AFFILIATES, OFFICERS, DIRECTORS, SHAREHOLDERS, MEMBERS, EMPLOYEES, AGENTS OR ASSIGNS BE LIABLE FOR ANY DIRECT, INDIRECT, PUNITIVE, INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES THAT RESULT FROM THE USE OF, OR INABILITY TO USE, THIS SITE OR SERVICE. THIS LIMITATION APPLIES WHETHER THE ALLEGED LIABILITY IS BASED ON CONTRACT, TORT, NEGLIGENCE, STRICT LIABILITY, OR ANY OTHER BASIS, EVEN IF PILL REMINDER SERVICE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. BECAUSE SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, PILL REMINDER SERVICE’S LIABILITY IN SUCH JURISDICTIONS SHALL BE LIMITED TO THE EXTENT PERMITTED BY LAW.\n\nINFORMATION AND SERVICES INCLUDED IN OR AVAILABLE THROUGH THIS SITE (THE “CONTENT”) ARE PROVIDED “AS IS” AND “AS AVAILABLE” FOR YOUR USE. THE CONTENT IS PROVIDED WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE OR NONINFRINGEMENT. PILL REMINDER SERVICE AND ITS LICENSORS DO NOT WARRANT THAT THE CONTENT IS ACCURATE, RELIABLE OR CORRECT; THAT THIS SITE WILL BE AVAILABLE AT ANY PARTICULAR TIME OR LOCATION; THAT ANY DEFECTS OR ERRORS WILL BE CORRECTED; OR THAT THE CONTENT IS FREE OF VIRUSES OR OTHER HARMFUL COMPONENTS. YOUR USE OF THIS SITE IS SOLELY AT YOUR RISK. BECAUSE SOME JURISDICTIONS DO NOT PERMIT THE EXCLUSION OF CERTAIN WARRANTIES, THESE EXCLUSIONS MAY NOT APPLY TO YOU" }, ]; static List questionAnswers = [ { "question": "What is a coronavirus?", "answer": "Coronaviruses are a large family of viruses which may cause illness in animals or humans. In humans, several coronaviruses are known to cause respiratory infections ranging from the common cold to more severe diseases such as Middle East Respiratory Syndrome (MERS) and Severe Acute Respiratory Syndrome (SARS). The most recently discovered coronavirus causes coronavirus disease COVID-19." }, { "question": "What is COVID-19?", "answer": "COVID-19 is the infectious disease caused by the most recently discovered coronavirus. This new virus and disease were unknown before the outbreak began in Wuhan, China, in December 2019." }, { "question": "What are the symptoms of COVID-19?", "answer": "The most common symptoms of COVID-19 are fever, tiredness, and dry cough. Some patients may have aches and pains, nasal congestion, runny nose, sore throat or diarrhea. These symptoms are usually mild and begin gradually. Some people become infected but don’t develop any symptoms and don't feel unwell. Most people (about 80%) recover from the disease without needing special treatment. Around 1 out of every 6 people who gets COVID-19 becomes seriously ill and develops difficulty breathing. Older people, and those with underlying medical problems like high blood pressure, heart problems or diabetes, are more likely to develop serious illness. People with fever, cough and difficulty breathing should seek medical attention." }, { "question": "How does COVID-19 spread?", "answer": "People can catch COVID-19 from others who have the virus. The disease can spread from person to person through small droplets from the nose or mouth which are spread when a person with COVID-19 coughs or exhales. These droplets land on objects and surfaces around the person. Other people then catch COVID-19 by touching these objects or surfaces, then touching their eyes, nose or mouth. People can also catch COVID-19 if they breathe in droplets from a person with COVID-19 who coughs out or exhales droplets. This is why it is important to stay more than 1 meter (3 feet) away from a person who is sick. \nWHO is assessing ongoing research on the ways COVID-19 is spread and will continue to share updated findings." }, { "question": "Can the virus that causes COVID-19 be transmitted through the air?", "answer": "Studies to date suggest that the virus that causes COVID-19 is mainly transmitted through contact with respiratory droplets rather than through the air" }, { "question": "Can CoVID-19 be caught from a person who has no symptoms?", "answer": "The main way the disease spreads is through respiratory droplets expelled by someone who is coughing. The risk of catching COVID-19 from someone with no symptoms at all is very low. However, many people with COVID-19 experience only mild symptoms. This is particularly true at the early stages of the disease. It is therefore possible to catch COVID-19 from someone who has, for example, just a mild cough and does not feel ill. WHO is assessing ongoing research on the period of transmission of COVID-19 and will continue to share updated findings. " }, { "question": "Can I catch COVID-19 from the feces of someone with the disease?", "answer": "The risk of catching COVID-19 from the feces of an infected person appears to be low. While initial investigations suggest the virus may be present in feces in some cases, spread through this route is not a main feature of the outbreak. WHO is assessing ongoing research on the ways COVID-19 is spread and will continue to share new findings. Because this is a risk, however, it is another reason to clean hands regularly, after using the bathroom and before eating." }, { "question": "How likely am I to catch COVID-19?", "answer": "The risk depends on where you are - and more specifically, whether there is a COVID-19 outbreak unfolding there.\nFor most people in most locations the risk of catching COVID-19 is still low. However, there are now places around the world (cities or areas) where the disease is spreading. For people living in, or visiting, these areas the risk of catching COVID-19 is higher. Governments and health authorities are taking vigorous action every time a new case of COVID-19 is identified. Be sure to comply with any local restrictions on travel, movement or large gatherings. Cooperating with disease control efforts will reduce your risk of catching or spreading COVID-19.\nCOVID-19 outbreaks can be contained and transmission stopped, as has been shown in China and some other countries. Unfortunately, new outbreaks can emerge rapidly. It’s important to be aware of the situation where you are or intend to go. WHO publishes daily updates on the COVID-19 situation worldwide." }, { "question": "Who is at risk of developing severe illness?", "answer": "While we are still learning about how COVID-2019 affects people, older persons and persons with pre-existing medical conditions (such as high blood pressure, heart disease, lung disease, cancer or diabetes) appear to develop serious illness more often than others. " }, { "question": "Should I wear a mask to protect myself?", "answer": "Only wear a mask if you are ill with COVID-19 symptoms (especially coughing) or looking after someone who may have COVID-19. Disposable face mask can only be used once. If you are not ill or looking after someone who is ill then you are wasting a mask. There is a world-wide shortage of masks, so WHO urges people to use masks wisely.\nWHO advises rational use of medical masks to avoid unnecessary wastage of precious resources and mis-use of masks\nThe most effective ways to protect yourself and others against COVID-19 are to frequently clean your hands, cover your cough with the bend of elbow or tissue and maintain a distance of at least 1 meter (3 feet) from people who are coughing or sneezing" }, { "question": "Are antibiotics effective in preventing or treating the COVID-19?", "answer": "No. Antibiotics do not work against viruses, they only work on bacterial infections. COVID-19 is caused by a virus, so antibiotics do not work. Antibiotics should not be used as a means of prevention or treatment of COVID-19. They should only be used as directed by a physician to treat a bacterial infection. " } ]; }
0
mirrored_repositories/Dr-Health/lib/src
mirrored_repositories/Dr-Health/lib/src/handlers/video_player_handler.dart
// @dart=2.12 import 'package:flutter/material.dart'; import 'package:video_player/video_player.dart'; class MyVideoPlayer extends StatefulWidget { final assetFile; MyVideoPlayer({Key? key, this.assetFile}) : super(key: key); @override _MyVideoPlayer createState() => _MyVideoPlayer(); } class _MyVideoPlayer extends State<MyVideoPlayer> { late VideoPlayerController _videoController; @override void initState() { super.initState(); _videoController = VideoPlayerController.asset(widget.assetFile) ..addListener(() => setState(() {})) ..initialize(); } @override Widget build(BuildContext context) { return Align( alignment: Alignment.center, child: _videoController.value.isInitialized ? _buildVideoPlayerUI() : const CircularProgressIndicator(), ); } Widget _buildVideoPlayerUI() { return Stack( alignment: Alignment.center, fit: StackFit.expand, children: [ AspectRatio( aspectRatio: _videoController.value.aspectRatio, child: VideoPlayer(_videoController), ), Column( mainAxisAlignment: MainAxisAlignment.end, children: [ TextButton( onPressed: () => _videoController.value.isPlaying ? _videoController.pause() : _videoController.play(), child: Icon(_videoController.value.isPlaying ? Icons.pause : Icons.play_arrow, color: Colors.greenAccent), ), VideoProgressIndicator(_videoController, allowScrubbing: true, colors: VideoProgressColors( playedColor: Colors.greenAccent)), ], ), ], ); } @override void dispose() { _videoController.dispose(); super.dispose(); } }
0
mirrored_repositories/Dr-Health/lib/src
mirrored_repositories/Dr-Health/lib/src/handlers/firebase_search_controller.dart
// @dart=2.12 import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:get/get.dart'; class DataController extends GetxController { Future getData(String collection) async { try { final FirebaseFirestore firebaseFirestore = FirebaseFirestore.instance; final QuerySnapshot<Map<String, dynamic>> snapshot = await firebaseFirestore.collection(collection).get(); return snapshot.docs; } catch(Ex) { return "No Query Specified"; } } // Future queryFullName(String doctorName) async { // return await FirebaseFirestore.instance // .collection('doctors_details') // .where('Fname . Lname',isGreaterThanOrEqualTo: doctorName) // .get(); // } Future queryPosition(String doctorPosition) async { try { return await FirebaseFirestore.instance .collection('doctors_details') .where('Position',isGreaterThanOrEqualTo: doctorPosition) .get(); } catch(Ex) { return "No Query Specified"; } } }
0
mirrored_repositories/Dr-Health/lib/src
mirrored_repositories/Dr-Health/lib/src/handlers/notifications_handler.dart
import 'dart:typed_data'; import 'package:flutter/cupertino.dart'; import 'package:timezone/timezone.dart' as tz; import 'package:flutter/material.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; class Notifications { BuildContext _context; Future<FlutterLocalNotificationsPlugin> initNotifies(BuildContext context) async{ this._context = context; //-----------------------------| Inicialize local notifications |-------------------------------------- var initializationSettingsAndroid = new AndroidInitializationSettings('app_icon'); var initializationSettings = new InitializationSettings( android: initializationSettingsAndroid); FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin(); flutterLocalNotificationsPlugin.initialize(initializationSettings, onSelectNotification: onSelectNotification); return flutterLocalNotificationsPlugin; //====================================================================================================== } //---------------------------------| Show the notification in the specific time |------------------------------- Future showNotification(String title, String description, int time, int id, FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin) async { await flutterLocalNotificationsPlugin.zonedSchedule( id.toInt(), title, description, tz.TZDateTime.now(tz.local).add(Duration(milliseconds: time)), NotificationDetails( android: AndroidNotificationDetails( 'Dr Health Med Reminder', // channel id 'Notification reminders', // channel name 'Dr Health Mediciation Reminder', // channel route playSound: true, showWhen: true, autoCancel: true, visibility: NotificationVisibility.public, ongoing: true, enableVibration: true, vibrationPattern: Int64List.fromList([8, 8, 8, 8]), enableLights: true, subText: "Med Reminder", icon: 'launcher_logo', largeIcon: DrawableResourceAndroidBitmap('launcher_logo'), sound: RawResourceAndroidNotificationSound('longcoldsting'), color: Colors.cyanAccent, importance: Importance.high, priority: Priority.high, additionalFlags: Int32List.fromList([4, 4, 4, 4]), ) ), androidAllowWhileIdle: true, uiLocalNotificationDateInterpretation: UILocalNotificationDateInterpretation.absoluteTime); } //================================================================================================================ //-------------------------| Cancel the notify |--------------------------- Future removeNotify(int notifyId, FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin) async{ try{ return await flutterLocalNotificationsPlugin.cancel(notifyId); }catch(e){ return null; } } //========================================================================== //-------------| function to inicialize local notifications |--------------------------- Future onSelectNotification(String payload) async { showDialog( context: _context, builder: (_) { return new AlertDialog( title: Text("Congratulations", style: TextStyle(fontWeight: FontWeight.bold),), content: Text("Medicine Taken."), ); }, ); } //====================================================================================== }
0
mirrored_repositories/Dr-Health/lib/src
mirrored_repositories/Dr-Health/lib/src/database/pills_database.dart
import 'package:path/path.dart'; import 'package:sqflite/sqflite.dart'; class PillsDatabase{ setDatabase() async{ String databasePath = await getDatabasesPath(); String path = join(databasePath,"medicine_db"); Database database = await openDatabase(path, version: 1, onCreate: (Database db,int version) async { await db.execute("CREATE TABLE Pills (id INTEGER PRIMARY KEY, name TEXT, description TEXT, amount TEXT, type TEXT, medicineForm TEXT, time INTEGER, notifyId INTEGER)"); }); return database; } }
0
mirrored_repositories/Dr-Health/lib/src
mirrored_repositories/Dr-Health/lib/src/database/repository.dart
import 'package:dr_health/src/database/pills_database.dart'; import 'package:sqflite/sqflite.dart'; class Repository{ PillsDatabase _pillsDatabase = PillsDatabase(); static Database _database; //init database Future<Database> get database async{ if(_database != null) return _database; _database = await _pillsDatabase.setDatabase(); return _database; } //insert data to database Future<int> insertData(String table, Map<String,dynamic> data) async { Database db = await database; try{ return await db.insert(table, data); }catch(e){ return null; } } //get all data from database Future<List<Map<String,dynamic>>> getAllData(table) async { Database db = await database; try{ return db.query(table); }catch(e){ return null; } } //delete data Future<int> deleteData(String table,int id) async{ Database db = await database; try{ return await db.delete(table,where: "id = ?", whereArgs: [id]); }catch(e){ return null; } } }
0
mirrored_repositories/Dr-Health/lib/src
mirrored_repositories/Dr-Health/lib/src/components/navigations_old.dart
// @dart=2.12 // ignore_for_file: import_of_legacy_library_into_null_safe import 'package:dr_health/src/screens/HealthDataScreen/health_data_screen.dart'; import 'package:dr_health/src/screens/SearchScreen/doctors_list.dart'; import 'package:dr_health/src/screens/index.dart'; import 'package:flutter/material.dart'; class Navigation extends StatefulWidget { const Navigation({Key? key}) : super(key: key); @override State<StatefulWidget> createState() => _NavigationState(); } class _NavigationState extends State<Navigation> with SingleTickerProviderStateMixin { int _currentTabIndex = 1; @override Widget build(BuildContext context) { // Screens final _kTabPages = <Widget>[ DoctorSearchScreen(), // at index 0, Search Home(), // at index 1, Home HealthData(), // at index 2, Health Data ]; // Navigations final _kBottomNavBarItems = <BottomNavigationBarItem>[ const BottomNavigationBarItem( icon: Icon(Icons.search_rounded, color: Colors.white), activeIcon: Icon(Icons.search_rounded, color: Colors.lightGreenAccent), label: 'Search', backgroundColor: Colors.green), const BottomNavigationBarItem( icon: Icon(Icons.add_alarm_rounded, color: Colors.white), activeIcon: Icon(Icons.add_alarm_rounded, color: Colors.lightGreenAccent), label: 'Reminders', backgroundColor: Colors.green), const BottomNavigationBarItem( icon: Icon(Icons.dashboard_rounded, color: Colors.white), activeIcon: Icon(Icons.dashboard_rounded, color: Colors.lightGreenAccent), label: 'Health Data', backgroundColor: Colors.green), ]; assert(_kTabPages.length == _kBottomNavBarItems.length); final bottomNavBar = BottomNavigationBar( showSelectedLabels: false, showUnselectedLabels: false, backgroundColor: Theme.of(context).primaryColor, // unselectedItemColor: Colors.white, // selectedItemColor: Colors.lightGreenAccent, items: _kBottomNavBarItems, currentIndex: _currentTabIndex, // type: BottomNavigationBarType.shifting, onTap: (int index) { setState(() { _currentTabIndex = index; }); }, ); return Scaffold( resizeToAvoidBottomInset: true, body: _kTabPages[_currentTabIndex], bottomNavigationBar: bottomNavBar, ); } }
0
mirrored_repositories/Dr-Health/lib/src
mirrored_repositories/Dr-Health/lib/src/components/navigation.dart
// @dart=2.12 // ignore_for_file: import_of_legacy_library_into_null_safe import 'package:dr_health/src/screens/HealthDataScreen/health_data_screen.dart'; import 'package:dr_health/src/screens/SearchScreen/doctors_list.dart'; // import 'package:dr_health/src/screens/SearchScreen/local_search.dart'; // import 'package:dr_health/src/screens/SearchScreen/search.dart'; import 'package:dr_health/src/screens/index.dart'; import 'package:flutter/material.dart'; import 'package:curved_navigation_bar/curved_navigation_bar.dart'; class Navigation extends StatefulWidget { const Navigation({Key? key}) : super(key: key); @override _NavigationState createState() => _NavigationState(); } class _NavigationState extends State<Navigation> { final navigationKey = GlobalKey<CurvedNavigationBarState>(); int tabIndex = 1; final screens = [ // LocalSearch(), // // Search(), // DoctorSearchScreen(), // at index 0, Search Home(), // at index 1, Home HealthData(), // at index 2, Health Data ]; @override Widget build(BuildContext context) { final items = <Widget> [ Icon(Icons.search, size: 30), Icon(Icons.alarm_add, size: 30), Icon(Icons.dashboard_rounded, size: 30), ]; final navigationIcons = Theme ( data: Theme.of(context).copyWith( iconTheme: IconThemeData(color: Colors.white), ), child: Padding( padding: const EdgeInsets.only(top: 38.0), child: CurvedNavigationBar( color: Theme.of(context).primaryColor, backgroundColor: Colors.transparent, height: 60, animationCurve: Curves.easeInOut, animationDuration: Duration(milliseconds: 300), index: tabIndex, items: items, onTap: (index) => setState(() => this.tabIndex = index), ), ), ); return SafeArea( top: false, child: ClipRect( child: Scaffold( extendBody: true, resizeToAvoidBottomInset: true, body: screens[tabIndex], bottomNavigationBar: navigationIcons ), ), ); } }
0
mirrored_repositories/Dr-Health/lib/src/components
mirrored_repositories/Dr-Health/lib/src/components/cards/medicine_card.dart
// ignore_for_file: deprecated_member_use import 'package:flutter/material.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:intl/intl.dart'; import 'package:dr_health/src/database/repository.dart'; import 'package:dr_health/src/models/pill.dart'; import 'package:dr_health/src/handlers/notifications_handler.dart'; class MedicineCard extends StatelessWidget { final Pill medicine; final Function setData; final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin; MedicineCard(this.medicine,this.setData,this.flutterLocalNotificationsPlugin); @override Widget build(BuildContext context) { //check if the medicine time is lower than actual final bool isEnd = DateTime.now().millisecondsSinceEpoch > medicine.time; return Card( shadowColor: Colors.greenAccent.shade200, elevation: 8.0, margin: EdgeInsets.symmetric(vertical: 7.0), color: Theme.of(context).primaryColor.withOpacity(1.0), //Colors.white, child: ListTile( shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)), onLongPress: () => _showDeleteDialog(context, medicine.name, medicine.id, medicine.notifyId), contentPadding: EdgeInsets.symmetric(vertical: 15.0, horizontal: 15.0), title: Text( medicine.name, style: Theme.of(context).textTheme.headline1.copyWith( color: Colors.white70, fontSize: 20.0, decoration: isEnd ? TextDecoration.lineThrough : null), maxLines: 1, overflow: TextOverflow.ellipsis, ), subtitle: Text( "${medicine.description}" + "\n" + "${medicine.amount} ${medicine.medicineForm}", style: Theme.of(context).textTheme.headline5.copyWith( color: Colors.white70, fontSize: 15.0, fontWeight: FontWeight.w500, decoration: isEnd ? TextDecoration.lineThrough : null), maxLines: 3, overflow: TextOverflow.ellipsis, ), isThreeLine: true, trailing: Column( mainAxisAlignment: MainAxisAlignment.start, children: [ Text( DateFormat("HH:mm").format( DateTime.fromMillisecondsSinceEpoch(medicine.time)), style: TextStyle( color: Colors.white70, fontWeight: FontWeight.w500, fontSize: 15, decoration: isEnd ? TextDecoration.lineThrough : null), ), ], ), leading: Container( width: 60.0, height: 60.0, child: ClipRRect( borderRadius: BorderRadius.circular(50.0), child: ColorFiltered( colorFilter: ColorFilter.mode( isEnd ? Colors.white : Colors.transparent, BlendMode.saturation), child: Image.asset( medicine.image )), ), ), ), ); } //--------------------------| SHOW THE DELETE DIALOG ON THE SCREEN |----------------------- void _showDeleteDialog(BuildContext context, String medicineName, int medicineId, int notifyId) { showDialog( context: context, builder: (context) => AlertDialog( title: Text("Delete ?"), content: Text("Are you sure to delete $medicineName medicine?"), contentTextStyle: TextStyle(fontSize: 17.0, color: Colors.grey[800]), actions: [ FlatButton( splashColor: Theme.of(context).primaryColor.withOpacity(0.3), child: Text( "Cancel", style: TextStyle(color: Theme.of(context).primaryColor), ), onPressed: () { Navigator.of(context).pop(); }, ), FlatButton( splashColor: Theme.of(context).primaryColor.withOpacity(0.3), child: Text("Delete", style: TextStyle(color: Theme.of(context).primaryColor)), onPressed: () async { await Repository().deleteData('Pills', medicineId); await Notifications().removeNotify(notifyId, flutterLocalNotificationsPlugin); setData(); Navigator.pop(context); }, ), ], )); } //============================================================================================ }
0
mirrored_repositories/Dr-Health/lib/src/components
mirrored_repositories/Dr-Health/lib/src/components/cards/medicine_type_card.dart
import 'package:flutter/material.dart'; import 'package:dr_health/src/models/medicine_type.dart'; class MedicineTypeCard extends StatelessWidget { final MedicineType pillType; final Function handler; MedicineTypeCard(this.pillType, this.handler); @override Widget build(BuildContext context) { return Row( children: [ GestureDetector( onTap: () => handler(pillType), child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(10.0), color: pillType.isChoose ? Colors.lightGreen.shade400 : Colors.white, ), width: 100, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox(height: 5.0,), Container(width:50,height: 50.0,child: pillType.image,), SizedBox(height: 7.0,), Container(child: Text(pillType.name, style: TextStyle( color:pillType.isChoose ? Colors.white : Colors.black, fontWeight: FontWeight.w500, ),)), ], ), ), ), SizedBox(width: 15.0,) ], ); } }
0
mirrored_repositories/Dr-Health/lib/src/components
mirrored_repositories/Dr-Health/lib/src/components/cards/cards.dart
// @dart=2.12 // ignore_for_file: import_of_legacy_library_into_null_safe import 'package:dr_health/src/screens/HealthDataScreen/Activity/activity_screen.dart'; import 'package:dr_health/src/screens/HealthDataScreen/Mindfulness/mindfulness_screen.dart'; import 'package:dr_health/src/screens/HealthDataScreen/Nutrition/nutrition_screen.dart'; import 'package:dr_health/src/screens/HealthDataScreen/sleep/sleep_screen.dart'; import 'package:flutter/material.dart'; import 'package:url_launcher/url_launcher.dart'; // Health Category Card class HealthCatCard extends StatelessWidget { @override Widget build(BuildContext context) { return Container( child: GridView( shrinkWrap: true, physics: NeverScrollableScrollPhysics(), gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, childAspectRatio: 2), children: <Widget>[ InkWell( child: HealthCatCardStyle( title: 'Activity', panelColor: Colors.red, textColor: Colors.white, // imageBanner: "assets/images/sleep_banner.png", ), onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => ActivityScreen()), ); }, ), InkWell( child: HealthCatCardStyle( title: 'Mindfulness', panelColor: Colors.green, textColor: Colors.white, // imageBanner: "assets/images/sleep_banner.png", ), onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => MindfulnessScreen()), ); }, ), InkWell( child: HealthCatCardStyle( title: 'Nutrition', panelColor: Colors.blue, textColor: Colors.white, // imageBanner: "assets/images/sleep_banner.png", ), onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => NutritionScreen()), ); }, ), InkWell( child: HealthCatCardStyle( title: 'Sleep', panelColor: Colors.black45, textColor: Colors.white, // imageBanner: "assets/images/sleep_banner.png", ), onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => SleepScreen()), ); }, ), ], ), ); } } // Style for the Health Category Card class HealthCatCardStyle extends StatelessWidget { final Color panelColor; final Color textColor; final String title; final imageBanner; HealthCatCardStyle( {Key? key, required this.panelColor, required this.textColor, required this.title, this.imageBanner}) : super(key: key); @override Widget build(BuildContext context) { double width = MediaQuery.of(context).size.width; return Container( margin: EdgeInsets.all(10), height: 80, width: width / 2, color: panelColor, child: Column( children: <Widget>[ Expanded( child: Align( alignment: Alignment.center, child: Padding( padding: const EdgeInsets.only(left: 18.0), child: Text( title, style: TextStyle( color: Colors.white, fontSize: 18.0, fontWeight: FontWeight.bold), ), ), ), ), // Expanded( // child: Align( // alignment: Alignment.centerRight, // child: Image.asset( // imageBanner, // ), // ), // ), ], ), ); } } // Articles Card class ArticlesCard extends StatelessWidget { final subtitle; final urlink; ArticlesCard(this.subtitle, this.urlink); @override Widget build(BuildContext context) { return Container( alignment: Alignment.topLeft, padding: const EdgeInsets.only(left: 12.0, top: 5.0, bottom: 5.0, right: 12.0), child: InkWell( child: Card( shadowColor: Colors.grey, elevation: 5.0, color: Theme.of(context).primaryColor.withOpacity(0.9), child: ListTile( subtitle: Padding( padding: const EdgeInsets.only(top: 4.0, bottom: 4.0), child: Text( subtitle, style: TextStyle( fontSize: 16.0, fontWeight: FontWeight.normal, color: Colors.white), ), ), trailing: InkWell( onTap: () => _launchURL(urlink), child: Icon(Icons.read_more_rounded, size: 60.0, color: Colors.white), ), ), ), onTap: () => _launchURL(urlink), ), ); } } // URL LAUNCHER _launchURL(urlink) async { if (await canLaunch(urlink)) { await launch(urlink, forceWebView: true); } else { throw 'Could not launch $urlink'; } } // ignore: must_be_immutable class MedShape extends StatelessWidget { String shapeName; Color? shapeColor; MedShape(this.shapeName, {this.shapeColor}); // String shapeName = this.shapeName; @override Widget build(BuildContext context) { return Image.asset(this.shapeName, color: this.shapeColor, height: 60.0, width: 60.0, scale: 1.0,); } } // CORONA STYLE PAGE class WorldwidePanel extends StatelessWidget { final Map worldData; const WorldwidePanel({Key? key, required this.worldData}) : super(key: key); @override Widget build(BuildContext context) { return Container( child: GridView( shrinkWrap: true, physics: NeverScrollableScrollPhysics(), gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, childAspectRatio: 2), children: <Widget>[ StatusPanel( title: 'CONFIRMED', panelColor: Colors.red, textColor: Colors.white, count: worldData['cases'].toString(), ), StatusPanel( title: 'ACTIVE', panelColor: Colors.lightBlue, textColor: Colors.white, count: worldData['active'].toString(), ), StatusPanel( title: 'RECOVERED', panelColor: Colors.lightGreen, textColor: Colors.white, count: worldData['recovered'].toString(), ), StatusPanel( title: 'DEATHS', panelColor: Colors.grey, textColor: Colors.white, count: worldData['deaths'].toString(), ), ], ), ); } } // CORONA CARD STYLE class StatusPanel extends StatelessWidget { final Color panelColor; final Color textColor; final String title; final String count; const StatusPanel( {Key? key, required this.panelColor, required this.textColor, required this.title, required this.count}) : super(key: key); @override Widget build(BuildContext context) { double width = MediaQuery.of(context).size.width; return Container( margin: EdgeInsets.all(10), height: 80, width: width / 2, color: panelColor, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( title, style: TextStyle( fontWeight: FontWeight.bold, fontSize: 16, color: textColor), ), Text( count, style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, color: textColor), ) ], ), ); } }
0
mirrored_repositories/Dr-Health/lib/src/components
mirrored_repositories/Dr-Health/lib/src/components/widgets/AppDrawer.dart
// @dart=2.12 // ignore_for_file: import_of_legacy_library_into_null_safe import 'package:dr_health/src/auth/auth.dart'; // import 'package:dr_health/src/auth/login.dart'; import 'package:dr_health/src/utils/app_shared_preference.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:url_launcher/url_launcher.dart'; class AppDrawer extends StatefulWidget { @override State<AppDrawer> createState() => _AppDrawerState(); } class _AppDrawerState extends State<AppDrawer> { String user_email = "Dr. Health"; @override void initState() { super.initState(); user_email = AppPreferences.getUserEmail().toString(); } @override Widget build(BuildContext context) { final whSize = MediaQuery.of(context).size.height / MediaQuery.of(context).size.width; return Drawer( child: SafeArea( child: ListView( padding: EdgeInsets.zero, children: [ DrawerHeader( curve: Curves.bounceInOut, duration: const Duration(milliseconds: 300), decoration: BoxDecoration( color: Theme.of(context).primaryColor, //Colors.green, shape: BoxShape.rectangle, image: DecorationImage( image: AssetImage('assets/images/doctor100.png'), )), child: Text(""), ), Padding( padding: const EdgeInsets.only(left: 15.0), child: Text( "Websites", style: TextStyle( color: Colors.black38, fontSize: whSize * 6, ), ), ), ListTile( leading: Icon(Icons.web_rounded, size: whSize * 15, color: Theme.of(context).primaryColor,), title: Text( 'Visit UHC Website', style: TextStyle( fontSize: whSize * 7, ), ), onTap: () { launch('https://www.udsm.ac.tz/web/index.php/centres/uhc'); }, ), ListTile( leading: Icon(Icons.web_rounded, size: whSize * 15, color: Theme.of(context).primaryColor,), title: Text( 'Visit UCC Website', style: TextStyle( fontSize: whSize * 7, ), ), onTap: () { launch('https://www.ucc.co.tz/'); }, ), Divider(), Padding( padding: const EdgeInsets.only(left: 15.0), child: Text( "Communicate", style: TextStyle( color: Colors.black38, fontSize: whSize * 6, ), ), ), ListTile( leading: Icon(Icons.mail, size: whSize * 15, color: Theme.of(context).primaryColor,), title: Text( 'Mail UHC', style: TextStyle( fontSize: whSize * 7, ), ), onTap: () async { String toEmail = 'healthcentre@udsm.ac.tz'; String subject = 'Your Subject Here...'; String message = 'Your Message Here...'; final url = 'mailto:$toEmail?subject=${Uri.encodeFull(subject)}&body=${Uri.encodeFull(message)}'; if(await canLaunch(url)) { await launch(url); } else { launch(url); } }, ), ListTile( leading: Icon(Icons.feedback, size: whSize * 15, color: Theme.of(context).primaryColor,), title: Text( 'Feedback', style: TextStyle( fontSize: whSize * 7, ), ), onTap: () async { String toEmail = 'healthdr.customer.care@gmail.com'; String subject = 'Dr. Health Client Feedback'; String message = 'Please provide your short feedback...'; final url = 'mailto:$toEmail?subject=${Uri.encodeFull(subject)}&body=${Uri.encodeFull(message)}'; if(await canLaunch(url)) { await launch(url); } else { launch(url); } }, ), Divider(), Padding( padding: const EdgeInsets.only(left: 15.0), child: Text( "Settings", style: TextStyle( color: Colors.black38, fontSize: whSize * 6, ), ), ), ListTile( leading: Icon(Icons.settings, size: whSize * 15, color: Theme.of(context).primaryColor,), title: Text( 'Settings', style: TextStyle( fontSize: MediaQuery.of(context).size.height / MediaQuery.of(context).size.width * 7, ), ), onTap: () { Navigator.popAndPushNamed(context, 'SettingsScreen'); }, ), Divider(), Padding( padding: const EdgeInsets.only(left: 15.0), child: Text( "Logout", style: TextStyle( color: Colors.black38, fontSize: whSize * 6, ), ), ), ListTile( leading: Icon(Icons.logout_outlined, size: whSize * 15, color: Theme.of(context).primaryColor,), title: Text( 'Logout', style: TextStyle( fontSize: MediaQuery.of(context).size.height / MediaQuery.of(context).size.width * 7, ), ), onTap: () { _signOut(); Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => LoginPage()),); }, ) ], ), ), ); } } Future<void> _signOut() async { await FirebaseAuth.instance.signOut(); }
0
mirrored_repositories/Dr-Health/lib/src/components
mirrored_repositories/Dr-Health/lib/src/components/widgets/slider.dart
import 'package:flutter/material.dart'; import 'package:dr_health/src/helpers/platform_slider.dart'; class UserSlider extends StatelessWidget { final Function handler; final int howManyWeeks; UserSlider(this.handler,this.howManyWeeks); @override Widget build(BuildContext context) { return Row( children: [ Expanded( child: PlatformSlider( divisions: 11, min: 1, max: 10, value: howManyWeeks, color: Theme.of(context).primaryColor, handler: this.handler,)), ], ); } }
0
mirrored_repositories/Dr-Health/lib/src/components
mirrored_repositories/Dr-Health/lib/src/components/panels/most_affected_countries.dart
// @dart=2.12 import 'package:flutter/material.dart'; class MostAffectedPanel extends StatelessWidget { final List countryData; const MostAffectedPanel({Key? key, required this.countryData}) : super(key: key); @override Widget build(BuildContext context) { return Container( child: ListView.builder( shrinkWrap: true, physics: NeverScrollableScrollPhysics(), itemBuilder: (context, index) { return Container( margin: EdgeInsets.symmetric(horizontal: 10, vertical: 10), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Image.network( countryData[index]['countryInfo']['flag'], height: 30, width: 40, ), SizedBox( width: 10, ), Text( countryData[index]['country'], style: TextStyle(fontWeight: FontWeight.bold), ), SizedBox( width: 10, ), Text( 'Deaths:' + countryData[index]['deaths'].toString(), style: TextStyle(color: Colors.red, fontWeight: FontWeight.bold), ) ], ), ); }, itemCount: 5, ), ); } }
0
mirrored_repositories/Dr-Health/lib/src/components
mirrored_repositories/Dr-Health/lib/src/components/panels/info_panel.dart
import 'package:flutter/material.dart'; import 'package:dr_health/src/handlers/datasource_handler.dart'; import 'package:dr_health/src/screens/CoronaScreen/faqs.dart'; import 'package:url_launcher/url_launcher.dart'; class InfoPanel extends StatelessWidget { @override Widget build(BuildContext context) { return Container( child: Column( children: <Widget>[ GestureDetector( onTap: () { Navigator.push( context, MaterialPageRoute(builder: (context) => FAQPage())); }, child: Container( padding: EdgeInsets.symmetric(vertical: 12, horizontal: 10), margin: EdgeInsets.symmetric(vertical: 5, horizontal: 10), color: primaryBlack, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Text( 'FAQS', style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 18), ), Icon( Icons.arrow_forward, color: Colors.white, ) ], ), ), ), GestureDetector( onTap: () { launch('https://covid19responsefund.org/'); }, child: Container( padding: EdgeInsets.symmetric(vertical: 12, horizontal: 10), margin: EdgeInsets.symmetric(vertical: 5, horizontal: 10), color: primaryBlack, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Text( 'DONATE', style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 18), ), Icon( Icons.arrow_forward, color: Colors.white, ) ], ), ), ), GestureDetector( onTap: () { launch( 'https://www.who.int/emergencies/diseases/novel-coronavirus-2019/advice-for-public/myth-busters'); }, child: Container( padding: EdgeInsets.symmetric(vertical: 12, horizontal: 10), margin: EdgeInsets.symmetric(vertical: 5, horizontal: 10), color: primaryBlack, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Text( 'MYTH BUSTERS', style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 18), ), Icon( Icons.arrow_forward, color: Colors.white, ) ], ), ), ) ], ), ); } }
0
mirrored_repositories/Dr-Health/lib/src/components
mirrored_repositories/Dr-Health/lib/src/components/HealthData/activity_data.dart
// @dart=2.12 import 'package:dr_health/src/handlers/video_player_handler.dart'; import 'package:flutter/material.dart'; class ActivityData extends StatefulWidget { @override _ActivityDataState createState() => _ActivityDataState(); } class _ActivityDataState extends State<ActivityData> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Theme.of(context).primaryColor, elevation: 6.0, shadowColor: Colors.blueGrey, title: Text("Health Data"), ), body: SingleChildScrollView( scrollDirection: Axis.vertical, child: SafeArea( child: Stack( children: [ Column( children: [ Container( alignment: Alignment.topLeft, padding: const EdgeInsets.only(top: 6.0, left: 25.0, bottom: 5.0), child: Text( "Activity", style: TextStyle( fontSize: 25.0, color: Colors.black, fontWeight: FontWeight.bold), ), ), Container( color: Colors.black12, width: 400.0, height: 2.0, ), Container( alignment: Alignment.topLeft, padding: const EdgeInsets.only(top: 20.0, left: 25.0, bottom: 8.0), child: Text( "Sit less. Move more. Get some exercise.", style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold), ), ), Container( height: 230.0, decoration: BoxDecoration( borderRadius: BorderRadius.circular(30.0), ), child: Stack( children: [ Container( padding: EdgeInsets.symmetric( horizontal: 16, vertical: 16, ), child: Align( alignment: Alignment.center, child: MyVideoPlayer(assetFile: "assets/videos/Apple_Health_Activity.mp4") ), ), ], ), ), Container( alignment: Alignment.topLeft, padding: const EdgeInsets.only(left: 12.0, top: 5.0, bottom: 8.0), child: ListTile( title: Text( "Steps", style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold), ), subtitle: Padding( padding: const EdgeInsets.only(top: 6.0), child: Text( "Step count is the number of steps you take throughout the day. Includes walking, running, stair-climbing and even movement as you go about your daily chores.", style: TextStyle(fontSize: 16.0, fontWeight: FontWeight.normal), ), ), ), ), ], ), ], ), ), ), ); } } class AccelerometerEvents { }
0
mirrored_repositories/Dr-Health/lib/src/components
mirrored_repositories/Dr-Health/lib/src/components/HealthData/nutrition_data.dart
// @dart=2.12 import 'package:dr_health/src/handlers/video_player_handler.dart'; import 'package:flutter/material.dart'; class NutritionData extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Theme.of(context).primaryColor, elevation: 6.0, shadowColor: Colors.blueGrey, title: Text("Health Data"), ), body: SingleChildScrollView( scrollDirection: Axis.vertical, child: SafeArea( child: Stack( children: [ Column( children: [ Container( alignment: Alignment.topLeft, padding: const EdgeInsets.only(top: 6.0, left: 25.0, bottom: 5.0), child: Text( "Nutrition", style: TextStyle( fontSize: 25.0, color: Colors.black, fontWeight: FontWeight.bold), ), ), Container( color: Colors.black12, width: 400.0, height: 2.0, ), Container( alignment: Alignment.topLeft, padding: const EdgeInsets.only(top: 20.0, left: 25.0, bottom: 8.0), child: Text( "Eat more real food. Eat less junk food. Watch the amount.", style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold), ), ), Container( height: 230.0, decoration: BoxDecoration( borderRadius: BorderRadius.circular(30.0), ), child: Stack( children: [ Container( padding: EdgeInsets.symmetric( horizontal: 16, vertical: 16, ), child: Align( alignment: Alignment.center, child: MyVideoPlayer(assetFile: "assets/videos/Apple_Health_Nutrition.mp4") ), ), ], ), ), Padding( padding: const EdgeInsets.only(left: 12.0, top: 5.0, bottom: 8.0), child: Column( children: [ ListTile( title: Text( "Nutrition is the study of nutrients in food, how the body uses them, and the relationship between diet, health, and disease. Nutritionists use ideas from molecular biology, biochemistry, and genetics to understand how nutrients affect the human body.", style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.normal), ), ), ], ), ), ], ), ], ), ), ), ); } }
0
mirrored_repositories/Dr-Health/lib/src/components
mirrored_repositories/Dr-Health/lib/src/components/HealthData/sleep_data.dart
// @dart=2.12 import 'package:dr_health/src/components/cards/cards.dart' as card; import 'package:dr_health/src/handlers/video_player_handler.dart'; import 'package:flutter/material.dart'; class SleepData extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Theme.of(context).primaryColor, elevation: 6.0, shadowColor: Colors.blueGrey, title: Text("Health Data"), ), body: SingleChildScrollView( scrollDirection: Axis.vertical, child: SafeArea( child: Stack( children: [ Column( children: [ Container( alignment: Alignment.topLeft, padding: const EdgeInsets.only(top: 6.0, left: 25.0, bottom: 5.0), child: Text( "Sleep", style: TextStyle( fontSize: 25.0, color: Colors.black, fontWeight: FontWeight.bold), ), ), Container( color: Colors.black12, width: 400.0, height: 2.0, ), Container( alignment: Alignment.topLeft, padding: const EdgeInsets.only(top: 20.0, left: 25.0, bottom: 8.0), child: Text( "Set a bedtime. Wake at the same time. Stay consistent.", style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold), ), ), Container( height: 230.0, decoration: BoxDecoration( borderRadius: BorderRadius.circular(30.0), ), child: Stack( children: [ Container( padding: EdgeInsets.symmetric( horizontal: 16, vertical: 16, ), child: Align( alignment: Alignment.center, child: MyVideoPlayer(assetFile: "assets/videos/Apple_Health_Sleep.mp4",) ), ), ], ), ), Container( alignment: Alignment.topLeft, padding: const EdgeInsets.only(top: 20.0, left: 25.0, bottom: 8.0), child: Text( "Sleep is one of our body’s strongest allies. It can lift your mood, improve thinking and memory, lower stress and blood pressure, and help boost your immune system.", style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.normal), ), ), Container( alignment: Alignment.topLeft, padding: const EdgeInsets.only(top: 20.0, left: 25.0, bottom: 8.0), child: Text( "Online Articles", style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold), ), ), card.ArticlesCard( "Recover from Days of Sleep Deprivation...", "https://www.healthline.com/health-news/it-can-take-more-than-a-week-to-recover-from-days-of-sleep-deprivation", ), card.ArticlesCard( "Why sleep is essential for health", "https://www.medicalnewstoday.com/articles/325353", ), card.ArticlesCard( "The National Sleep Foundation's Sleep Health Index", "https://www.sleephealthjournal.org/article/S2352-7218(17)30102-X/fulltext", ), card.ArticlesCard( "Why Do We Need Sleep?", "https://www.sleepfoundation.org/how-sleep-works/why-do-we-need-sleep", ), card.ArticlesCard( "Sleep and Pregnancy", "https://familydoctor.org/getting-enough-sleep-pregnancy/", ), card.ArticlesCard( "The Benefits of Getting a Full Night's Sleep ", "https://www.sclhealth.org/blog/2018/09/the-benefits-of-getting-a-full-night-sleep/", ), card.ArticlesCard( "The Importance of Sleep for Kids", "https://www.hopkinsallchildrens.org/ACH-News/General-News/The-importance-of-sleep-for-kids", ), card.ArticlesCard( "The importance of sleep during pregnancy", "https://www.evybaby.com/en-eg/moms-land/articles/2015/october/the-importance-of-sleep-during-pregnancy", ), ], ), ], ), ), ), ); } }
0
mirrored_repositories/Dr-Health/lib/src/components
mirrored_repositories/Dr-Health/lib/src/components/HealthData/mindfulness_data.dart
// @dart=2.12 import 'package:dr_health/src/components/cards/cards.dart' as card; import 'package:dr_health/src/handlers/video_player_handler.dart'; import 'package:flutter/material.dart'; class MindfulnessData extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Theme.of(context).primaryColor, elevation: 6.0, shadowColor: Colors.blueGrey, title: Text("Health Data"), ), body: SingleChildScrollView( scrollDirection: Axis.vertical, child: SafeArea( child: Stack( children: [ Column( children: [ Container( alignment: Alignment.topLeft, padding: const EdgeInsets.only(top: 6.0, left: 25.0, bottom: 5.0), child: Text( "Mindfulness", style: TextStyle( fontSize: 25.0, color: Colors.black, fontWeight: FontWeight.bold), ), ), Container( color: Colors.black12, width: 400.0, height: 2.0, ), Container( alignment: Alignment.topLeft, padding: const EdgeInsets.only(top: 20.0, left: 25.0, bottom: 8.0), child: Text( "Quiet your mind. Relax your body. Be in the moment", style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold), ), ), Container( height: 230.0, decoration: BoxDecoration( borderRadius: BorderRadius.circular(30.0), ), child: Stack( children: [ Container( padding: EdgeInsets.symmetric( horizontal: 16, vertical: 16, ), child: Align( alignment: Alignment.center, child: MyVideoPlayer(assetFile: "assets/videos/Apple_Health_Mindfulness.mp4",) ), ), ], ), ), Container( alignment: Alignment.topLeft, padding: const EdgeInsets.only(left: 12.0, top: 5.0, bottom: 8.0), child: ListTile( title: Text( "Mindfulness", style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold), ), subtitle: Padding( padding: const EdgeInsets.only(top: 6.0), child: Text( "Mindfulness is a state of active, open attention on the present. When you're mindful, you observe your thoughts and feelings from a distance, without judging them good or bad. Instead of letting your life pass you by, mindfulness means living in the moment and awakening to experience.", style: TextStyle( fontSize: 16.0, fontWeight: FontWeight.normal), ), ), ), ), Container( alignment: Alignment.topLeft, padding: const EdgeInsets.only(top: 20.0, left: 25.0, bottom: 8.0), child: Text( "Online Articles", style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold), ), ), card.ArticlesCard( "Benefits of Mindfulness", "https://www.helpguide.org/harvard/benefits-of-mindfulness.htm" ), card.ArticlesCard( "The Importance of Mindfulness: 20+ Reasons to Practice Mindfulness", "https://positivepsychology.com/importance-of-mindfulness/" ), card.ArticlesCard( "What is Mindfulness Therapy and How to Apply It?", "https://positivepsychology.com/mindfulness-therapy/" ), card.ArticlesCard( "Improving Sleep Through Mindfulness Meditation", "https://positivepsychology.com/improving-sleep-mindfulness/" ), card.ArticlesCard( "What Is Mindful Walking Meditation and How Can It Impact Your Life?", "https://positivepsychology.com/mindful-walking/" ), card.ArticlesCard( "65+ Mindfulness Worksheets for Adults, Kids, and Your Therapy Sessions", "https://positivepsychology.com/mindfulness-worksheets/" ), card.ArticlesCard( "Mindfulness and the Brain: What Does Research and Neuroscience Say?", "https://positivepsychology.com/mindfulness-brain-research-neuroscience/" ), card.ArticlesCard( "18 Mindfulness Games, Worksheets and Activities for Kids", "https://positivepsychology.com/mindfulness-for-kids/" ), card.ArticlesCard( "Mindfulness at Work: Using Mindful Leadership in the Workplace", "https://positivepsychology.com/mindfulness-at-work/" ), card.ArticlesCard( "What Is Mindful Breathing? Exercises, Scripts, and Videos", "https://positivepsychology.com/mindful-breathing/" ), card.ArticlesCard( "Practicing Mindfulness in Groups: 9 Activities and Exercises", "https://positivepsychology.com/group-mindfulness-activities/" ), ], ), ], ), ), ), ); } }
0
mirrored_repositories/Dr-Health/lib/src/components
mirrored_repositories/Dr-Health/lib/src/components/Medicine/medicines_list.dart
import 'package:flutter/material.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:dr_health/src/models/pill.dart'; import 'package:dr_health/src/components/cards/medicine_card.dart'; class MedicinesList extends StatelessWidget { final List<Pill> listOfMedicines; final Function setData; final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin; MedicinesList(this.listOfMedicines,this.setData,this.flutterLocalNotificationsPlugin); @override Widget build(BuildContext context) { return ListView.builder( itemBuilder: (context, index) => MedicineCard(listOfMedicines[index],setData,flutterLocalNotificationsPlugin), itemCount: listOfMedicines.length, shrinkWrap: true, physics: NeverScrollableScrollPhysics(), ); } }
0
mirrored_repositories/Dr-Health/lib/src/components
mirrored_repositories/Dr-Health/lib/src/components/Medicine/medicine_form_fields.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class FormFields extends StatelessWidget { final List<String> weightValues = ["pills", "ml", "mg"]; // final int howManyWeeks; final TextEditingController nameController; final TextEditingController descriptionController; final TextEditingController amountController; final String selectWeight; final Function onPopUpMenuChanged; //, onSliderChanged; FormFields( this.nameController, this.descriptionController, this.amountController, this.selectWeight, this.onPopUpMenuChanged, ); @override Widget build(BuildContext context) { final focus = FocusScope.of(context); return LayoutBuilder( builder:(context,constrains)=> Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( height: constrains.maxHeight * 0.22, child: TextField( textInputAction: TextInputAction.next, controller: nameController, style: TextStyle( color: Colors.black, fontWeight: FontWeight.w400, fontSize: 16.0), decoration: InputDecoration( contentPadding: EdgeInsets.symmetric( horizontal: 15.0, vertical: 20.0), labelText: "Medicine Name", border: OutlineInputBorder( borderRadius: BorderRadius.circular(10.0), borderSide: BorderSide(width: 0.5, color: Colors.grey))), onSubmitted: (val)=>focus.nextFocus(), ), ), SizedBox( height: constrains.maxHeight * 0.07, ), Container( height: constrains.maxHeight * 0.22, child: TextField( textInputAction: TextInputAction.next, controller: descriptionController, style: TextStyle( color: Colors.black, fontWeight: FontWeight.w400, fontSize: 16.0), decoration: InputDecoration( contentPadding: EdgeInsets.symmetric( horizontal: 15.0, vertical: 20.0), labelText: "Medicine Description", border: OutlineInputBorder( borderRadius: BorderRadius.circular(10.0), borderSide: BorderSide(width: 0.5, color: Colors.grey))), onSubmitted: (val)=>focus.nextFocus(), ), ), SizedBox( height: constrains.maxHeight * 0.07, ), Row( children: [ Flexible( flex: 2, child: Container( height: constrains.maxHeight * 0.24, child: TextField( controller: amountController, keyboardType: TextInputType.number, style: TextStyle( color: Colors.black, fontWeight: FontWeight.w400, fontSize: 16.0), decoration: InputDecoration( contentPadding: EdgeInsets.symmetric( horizontal: 15.0, vertical: 20.0), labelText: "Dosage Amount", border: OutlineInputBorder( borderRadius: BorderRadius.circular(10.0), borderSide: BorderSide( width: 0.5, color: Colors.grey))), onSubmitted: (val)=>focus.unfocus(), ), ), ), SizedBox( width: 10, ), Flexible( flex: 1, child: Container( height: constrains.maxHeight * 0.24, child: DropdownButtonFormField( onTap: ()=>focus.unfocus(), decoration: InputDecoration( contentPadding: EdgeInsets.symmetric( horizontal: 15.0, vertical: 18.0), labelText: "Type", border: OutlineInputBorder( borderRadius: BorderRadius.circular(10.0), borderSide: BorderSide( width: 0.5, color: Colors.grey))), items: weightValues .map((weight) => DropdownMenuItem( child: Text(weight), value: weight, )).toList(), onChanged: (value) => this.onPopUpMenuChanged(value), value: selectWeight, ), ), ) ], ), // SizedBox( // height: constrains.maxHeight * 0.1, // ), // Flexible( // flex: 3, // child: Container( // height: constrains.maxHeight * 0.1, // child: Padding( // padding: const EdgeInsets.only(left: 12.0), // child: FittedBox( // child: Text( // "How long?", // style: TextStyle( // color: Colors.grey[800], // fontSize: 18.0, // fontWeight: FontWeight.w600), // ), // ), // ), // ), // ), // Flexible( // flex: 3, // child: Container( // height: constrains.maxHeight * 0.18, // child: UserSlider(this.onSliderChanged,this.howManyWeeks) // ), // ), // Flexible( // flex: 3, // child: Align( // alignment: Alignment.bottomRight, // child: FittedBox(child: Text('$howManyWeeks weeks')), // ), // ) ], ), ); } }
0
mirrored_repositories/Dr-Health/lib/src
mirrored_repositories/Dr-Health/lib/src/models/medicine_type.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class MedicineType{ String name; Widget image; bool isChoose; MedicineType(this.name, this.image, this.isChoose); }
0
mirrored_repositories/Dr-Health/lib/src
mirrored_repositories/Dr-Health/lib/src/models/pill.dart
class Pill { int id; String name; String description; String amount; String type; // int howManyWeeks; String medicineForm; int time; int notifyId; Pill( {this.id, // this.howManyWeeks, this.time, this.amount, this.medicineForm, this.name, this.description, this.type, this.notifyId}); //------------------set pill to map------------------- Map<String, dynamic> pillToMap() { Map<String, dynamic> map = Map(); map['id'] = this.id; map['name'] = this.name; map['description'] = this.description; map['amount'] = this.amount; map['type'] = this.type; // map['howManyWeeks'] = this.howManyWeeks; map['medicineForm'] = this.medicineForm; map['time'] = this.time; map['notifyId'] = this.notifyId; return map; } //===================================================== //---------------------create pill object from map--------------------- Pill pillMapToObject(Map<String, dynamic> pillMap) { return Pill( id: pillMap['id'], name: pillMap['name'], description: pillMap['description'], amount: pillMap['amount'], type: pillMap['type'], // howManyWeeks: pillMap['howManyWeeks'], medicineForm: pillMap['medicineForm'], time: pillMap['time'], notifyId: pillMap['notifyId']); } //===================================================================== //---------------------| Get the medicine image path |------------------------- String get image{ switch(this.medicineForm){ case "Syrup": return "assets/images/syrup.png"; break; case "Pill":return "assets/images/pills.png"; break; case "Capsule":return "assets/images/capsule.png"; break; case "Cream":return "assets/images/cream.png"; break; case "Drops":return "assets/images/drops.png"; break; case "Syringe":return "assets/images/syringe.png"; break; default : return "assets/images/pills.png"; break; } } //============================================================================= }
0
mirrored_repositories/Dr-Health/lib/src
mirrored_repositories/Dr-Health/lib/src/models/calendar_day_model.dart
// ignore_for_file: deprecated_member_use import 'package:intl/intl.dart'; class CalendarDayModel { String dayLetter; int dayNumber; int month; int year; bool isChecked; CalendarDayModel({this.dayLetter,this.dayNumber,this.year, this.month, this.isChecked}); //----------------| get current 7 days |---------------------- List<CalendarDayModel> getCurrentDays() { final List<CalendarDayModel> daysList = List(); DateTime currentTime = DateTime.now(); for (int i = 0; i < 7; i++) { daysList.add(CalendarDayModel( dayLetter: DateFormat.E().format(currentTime).toString()[0], dayNumber: currentTime.day, month:currentTime.month, year: currentTime.year, isChecked: false)); currentTime = currentTime.add(Duration(days: 1)); } daysList[0].isChecked = true; return daysList; } //============================================================ }
0
mirrored_repositories/Dr-Health/lib/src
mirrored_repositories/Dr-Health/lib/src/auth/auth.dart
//@dart=2.9 // ignore_for_file: deprecated_member_use import 'package:dr_health/src/utils/app_shared_preference.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:dr_health/src/auth/forgotpassword.dart'; import 'package:dr_health/src/auth/signup.dart'; import 'package:dr_health/src/constant.dart'; import 'package:dr_health/src/screens/index.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:google_sign_in/google_sign_in.dart'; class LoginPage extends StatefulWidget { @override _LoginPageState createState() => _LoginPageState(); } class _LoginPageState extends State<LoginPage> { final GlobalKey<FormState> _formKey = GlobalKey<FormState>(); final FirebaseAuth _firebaseAuth = FirebaseAuth.instance; final TextEditingController _emailController = TextEditingController(); final TextEditingController _passwordController = TextEditingController(); String email, password; Widget _buildLogo() { return Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Padding( padding: const EdgeInsets.symmetric(vertical: 30), child: Text( 'Dr. Health', style: TextStyle( fontSize: MediaQuery.of(context).size.height / 30, fontWeight: FontWeight.bold, color: Colors.white, letterSpacing: 2.0 ), ), ) ], ); } Widget _buildEmailRow() { return Padding( padding: EdgeInsets.all(8), child: Form( key: _formKey, child: TextFormField( controller: _emailController, keyboardType: TextInputType.emailAddress, validator: (String value) { if (value.isEmpty) { return 'Please provide your credentials'; } return null; }, onChanged: (value) { setState(() { email = value; }); }, decoration: InputDecoration( prefixIcon: Icon( Icons.email, color: mainColor, ), labelText: 'Email Address'), ), ), ); } Widget _buildPasswordRow() { return Padding( padding: EdgeInsets.all(8), child: TextFormField( controller: _passwordController, keyboardType: TextInputType.text, obscureText: true, validator: (String value) { if (value.isEmpty) { return 'Please provide your credentials'; } return null; }, onChanged: (value) { setState(() { password = value; }); }, decoration: InputDecoration( prefixIcon: Icon( Icons.lock, color: mainColor, ), labelText: 'Password', ), ), ); } Widget _buildForgetPasswordButton() { return Row( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ SizedBox(height: 10), FlatButton.icon( onPressed: () { setState(() { Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => forgotpassword()),); }); }, label: Text("Forgot Password?"), icon: Icon(Icons.arrow_circle_down_outlined), ), ], ); } Widget _buildLoginButton() { return Container( height: 1.4 * (MediaQuery.of(context).size.height / 20), width: 5 * (MediaQuery.of(context).size.width / 10), margin: EdgeInsets.only(bottom: 20), child: RaisedButton( elevation: 5.0, color: mainColor, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(30.0), ), onPressed: () async { final SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); AppPreferences.setUserEmail(email); // AppPreferences.setUserEmail('email', _emailController.text); if (email != null && password != null) { setState(() { if(_signInWithEmailAndPassword()) { print("Welcome"); } else { print('Need an Account?'); } AppPreferences.setUserEmail(email); Navigator.pushReplacementNamed(context, '/Navigation'); // Navigator.push(context , MaterialPageRoute(builder: (context) => Navigation())); // Navigator.pushReplacementNamed(context, '/loading'); }); } if(email != null && password != null) { Navigator.pushReplacementNamed(context, '/Navigation'); // Navigator.push(context , MaterialPageRoute(builder: (context) => Navigation())); // Navigator.pushReplacementNamed(context, '/loading'); } }, child: Text( "Welcome", style: TextStyle( color: Colors.white, letterSpacing: 2.0, fontSize: MediaQuery.of(context).size.height / 50, ), ), ), ); } // Widget _buildOrRow() { // return Row( // mainAxisAlignment: MainAxisAlignment.center, // children: <Widget>[ // Container( // margin: EdgeInsets.only(bottom: 20), // child: Text( // '- OR -', // style: TextStyle( // fontWeight: FontWeight.w600, // ), // ), // ) // ], // ); // } // Widget _buildSocialBtnRow() { // return Row( // mainAxisAlignment: MainAxisAlignment.center, // children: <Widget>[ // GestureDetector( // onTap: () {setState(() async { // await signInWithGoogle(); // Navigator.pushReplacementNamed(context, '/Navigation'); // // await Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (_) => Navigation())); // });}, // child: Container( // height: 60, // width: 60, // decoration: BoxDecoration( // shape: BoxShape.circle, // color: mainColor, // boxShadow: [ // BoxShadow( // color: Colors.black26, // offset: Offset(0, 2), // blurRadius: 6.0) // ], // ), // child: Icon( // FontAwesomeIcons.google, // color: Colors.white, // ), // ), // ) // ], // ); // } Widget _buildContainer() { return Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ClipRRect( borderRadius: BorderRadius.all( Radius.circular(20), ), child: Container( height: MediaQuery.of(context).size.height * 0.6, width: MediaQuery.of(context).size.width * 0.8, decoration: BoxDecoration( color: Colors.green.shade300, //Colors.white60, ), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( "Provide your information", style: TextStyle( fontSize: MediaQuery.of(context).size.height / 40, ), ), ], ), _buildEmailRow(), _buildPasswordRow(), _buildForgetPasswordButton(), _buildLoginButton(), // _buildOrRow(), // _buildSocialBtnRow(), ], ), ), ), ], ); } Widget _buildSignUpBtn() { return Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Padding( padding: EdgeInsets.only(top: 40), child: FlatButton( onPressed: () { setState(() { Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (_) => signUp())); //LoginPage }); }, child: RichText( text: TextSpan(children: [ TextSpan( text: 'Don\'t have an account? ', style: TextStyle( color: Colors.black, fontSize: MediaQuery.of(context).size.height / 50, fontWeight: FontWeight.w400, ), ), TextSpan( text: 'Register here', style: TextStyle( color: mainColor, fontSize: MediaQuery.of(context).size.height / 50, fontWeight: FontWeight.bold, letterSpacing: 0.3 ), ) ]), ), ), ), ], ); } @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( resizeToAvoidBottomInset: false, backgroundColor: Colors.brown[300], //Color(0xfff2f3f7), body: Stack( children: <Widget>[ Container( height: MediaQuery.of(context).size.height * 0.7, width: MediaQuery.of(context).size.width, child: Container( decoration: BoxDecoration( color: mainColor, borderRadius: BorderRadius.only( bottomLeft: const Radius.circular(50), bottomRight: const Radius.circular(50), ), ), ), ), Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ _buildLogo(), _buildContainer(), _buildSignUpBtn(), FlatButton(onPressed: () { Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (_) => Home())); //LoginPage }, child: Text("Anonymous login" , style: TextStyle(fontSize: 15, color: Colors.blueGrey))), ], ) ], ), ), ); } //Email and Password SignIn method _signInWithEmailAndPassword() async{ try{ final User user = (await _firebaseAuth.signInWithEmailAndPassword( email: _emailController.text.trim(), password: _passwordController.text.trim())).user; if(user!=null){ setState(() { Fluttertoast.showToast(msg: "Welcome !"); Navigator.pushReplacementNamed(context, '/Navigation'); // Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => Navigation()),); }); } }catch(e){ Fluttertoast.showToast(msg: "Provide correct details or create an account", toastLength: Toast.LENGTH_LONG); } } } // Google sign in Future<UserCredential> signInWithGoogle() async { final GoogleSignInAccount googleuser = await GoogleSignIn().signIn(); final GoogleSignInAuthentication googleAuth = await googleuser.authentication; final GoogleAuthCredential credential = GoogleAuthProvider.credential( idToken: googleAuth.idToken, accessToken: googleAuth.accessToken ); Fluttertoast.showToast(msg: "Welcome !"); return await FirebaseAuth.instance.signInWithCredential(credential); }
0
mirrored_repositories/Dr-Health/lib/src
mirrored_repositories/Dr-Health/lib/src/auth/login.dart
//@dart=2.9 import 'package:dr_health/src/components/navigation.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; import 'package:dr_health/src/screens/index.dart'; import 'forgotpassword.dart'; import 'home.dart'; import 'signup.dart'; import 'package:fluttertoast/fluttertoast.dart'; class LOGIN extends StatefulWidget { @override _LOGINState createState() => _LOGINState(); } class _LOGINState extends State<LOGIN> { final GlobalKey<FormState> _formKey = GlobalKey<FormState>(); final TextEditingController _emailController = TextEditingController(); final TextEditingController _passwordController = TextEditingController(); final FirebaseAuth _firebaseAuth = FirebaseAuth.instance; final color3 = const Color(0xFF38BF68); Widget Title = Container( padding: const EdgeInsets.symmetric(horizontal: 20,), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Row( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text( "Login", style: TextStyle( letterSpacing: 2.0, color: Colors.black87, fontWeight: FontWeight.bold, fontSize: 20 ), ), Container( width: 5), ], ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon( Icons.circle, color: Colors.black87, size: 10.0, ), new SizedBox( width: 70.0, child: new Center( child: new Container( margin: new EdgeInsetsDirectional.only(start: 10.0, end: 10.0), height: 1.0, color: Colors.yellow, ), ), ), Icon( Icons.circle, color: Colors.black, size: 10.0, ) ], ) ], ), ); Widget back = Container( child: Stack( alignment: Alignment.bottomCenter, children: [ Container(height: 615,width: 300), Positioned( top: 0, child: Container( decoration: BoxDecoration( color: Colors.white, border: Border.all( color: Colors.white, ), borderRadius: BorderRadius.all(Radius.circular(20)) ), height: 510,width: 290, margin: EdgeInsets.symmetric(vertical: 15.0,horizontal:35), ), ), ], ) ); Widget text(BuildContext context) { return Container( child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Container( child: const Text("Welcome", style: TextStyle( fontSize: 30, ), ), ), SizedBox(height: 3), Container( child: Text("Provide your details to procede: ", style: TextStyle( fontSize: 14, color: Colors.black54 ), ), ), SizedBox(height: 50), Container( decoration: BoxDecoration( border: Border.all(color: Colors.black54), borderRadius: BorderRadius.circular(12) ), child: Container( padding: EdgeInsets.all(10), constraints: BoxConstraints( minWidth: 80, minHeight: 40, maxWidth: 260), child: Row( children: [ Icon(Icons.email), SizedBox(width: 10), Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text("EMAIL", style: TextStyle( color: Colors.black54 ), ), SizedBox( width: 180, height: 30, child: TextFormField( controller: _emailController, decoration: InputDecoration( border: UnderlineInputBorder(), ), validator: (String value) { if (value.isEmpty) { return 'Please provide your details'; } return null; }, ), ) // TextFormField( // decoration: InputDecoration( // ), // ) ] ), ], ) ), ), SizedBox(height: 7), Container( decoration: BoxDecoration( border: Border.all(color: Colors.black54), borderRadius: BorderRadius.circular(12) ), child: Container( padding: EdgeInsets.all(10), constraints: BoxConstraints( minWidth: 80, minHeight: 40, maxWidth: 260), child: Row( children: [ Icon(Icons.lock), SizedBox(width: 10), Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text("PASSWORD", style: TextStyle( color: Colors.black54 ),), SizedBox( width: 180, height: 30, child: TextFormField( controller: _passwordController, decoration: InputDecoration( border: UnderlineInputBorder(), ), validator: (String value) { if (value.isEmpty) { return 'Please provide your details'; } return null; }, ), ) // TextFormField( // decoration: InputDecoration( // ), // ) ] ), ], ) ), ), Row( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ GestureDetector( onTap: () { setState(() { Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => forgotpassword()),); }); }, child: Container( margin: EdgeInsets.only(top: 20,left: 150), child: const Text("Forgot Password?", style: TextStyle( fontSize: 13, color: Color(0xFF267D43) ), ) ), ), ], ), //Check SizedBox(height: 70), Container( // width: 120, padding: const EdgeInsets.only(left: 30, top: 7, right: 7, bottom: 7), decoration: const BoxDecoration( gradient: LinearGradient( colors: [Colors.lightGreen, Color(0xFF2A9750)]), borderRadius: BorderRadius.horizontal( right: Radius.circular(40), left: Radius.circular(40)) ), child: Row( mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: [ const Text("Login", style: TextStyle( letterSpacing: 2.0, color: Colors.white, fontSize: 20 ),), Container(width: 15), Container( decoration: const BoxDecoration( shape: BoxShape.circle, color: Colors.lightGreen ), child: IconButton(onPressed: () async { if (_formKey.currentState.validate()) { setState(() { _signInWithEmailAndPassword(); }); } }, icon: Icon(Icons.arrow_forward_rounded), iconSize: 25, color: Colors.black54), width: 40, height: 40,) ] ), ), SizedBox(height: 30), const Text("Don't Have An Account ?", style: TextStyle( fontSize: 13 ), ), GestureDetector( onTap: () { setState(() { Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => signUp()),); }); }, child: Container( child: const Text("Create one", style: TextStyle( color: Color(0xFF267D43) ), ) ), ), SizedBox(height: 80, width: 20), ] ) ); } @override Widget build(BuildContext context) { const color3 = const Color(0xFF38BF68); return Form( key: _formKey, child: MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData(fontFamily: 'Balsamiq_Sans'), home: Scaffold( backgroundColor: color3, body: Container( child: ListView( children:[ Title, Stack( alignment: Alignment.center, children: [ back, text(context), ] ) ] ), ), ) ) ); } _signInWithEmailAndPassword() async{ try{ final User user = (await _firebaseAuth.signInWithEmailAndPassword( email: _emailController.text.trim(), password: _passwordController.text.trim())).user; if(user!=null){ setState(() { Fluttertoast.showToast(msg: "Signed In Sucessfully"); // Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => Home()),); Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => Navigation()),); }); } }catch(e){ Fluttertoast.showToast(msg: e.toString()); } } }
0
mirrored_repositories/Dr-Health/lib/src
mirrored_repositories/Dr-Health/lib/src/auth/signup.dart
//@dart=2.9 import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:dr_health/src/screens/index.dart'; import 'home.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'login.dart'; class signUp extends StatefulWidget{ @override _signUpState createState()=> _signUpState(); } class _signUpState extends State<signUp> { final color3 = const Color(0xFF38BF68); final GlobalKey<FormState> _formKey = GlobalKey<FormState>(); final TextEditingController _emailController = TextEditingController(); final TextEditingController _passwordController = TextEditingController(); final TextEditingController _confpasswordController = TextEditingController(); final FirebaseAuth _auth = FirebaseAuth.instance; Widget Title = Container( padding: EdgeInsets.symmetric(horizontal: 20,), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Row( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text( "Registration", style: TextStyle( color: Colors.black87, fontWeight: FontWeight.bold, fontSize: 20 ), ), Container(width: 5), const Text( "Page", style: TextStyle( color: Colors.yellow, fontWeight: FontWeight.bold, fontSize: 20 ), ), ], ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ const Icon( Icons.circle, color: Colors.black87, size: 10.0, ), SizedBox( width: 70.0, child: Center( child: Container( margin: const EdgeInsetsDirectional.only( start: 10.0, end: 10.0), height: 1.0, color: Colors.yellow, ), ), ), const Icon( Icons.circle, color: Colors.black, size: 10.0, ) ], ) ], ), ); Widget back = Container( child: Stack( alignment: Alignment.bottomCenter, children: [ Container(height: 615, width: 300,), Positioned(top: 0, child: Container( decoration: BoxDecoration( color: Colors.white, border: Border.all( color: Colors.white, ), borderRadius: BorderRadius.all(Radius.circular(20)) ), height: 510, width: 290, margin: EdgeInsets.symmetric(vertical: 15.0, horizontal: 35), ), ), ], ) ); Widget text(BuildContext context) { return Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Container( child: const Text("Register", style: TextStyle( fontSize: 30, ), ), ), SizedBox(height: 3), Container( child: const Text("Create an Account", style: TextStyle( fontSize: 14, color: Colors.black54 ), ), ), SizedBox(height: 15), Container( decoration: BoxDecoration( border: Border.all(color: Colors.black54), borderRadius: BorderRadius.circular(12) ), child: Container( padding: EdgeInsets.all(10), constraints: const BoxConstraints( minWidth: 80, minHeight: 40, maxWidth: 260), child: Row( children: [ Icon(Icons.email), SizedBox(width: 10), Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ const Text("Email Address", style: TextStyle( color: Colors.black54 ), ), SizedBox( width: 180, height: 50, child: TextFormField( controller: _emailController, validator: (String value) { if (value.isEmpty) { return 'Please provide your details'; } return null; }, decoration: const InputDecoration( border: UnderlineInputBorder(), ), ), ) // TextFormField( // decoration: InputDecoration( // ), // ) ] ), ], ) ), ), SizedBox(height: 7), Container( decoration: BoxDecoration( border: Border.all(color: Colors.black54), borderRadius: BorderRadius.circular(12) ), child: Container( padding: EdgeInsets.all(10), constraints: const BoxConstraints( minWidth: 80, minHeight: 40, maxWidth: 260), child: Row( children: [ Icon(Icons.lock), SizedBox(width: 10), Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ const Text("Password", style: TextStyle( color: Colors.black54 ),), SizedBox( width: 180, height: 50, child: TextFormField( controller: _passwordController, validator: (String value) { if (value.isEmpty) { return 'Provide details'; } return null; }, decoration: const InputDecoration( border: UnderlineInputBorder(), ), ), ) // TextFormField( // decoration: InputDecoration( // ), // ) ] ), ], ) ), ), SizedBox(height: 7), Container( decoration: BoxDecoration( border: Border.all(color: Colors.black54), borderRadius: BorderRadius.circular(12) ), child: Container( padding: EdgeInsets.all(10), constraints: const BoxConstraints( minWidth: 80, minHeight: 40, maxWidth: 260), child: Row( children: [ Icon(Icons.lock), SizedBox(width: 10), Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ const Text("Verify your password", style: TextStyle( color: Colors.black54 ),), SizedBox( width: 180, height: 50, child: TextFormField( controller: _confpasswordController, validator: (String value) { if (value.isEmpty) { return 'Please provide your details'; } return null; }, decoration: const InputDecoration( border: UnderlineInputBorder(), ), ), ) // TextFormField( // decoration: InputDecoration( // ), // ) ] ), ], ) ), ), SizedBox(height: 10), Container( // width: 120, padding: EdgeInsets.only(left: 30, top: 7, right: 7, bottom: 7), decoration: const BoxDecoration( gradient: LinearGradient( colors: [Colors.lightGreen, Color(0xFF2A9750)]), borderRadius: BorderRadius.horizontal( right: Radius.circular(40), left: Radius.circular(40)) ), child: Row( mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: [ const Text("Register", style: TextStyle( color: Colors.white, fontSize: 20 ),), Container(width: 15), Container( decoration: const BoxDecoration( shape: BoxShape.circle, color: Colors.lightGreen ), child: IconButton(onPressed: () async { if (_formKey.currentState.validate()) { _register(); } }, icon: Icon(Icons.arrow_forward_rounded), iconSize: 25, color: Colors.black54), width: 40, height: 40,) ] ), ), SizedBox(height: 30), const Text("Do you have an account ?", style: TextStyle( fontSize: 13 ), ), GestureDetector( onTap: () { Navigator.pushReplacement( context, MaterialPageRoute(builder: (context) => LOGIN()),); }, child: Container( //onPressed: }, child: const Text("Login", style: TextStyle( color: Color(0xFF267D43) ), ) ), ), SizedBox(height: 80, width: 20), ] ); } @override Widget build(BuildContext context) { const color3 = const Color(0xFF38BF68); return MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData(fontFamily: 'Balsamiq_Sans'), home: Scaffold( backgroundColor: color3, body: Form( key: _formKey, child:Container( // margin: EdgeInsets.symmetric(horizontal: 15.0), child: ListView( children: [ Title, Stack( alignment: Alignment.center, children: [ back, text(context), ] ) ] ), ), ) ) ); } @override void dispose() { _emailController.dispose(); _passwordController.dispose(); super.dispose(); } void _register()async{ String email = _emailController.text.trim(); String password = _passwordController.text.trim(); String confirmpassword = _confpasswordController.text.trim(); if(password == confirmpassword) { try { final User user = (await _auth.createUserWithEmailAndPassword( email: email, password: password)).user; setState(() { if (user != null) { Fluttertoast.showToast(msg: "Account Created Successfully"); Navigator.pushReplacement( context, MaterialPageRoute(builder: (context) => LOGIN()),); } }); } catch (e) { Fluttertoast.showToast(msg: e.toString()); } } else{ Fluttertoast.showToast(msg: "Your password do not match"); } } }
0
mirrored_repositories/Dr-Health/lib/src
mirrored_repositories/Dr-Health/lib/src/auth/home.dart
//@dart=2.9 import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'login.dart'; class HomeContent extends StatefulWidget { @override _HomeContentState createState() => _HomeContentState(); } class _HomeContentState extends State<HomeContent> { @override Widget build(BuildContext context) { return Center( child: GestureDetector( onTap: () { _signOut(); Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => LOGIN()),); }, child: Container( margin: EdgeInsets.symmetric(horizontal: 14), padding: const EdgeInsets.only( left: 12, top: 5, bottom: 5), child: Row( mainAxisAlignment: MainAxisAlignment.start, // ignore: prefer_const_literals_to_create_immutables children: [ // Container(width: 15), Icon(Icons.logout,size: 17,), SizedBox(width: 10), const Text("Logout", style: TextStyle( color: Colors.red, fontSize: 17,fontWeight: FontWeight.bold )), ]), ), ), ); } Future<void> _signOut() async { await FirebaseAuth.instance.signOut(); } }
0
mirrored_repositories/Dr-Health/lib/src
mirrored_repositories/Dr-Health/lib/src/auth/forgotpassword.dart
//@dart=2.9 import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'login.dart'; class forgotpassword extends StatefulWidget{ @override _forgotpasswordState createState() => _forgotpasswordState(); } class _forgotpasswordState extends State<forgotpassword> { TextEditingController _emailController = TextEditingController(); final GlobalKey<FormState> _formKey = GlobalKey<FormState>(); final FirebaseAuth _firebaseAuth = FirebaseAuth.instance; Widget Title = Container( padding: EdgeInsets.symmetric(horizontal: 20,), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Row( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text( "FORGOT", style: TextStyle( color: Colors.black87, fontWeight: FontWeight.bold, fontSize: 20 ), ), Container( width: 5), const Text( "PASSWORD", style: TextStyle( color: Colors.yellow, fontWeight: FontWeight.bold, fontSize: 20 ), ), ], ), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ const Icon( Icons.circle, color: Colors.black87, size: 10.0, ), SizedBox( width: 70.0, child: Center( child: Container( margin: new EdgeInsetsDirectional.only(start: 10.0, end: 10.0), height: 1.0, color: Colors.yellow, ), ), ), const Icon( Icons.circle, color: Colors.black, size: 10.0, ) ], ) ], ), ); Widget back = Container( child: Stack( alignment: Alignment.bottomCenter, children: [ Container(height: 615,width: 300,), Positioned( top: 0, child: Container( decoration: BoxDecoration( color: Colors.white, border: Border.all( color: Colors.white, ), borderRadius: BorderRadius.all(Radius.circular(20)) ), height: 510,width: 290, margin: EdgeInsets.symmetric(vertical: 15.0,horizontal:35), ), ), ], ) ); Widget text(BuildContext context) { return Container( child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Container( child: const Text("Reset Password!", style: TextStyle( fontSize: 25, color: Colors.black ), ), ), SizedBox(height: 15), Text("Provide your",style: TextStyle(fontSize: 16)), Text("account email",style: TextStyle(fontSize: 16)), SizedBox(height: 9), Text("We will send you a link",style: TextStyle(color: Colors.black54)), Text(" for your password",style: TextStyle(color: Colors.black54)), SizedBox(height: 150), Container( decoration: BoxDecoration( border: Border.all(color: Colors.black54), borderRadius: BorderRadius.circular(12) ), child: Container( padding: EdgeInsets.all(10), constraints: const BoxConstraints( minWidth: 80, minHeight: 40, maxWidth: 260), child: Row( children: [ Icon(Icons.email), SizedBox(width: 10), Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ const Text("EMAIL", style: TextStyle( color: Colors.black54 ), ), SizedBox( width: 180, height: 50, child: TextFormField( controller: _emailController, decoration: const InputDecoration( border: UnderlineInputBorder(), ), validator: (String value) { if (value.isEmpty) { return 'Please, provide your details'; } return null; }, ), ) ] ), ], ) ), ), SizedBox(height: 13), Container( // width: 120, padding: EdgeInsets.only(left: 30, top: 7, right: 7, bottom: 7), decoration: const BoxDecoration( gradient: LinearGradient( colors: [Colors.lightGreen, Color(0xFF2A9750)]), borderRadius: BorderRadius.horizontal( right: Radius.circular(40), left: Radius.circular(40)) ), child: Row( mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: [ const Text("Continue", style: TextStyle( color: Colors.white, fontSize: 20 ),), Container(width: 15), Container( decoration: const BoxDecoration( shape: BoxShape.circle, color: Colors.lightGreen ), child: IconButton(onPressed: () async { resetPassword(); }, icon: Icon(Icons.arrow_forward_rounded), iconSize: 25, color: Colors.black54), width: 40, height: 40,) ] ), ), SizedBox(height: 12), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text("Back to ", style: TextStyle( fontSize: 13 ), ), GestureDetector( onTap: () { setState(() { Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => LOGIN()),); }); }, child: Container( child: const Text("Login", style: TextStyle( color: Color(0xFF267D43) ), ) ), ), ], ), SizedBox(height: 80, width: 20), ] ) ); } @override Widget build(BuildContext context) { const color3 = const Color(0xFF38BF68); return Form( key: _formKey, child: MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData(fontFamily: 'Balsamiq_Sans'), home: Scaffold( backgroundColor: color3, body: Container( child: Container( // margin: EdgeInsets.symmetric(horizontal: 15.0), child: ListView( children:[ Title, Stack( alignment: Alignment.center, children: [ back, text(context), ] ) ] ), ), ) ) )); } resetPassword() async { String email = _emailController.text.toString(); try { await _firebaseAuth.sendPasswordResetEmail(email: email); Fluttertoast.showToast(msg: "Password reset request sent.."); _emailController.clear(); } catch (e) { // Fluttertoast.showToast(msg: e.toString()); Fluttertoast.showToast(msg: "Please Provide valid email"); } } }
0
mirrored_repositories/Dr-Health/lib/src
mirrored_repositories/Dr-Health/lib/src/auth/is_user_loggedin.dart
import 'package:dr_health/src/components/navigation.dart'; import 'package:dr_health/src/utils/app_shared_preference.dart'; import 'package:flutter/material.dart'; class LoginPageCheck extends StatefulWidget { @override State<LoginPageCheck> createState() => _LoginPageStateCheck(); } class _LoginPageStateCheck extends State<LoginPageCheck> { String userlogged; @override void initState() { super.initState(); userlogged = AppPreferences.getUserEmail(); } Widget buildCheck(BuildContext context) { return Scaffold( body: CheckUserLogin(), ); } CheckUserLogin() { if(userlogged != null) { Navigator.push(context , MaterialPageRoute(builder: (context) => Navigation())); } else { Navigator.push(context , MaterialPageRoute(builder: (context) => Navigation())); } } @override Widget build(BuildContext context) { } }
0
mirrored_repositories/Dr-Health/lib/src
mirrored_repositories/Dr-Health/lib/src/provider/dkt_provider.dart
// @dart=2.12 // ignore: must_be_immutable import 'package:dr_health/src/screens/DetailScreen/detail_screen.dart'; import 'package:flutter/material.dart'; // ignore: must_be_immutable class DoctorList extends StatefulWidget { String doctorName; String doctorPos; String doctorProfile; String doctorAbout; String doctorAvailability; String receptionPhoneNo; String receptionEmail; DoctorList(this.doctorName, this.doctorPos, this.doctorProfile, this.doctorAbout, this.doctorAvailability, this.receptionPhoneNo, this.receptionEmail); @override _DoctorListState createState() => _DoctorListState(); } class _DoctorListState extends State<DoctorList> { @override Widget build(BuildContext context) { return ListTile( horizontalTitleGap: 3.0, leading: CircleAvatar( backgroundColor: Colors.lightBlue[100], child: CircleAvatar( minRadius: 45, maxRadius: 50, backgroundColor: Colors.transparent, backgroundImage: AssetImage('assets/images/avatar_profile.jpg'), foregroundImage: NetworkImage(widget.doctorProfile), ), ), //Icon(Icons.person), title: Padding( padding: const EdgeInsets.only(left: 8.0), child: Text(widget.doctorName), ), subtitle: Padding( padding: const EdgeInsets.only(left: 9.0), child: Text(widget.doctorPos), ), trailing: TextButton( onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (BuildContext context) => DetailScreen(widget.doctorName, widget.doctorPos, widget.doctorProfile, widget.doctorAbout, widget.doctorAvailability, widget.receptionPhoneNo, widget.receptionEmail), ), ); }, child: Text("VIEW", style: TextStyle(fontWeight: FontWeight.bold, color: Theme.of(context).primaryColor),), ) , ); } }
0
mirrored_repositories/Dr-Health/lib/src
mirrored_repositories/Dr-Health/lib/src/helpers/platform_slider.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'dart:io'; class PlatformSlider extends StatelessWidget { final int min, max, divisions, value; final Function handler; final Color color; PlatformSlider( {@required this.value, @required this.handler, @required this.color, @required this.max, @required this.min, @required this.divisions}); @override Widget build(BuildContext context) { return Platform.isIOS ? CupertinoSlider( onChanged: (value) => this.handler(value), max: this.max.toDouble(), min: this.min.toDouble(), divisions: this.divisions, activeColor: Theme.of(context).primaryColor, value: this.value.toDouble(), ) : Slider( value: this.value.toDouble(), onChanged: (value) => this.handler(value), max: this.max.toDouble(), min: this.min.toDouble(), divisions: this.divisions, activeColor: this.color, ); } }
0
mirrored_repositories/Dr-Health/lib/src
mirrored_repositories/Dr-Health/lib/src/helpers/platform_flat_button.dart
// ignore_for_file: deprecated_member_use import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; class PlatformFlatButton extends StatelessWidget { final Function handler; final Widget buttonChild; final Color color; PlatformFlatButton({@required this.buttonChild, @required this.color, @required this.handler}); @override Widget build(BuildContext context) { return FlatButton( child: this.buttonChild, color: this.color, onPressed: this.handler, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(15.0)), ); } }
0
mirrored_repositories/Dr-Health/lib/src
mirrored_repositories/Dr-Health/lib/src/helpers/snack_bar.dart
// ignore_for_file: deprecated_member_use import 'package:flutter/material.dart'; class Snackbar { void showSnack(String message, GlobalKey<ScaffoldState> _scaffoldKey, Function undo) => _scaffoldKey.currentState.showSnackBar( SnackBar( content: Text(message), action: undo != null ? SnackBarAction( textColor: Theme.of(_scaffoldKey.currentState.context).primaryColor, label: "Undo", onPressed: () => undo, ):null, ), ); }
0
mirrored_repositories/Dr-Health/lib/src
mirrored_repositories/Dr-Health/lib/src/utils/calendar_day.dart
import "package:flutter/material.dart"; import '../models/calendar_day_model.dart'; class CalendarDay extends StatefulWidget { final CalendarDayModel day; final Function onDayClick; CalendarDay(this.day, this.onDayClick); @override _CalendarDayState createState() => _CalendarDayState(); } class _CalendarDayState extends State<CalendarDay> { @override Widget build(BuildContext context) { return LayoutBuilder( builder: (context,constrains) => Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ Text( widget.day.dayLetter, style: TextStyle( color: Colors.grey[500], fontSize: 17.0, fontWeight: FontWeight.w400), ), SizedBox( height: constrains.maxHeight * 0.1, ), GestureDetector( onTap: () => widget.onDayClick(widget.day), child: CircleAvatar( radius: constrains.maxHeight * 0.25, backgroundColor: widget.day.isChecked ? Theme.of(context).primaryColor : Colors.transparent, child: Padding( padding: const EdgeInsets.all(2.0), child: Text( widget.day.dayNumber.toString(), style: TextStyle( color: widget.day.isChecked ? Colors.white : Colors.black, fontSize: 22.0, fontWeight: FontWeight.w500), ), ), ), ), ], ), ); } }
0
mirrored_repositories/Dr-Health/lib/src
mirrored_repositories/Dr-Health/lib/src/utils/app_shared_preference.dart
// @dart=2.12 import 'package:shared_preferences/shared_preferences.dart'; class AppPreferences { static SharedPreferences ? _preferences; static const _keyMedName = 'medname'; static const _keyMedDescription = 'meddescription'; static const _keyMedTime = 'medtime'; static const _keyAlarmSound = 'alarmsound'; static const _userEmail = 'useremail'; static Future init() async => _preferences = await SharedPreferences.getInstance(); static Future setMedName(String medName) async => await _preferences?.setString(_keyMedName, medName,); static String? getMedName() => _preferences?.getString(_keyMedName); static Future setMedDescription(String medDescription) async => await _preferences?.setString(_keyMedDescription, medDescription); static String? getMedDescription() => _preferences?.getString(_keyMedDescription); static Future setMedTime(String medTime) async => await _preferences?.setString(_keyMedTime, medTime); static String? getMedTime() => _preferences?.getString(_keyMedTime); static Future setAlarmRingtone(String alarmName) async => await _preferences?.setString(_keyAlarmSound, alarmName); static String? getAlarmRingtone() => _preferences?.getString(_keyAlarmSound); static Future setUserEmail(String useremail) async => await _preferences?.setString(_userEmail, useremail,); static String? getUserEmail() => _preferences?.getString(_userEmail); }
0
mirrored_repositories/Dr-Health/lib/src
mirrored_repositories/Dr-Health/lib/src/utils/calendar.dart
import 'package:flutter/material.dart'; import '../models/calendar_day_model.dart'; import 'calendar_day.dart'; class Calendar extends StatefulWidget { final Function chooseDay; final List<CalendarDayModel> _daysList; Calendar(this.chooseDay,this._daysList); @override _CalendarState createState() => _CalendarState(); } class _CalendarState extends State<Calendar> { @override void initState() { super.initState(); } @override Widget build(BuildContext context) { final double deviceHeight = MediaQuery.of(context).size.height - MediaQuery.of(context).padding.top; return Container( height: deviceHeight * 0.11, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [...widget._daysList.map((day) => CalendarDay(day, widget.chooseDay))], ), ); } }
0
mirrored_repositories/Dr-Health/lib/src
mirrored_repositories/Dr-Health/lib/src/screens/index.dart
import 'package:animated_text_kit/animated_text_kit.dart'; import 'package:animated_widgets/animated_widgets.dart'; import 'package:dr_health/src/components/widgets/AppDrawer.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:dr_health/src/handlers/notifications_handler.dart'; import 'package:dr_health/src/database/repository.dart'; import 'package:dr_health/src/models/pill.dart'; import 'package:dr_health/src/components/Medicine/medicines_list.dart'; import 'package:dr_health/src/utils/calendar.dart'; import 'package:dr_health/src/models/calendar_day_model.dart'; import 'package:flutter_speed_dial/flutter_speed_dial.dart'; class Home extends StatefulWidget { @override _HomeState createState() => _HomeState(); } class _HomeState extends State<Home> { //-------------------| Flutter notifications |------------------- final Notifications _notifications = Notifications(); FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin; //=============================================================== //--------------------| List of Pills from database |---------------------- // ignore: deprecated_member_use List<Pill> allListOfPills = List<Pill>(); final Repository _repository = Repository(); // ignore: deprecated_member_use List<Pill> dailyPills = List<Pill>(); //========================================================================= //-----------------| Calendar days |------------------ final CalendarDayModel _days = CalendarDayModel(); List<CalendarDayModel> _daysList; //==================================================== //handle last choose day index in calendar int _lastChooseDay = 0; @override void initState() { super.initState(); initNotifies(); setData(); _daysList = _days.getCurrentDays(); } //init notifications Future initNotifies() async => flutterLocalNotificationsPlugin = await _notifications.initNotifies(context); //--------------------GET ALL DATA FROM DATABASE--------------------- Future setData() async { allListOfPills.clear(); (await _repository.getAllData("Pills")).forEach((pillMap) { allListOfPills.add(Pill().pillMapToObject(pillMap)); }); chooseDay(_daysList[_lastChooseDay]); } //=================================================================== @override Widget build(BuildContext context) { final whSize = MediaQuery.of(context).size.height / MediaQuery.of(context).size.width; final double deviceHeight = MediaQuery.of(context).size.height - MediaQuery.of(context).padding.top; final isDialOpen = ValueNotifier(false); final Widget addReminderButton = SpeedDial ( icon: Icons.control_point_rounded, // animatedIcon: AnimatedIcons.menu_close, backgroundColor: Theme.of(context).primaryColor, overlayColor: Colors.black, overlayOpacity: 0.4, spacing: 12, spaceBetweenChildren: 12, closeManually: false, openCloseDial: isDialOpen, children: [ SpeedDialChild( child: Icon(Icons.alarm_add_rounded), backgroundColor: Theme.of(context).primaryColor.withOpacity(1.0), foregroundColor: Colors.white, label: 'Add Reminder', onTap: () => Navigator.pushNamed(context, '/AddNewMedicine'), ), // SpeedDialChild( // child: Icon(Icons.qr_code_2_rounded), // backgroundColor: Theme.of(context).primaryColor.withOpacity(1.0), // foregroundColor: Colors.white, // label: 'Scan QR Code', // onTap: () => {}, // ) ], ); // HOME BODY return WillPopScope( onWillPop: () async { if (isDialOpen.value) { isDialOpen.value = false; return false; } else { return true; } }, child: Scaffold( // resizeToAvoidBottomInset: true, floatingActionButton: Container(child: addReminderButton, margin: EdgeInsets.only(bottom: 65.0),), floatingActionButtonLocation: FloatingActionButtonLocation.endFloat, backgroundColor: Color.fromRGBO(248, 248, 248, 1), // APPLICATION BAR appBar: AppBar( backgroundColor: Theme.of(context).primaryColor, actions: [ GestureDetector( onTap: () { Navigator.pushNamed(context, '/AddNewMedicine'); }, child: Padding( padding: const EdgeInsets.only(right: 25.0), child: ShakeAnimatedWidget( enabled: true, duration: Duration(milliseconds: 2000), curve: Curves.linear, shakeAngle: Rotation.deg(z: 30), child: Icon( Icons.notifications_none, size: 35.0, ), ), ), ), ], title: Text( "Dr. Health", style: TextStyle( fontWeight: FontWeight.bold, fontSize: whSize * 10.5, color: Colors.white, ), ), centerTitle: false, elevation: 2, shadowColor: Colors.lightGreenAccent[100], shape: RoundedRectangleBorder( borderRadius: BorderRadius.vertical( bottom: Radius.circular(10), ), ), ), // APP DRAWER drawer: AppDrawer(), // END APP DRAWER body: SingleChildScrollView( child: SafeArea( child: Padding( padding: EdgeInsets.only( top: 0.0, left: 25.0, right: 25.0, bottom: 20.0), child: Column( children: [ SizedBox( height: deviceHeight * 0.03, ), Padding( padding: EdgeInsets.symmetric(horizontal: 5.0), child: SingleChildScrollView( scrollDirection: Axis.horizontal, child: Calendar(chooseDay,_daysList), ), ), SizedBox(height: deviceHeight * 0.02), dailyPills.isEmpty ? SizedBox( width: double.infinity, height: 100, child: Center( // ignore: deprecated_member_use child: WavyAnimatedTextKit( textStyle: TextStyle( fontSize: 20.0, fontWeight: FontWeight.bold, color: Theme.of(context).primaryColor), text: [ "No Reminders Today..." ], isRepeatingAnimation: true, speed: Duration(milliseconds: 150), ), ), ) : MedicinesList(dailyPills, setData, flutterLocalNotificationsPlugin) ], ), ), ), ), ), ); } //-------------------------| Click on the calendar day |------------------------- void chooseDay(CalendarDayModel clickedDay){ setState(() { _lastChooseDay = _daysList.indexOf(clickedDay); _daysList.forEach((day) => day.isChecked = false ); CalendarDayModel chooseDay = _daysList[_daysList.indexOf(clickedDay)]; chooseDay.isChecked = true; dailyPills.clear(); allListOfPills.forEach((pill) { DateTime pillDate = DateTime.fromMicrosecondsSinceEpoch(pill.time * 1000); if(chooseDay.dayNumber == pillDate.day && chooseDay.month == pillDate.month && chooseDay.year == pillDate.year){ dailyPills.add(pill); } }); dailyPills.sort((pill1,pill2) => pill1.time.compareTo(pill2.time)); }); } //=============================================================================== }
0
mirrored_repositories/Dr-Health/lib/src/screens
mirrored_repositories/Dr-Health/lib/src/screens/DetailScreen/detail_screen.dart
// @dart=2.12 import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:url_launcher/url_launcher.dart'; // ignore: must_be_immutable class DetailScreen extends StatefulWidget { String _name; String _position; String _imageUrl; String _about; String _available; String _contact; String _email; String? iconName; // ignore: non_constant_identifier_names DetailScreen(this._name, this._position, this._imageUrl, this._about, this._contact, this._email, this._available,); @override _DetailScreenState createState() => _DetailScreenState(); } class _DetailScreenState extends State<DetailScreen> { final double coverHeight = 180; final double profileHeight = 125; String? url; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Doctor Basic Information"), backgroundColor: Theme.of(context).primaryColor, ), body: ListView( padding: EdgeInsets.zero, children: <Widget>[ buildTop(), buildContent(), ], ), ); } Widget buildCoverImage() => Container( color: Colors.green.shade700, child: Image.asset( "assets/images/detail_illustration.png", width: double.infinity, height: coverHeight, fit: BoxFit.cover, ), ); Widget buildProfileImage() => CircleAvatar( radius: profileHeight / 2, backgroundColor: Colors.grey.shade800, backgroundImage: AssetImage('assets/images/avatar_profile.jpg'), foregroundImage: NetworkImage(widget._imageUrl), ); Widget buildTop() { final top = coverHeight - profileHeight / 2; final bottom = profileHeight / 2; return Stack( clipBehavior: Clip.none, alignment: Alignment.center, children: [ Container( margin: EdgeInsets.only(bottom: bottom), child: buildCoverImage() ), Positioned( top: top, child: buildProfileImage(), ), ], ); } Widget buildSocialIcon(IconData icon, String iconName) { return CircleAvatar( radius: 25, child: Material( shape: CircleBorder(), clipBehavior: Clip.hardEdge, color: Theme.of(context).primaryColor.withOpacity(0.9), child: InkWell( onTap: () async { if (iconName == "phone") { launch("tel://${widget._contact}"); } else if (iconName == "email") { String toEmail = widget._email; //'healthdr.customer.care@gmail.com'; String subject = 'Doctor Appointment Request'; String message = '(Please provide your need for an appointment here and you will be notified)'; final url = 'mailto:$toEmail?subject=${Uri.encodeFull(subject)}&body=${Uri.encodeFull(message)}'; if(await canLaunch(url)) { await launch(url); } else { launch(url); } } else { print("AN ERROR OCCURED"); } }, child: Center( child: Icon( icon, size: 32, ), ), ), ), ); } Widget buildAbout() => Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.only(left: 25.0, right: 25.0), child: Text( "About", style: TextStyle(fontSize: 26, fontWeight: FontWeight.bold), ), ), Padding( padding: const EdgeInsets.only(left: 25.0, right: 25.0, top: 10.0), child: Text( widget._about, style: TextStyle(fontSize: 16.5,), ), ), Padding( padding: const EdgeInsets.only(left: 25.0, right: 25.0, top: 12.0), child: Text( "Available", style: TextStyle(fontSize: 26, fontWeight: FontWeight.bold), ), ), Padding( padding: const EdgeInsets.only(left: 25.0, right: 25.0, top: 10.0), child: Text( widget._available, style: TextStyle(fontSize: 16.5,), ), ), ], ); Widget buildContent() => Column( children: [ const SizedBox(height: 8,), Text( widget._name, style: TextStyle( fontSize: 25, fontWeight: FontWeight.bold, ), ), const SizedBox(height: 3,), Padding( padding: const EdgeInsets.only(left: 25.0, right: 25.0), child: Text( widget._position, style: TextStyle( fontSize: MediaQuery.of(context).size.width / 20, color: Colors.black54, fontWeight: FontWeight.normal, ), ), ), const SizedBox(height: 4,), Padding( padding: const EdgeInsets.only(left: 25.0, right: 25.0), child: Center( child: Text( "Communicate with Reception for an appointment.", style: TextStyle( fontSize: 15, color: Colors.pinkAccent.shade200, fontWeight: FontWeight.normal, ), textAlign: TextAlign.justify, ), ), ), const SizedBox(height: 16,), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ buildSocialIcon(FontAwesomeIcons.phoneAlt, "phone"), const SizedBox(height: 12, width: 12,), buildSocialIcon(Icons.mail_outline, "email"), const SizedBox(height: 12,), ] ), const SizedBox(height: 14,), buildAbout(), ], ); }
0
mirrored_repositories/Dr-Health/lib/src/screens
mirrored_repositories/Dr-Health/lib/src/screens/HealthDataScreen/health_data_screen.dart
// @dart=2.12 import 'package:dr_health/src/components/cards/cards.dart' as card; import 'package:dr_health/src/handlers/video_player_handler.dart'; import 'package:dr_health/src/constant.dart'; import 'package:flutter/material.dart'; class HealthData extends StatefulWidget { @override _HealhDataState createState() => _HealhDataState(); } class _HealhDataState extends State<HealthData> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Theme.of(context).primaryColor, title: Text("Health Data"), ), backgroundColor: kWhiteColor, body: SingleChildScrollView( scrollDirection: Axis.vertical, child: SafeArea( child: Wrap( children: [ Container( color: Colors.black12, width: 400.0, height: 2.0, ), // Health Overview Video Container( alignment: Alignment.topLeft, padding: const EdgeInsets.only(top: 10.0, left: 10.0), child: Text( "Overview Video.", style: TextStyle(fontSize: 20.0, fontWeight: FontWeight.bold), ), ), Container( height: 230.0, decoration: BoxDecoration( borderRadius: BorderRadius.circular(30.0), ), child: Stack( children: [ Container( padding: EdgeInsets.symmetric( horizontal: 16, vertical: 16, ), child: Align( alignment: Alignment.center, child: MyVideoPlayer(assetFile: "assets/videos/Apple_Health_Everythings_Connected.mp4",) ), ), ], ), ), // Health Category Cards card.HealthCatCard(), // END Health Category Cards // CORONA UPDATES InkWell( child: Padding( padding: const EdgeInsets.only(top: 12.0, right: 10.0, bottom: 5.0, left: 10.0), child: ListTile( title: Text( 'CORONA UPDATES', style: TextStyle( fontWeight: FontWeight.bold, ), ), subtitle: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Stay Home, Stay Safe.', style: TextStyle( fontStyle: FontStyle.italic, ), ), Text( '(Click the card to learn more)', style: TextStyle( color: Colors.blueAccent, ), ), ], ), isThreeLine: true, trailing: Image.asset('assets/images/stay_home.gif'), tileColor: Colors.amberAccent, contentPadding: const EdgeInsets.symmetric( horizontal: 10.0, vertical: 10.0, ) ), ), onTap: () { Navigator.pushNamed(context, 'CoronaUpdateScreen'); }, ), // END CORONA UPDATES // WHY DRINKING WATER // InkWell( // child: Padding( // padding: const EdgeInsets.only(top: 12.0, right: 10.0, bottom: 5.0, left: 10.0), // child: ListTile( // title: Text( // 'DRINKING WATER', // style: TextStyle( // fontWeight: FontWeight.bold, // ), // ), // subtitle: Column( // crossAxisAlignment: CrossAxisAlignment.start, // children: [ // Text( // 'The Benefits of Water in our daily life', // style: TextStyle( // fontStyle: FontStyle.italic, // ), // ), // Text( // '(Click the card to learn more)', // style: TextStyle( // color: Colors.blueGrey, // ), // ), // ], // ), // isThreeLine: true, // trailing: Image.asset('assets/images/water_guide.gif'), // tileColor: Colors.lightBlueAccent, // contentPadding: const EdgeInsets.symmetric( // horizontal: 10.0, // vertical: 10.0, // ) // ), // ), // onTap: () { // Navigator.pushNamed(context, 'CoronaUpdateScreen'); // }, // ), // END WHY DRINKING WATER ], ), ), ), ); } }
0
mirrored_repositories/Dr-Health/lib/src/screens/HealthDataScreen
mirrored_repositories/Dr-Health/lib/src/screens/HealthDataScreen/sleep/sleep_screen.dart
import 'package:dr_health/src/components/HealthData/sleep_data.dart'; import 'package:flutter/material.dart'; class SleepScreen extends StatefulWidget { @override _SleepScreenState createState() => _SleepScreenState(); } class _SleepScreenState extends State<SleepScreen> { @override Widget build(BuildContext context) { return Scaffold( body: SleepData(), ); } }
0
mirrored_repositories/Dr-Health/lib/src/screens/HealthDataScreen
mirrored_repositories/Dr-Health/lib/src/screens/HealthDataScreen/Nutrition/nutrition_screen.dart
import 'package:dr_health/src/components/HealthData/nutrition_data.dart'; import 'package:flutter/material.dart'; class NutritionScreen extends StatefulWidget { @override _NutritionScreenState createState() => _NutritionScreenState(); } class _NutritionScreenState extends State<NutritionScreen> { @override Widget build(BuildContext context) { return Scaffold( body: NutritionData(), ); } }
0
mirrored_repositories/Dr-Health/lib/src/screens/HealthDataScreen
mirrored_repositories/Dr-Health/lib/src/screens/HealthDataScreen/Mindfulness/mindfulness_screen.dart
import 'package:dr_health/src/components/HealthData/mindfulness_data.dart'; import 'package:flutter/material.dart'; class MindfulnessScreen extends StatefulWidget { @override _MindfulnessScreenState createState() => _MindfulnessScreenState(); } class _MindfulnessScreenState extends State<MindfulnessScreen> { @override Widget build(BuildContext context) { return Scaffold( body: MindfulnessData(), ); } }
0
mirrored_repositories/Dr-Health/lib/src/screens/HealthDataScreen
mirrored_repositories/Dr-Health/lib/src/screens/HealthDataScreen/Activity/activity_screen.dart
import 'package:dr_health/src/components/HealthData/activity_data.dart'; import 'package:flutter/material.dart'; class ActivityScreen extends StatefulWidget { @override _ActivityScreenState createState() => _ActivityScreenState(); } class _ActivityScreenState extends State<ActivityScreen> { @override Widget build(BuildContext context) { return Scaffold( body: ActivityData(), ); } }
0
mirrored_repositories/Dr-Health/lib/src/screens
mirrored_repositories/Dr-Health/lib/src/screens/SettingsScreen/settings.dart
// @dart=2.12 // ignore_for_file: import_of_legacy_library_into_null_safe import 'package:dr_health/src/constant.dart'; import 'package:dr_health/src/handlers/datasource_handler.dart'; import 'package:flutter/material.dart'; import 'package:system_settings/system_settings.dart'; class SettingsPage extends StatefulWidget { @override _SettingsPageState createState() => _SettingsPageState(); } class _SettingsPageState extends State<SettingsPage> { @override Widget build(BuildContext context) { return Scaffold( backgroundColor: kWhiteColor, appBar: AppBar( backgroundColor: Theme.of(context).primaryColor, title: Text( "Settings" ), ), body: settingTiles(), ); } settingTiles() { return SafeArea( child: SingleChildScrollView( scrollDirection: Axis.vertical, child: Container( child: Column( children: [ Padding( padding: const EdgeInsets.only(top: 12.0, left: 15.0, bottom: 12.0), child: Align( alignment: Alignment.centerLeft, child: Text( "General", style: TextStyle( color: Theme.of(context).primaryColor.withOpacity(0.9), fontSize: 20.0, fontWeight: FontWeight.w600, ), ), ), ), ListTile( leading: Icon(Icons.settings_applications, color: Theme.of(context).primaryColor,), title: Text( "Notifications Settings", style: TextStyle( fontWeight: FontWeight.w600, ), ), subtitle: Padding( padding: const EdgeInsets.only(top: 6.0), child: Text( "Notification settings like sound, vibration etc.", style: TextStyle( fontSize: 13.5, color: Colors.black87, ), ), ), onTap: () => SystemSettings.appNotifications(), ), ListTile( leading: Icon(Icons.info, color: Theme.of(context).primaryColor,), title: Text( "Application Info", style: TextStyle( fontWeight: FontWeight.w600, ), ), subtitle: Padding( padding: const EdgeInsets.only(top: 6.0), child: Text( "Dr. Health Application information", style: TextStyle( fontSize: 13.5, color: Colors.black87, ), ), ), onTap: () => SystemSettings.app(), ), // ExpansionTile( // textColor: Theme.of(context).primaryColor, // iconColor: Theme.of(context).primaryColor, // leading: Icon(Icons.notifications, color: Theme.of(context).primaryColor,), // title: Text( // 'Notifications', // style: TextStyle( // fontWeight: FontWeight.w600, // ), // ), // subtitle: Padding( // padding: const EdgeInsets.only(top: 8.0), // child: Text( // "Set Notification Sound", // style: TextStyle( // fontSize: 13.5, // color: Colors.black87, // ), // ), // ), // children: [ // Align( // alignment: Alignment.centerLeft, // child: ListTile( // leading: Icon(Icons.notifications_active), // title: Text( // "Alarm Ringtone", // style: TextStyle( // color: Colors.black87, // ), // ), // subtitle: DropdownButton<String>( // value: _defaultSound, // style: TextStyle(color: Colors.black54, fontWeight: FontWeight.w600), // items: <String>['long\ cold\ sting', 'simplesound'] // .map<DropdownMenuItem<String>>((String value) { // return DropdownMenuItem<String>( // value: value.replaceAll(' ', ''), // child: Text(value), // ); // }).toList(), // hint: Text( // AppPreferences.getAlarmRingtone()?.replaceAll('', ' ') ?? 'long cold sting (Default)', // style: TextStyle( // color: Colors.black, // fontWeight: FontWeight.w600, // ), // ), // onChanged: (String? value) async { // String _newSound = value!.replaceAll(' ', ''); // await AppPreferences.setAlarmRingtone(_newSound); // setState(() { // _defaultSound = _newSound; // }); // }, // ), // ), // ), // ], // ), Padding( padding: const EdgeInsets.only(top: 10.0, left: 15.0, bottom: 0.9), child: Align( alignment: Alignment.centerLeft, child: Text( "Licence", style: TextStyle( color: Theme.of(context).primaryColor.withOpacity(0.9), fontSize: 18.0, fontWeight: FontWeight.w600, ), ), ), ), Padding( padding: const EdgeInsets.only(top: 6.0), child: ListView.builder( controller: ScrollController(), scrollDirection: Axis.vertical, shrinkWrap: true, itemCount: DataSource.licenceAndTerms.length, itemBuilder: (context, index) { return ExpansionTile( textColor: Theme.of(context).primaryColor, iconColor: Theme.of(context).primaryColor, leading: Icon(Icons.read_more, color: Theme.of(context).primaryColor,), title: Text( DataSource.licenceAndTerms[index]['Title'], style: TextStyle(fontWeight: FontWeight.w600), ), children: <Widget>[ Padding( padding: const EdgeInsets.all(12.0), child: Text(DataSource.licenceAndTerms[index]['Body']), ) ], ); }), ), Padding( padding: const EdgeInsets.only(top: 10.0, left: 15.0, bottom: 0.9), child: Align( alignment: Alignment.centerLeft, child: Text( "About", style: TextStyle( color: Theme.of(context).primaryColor.withOpacity(0.9), fontSize: 18.0, fontWeight: FontWeight.w600, ), ), ), ), Padding( padding: const EdgeInsets.only(top: 10.0, left: 15.0, bottom: 0.9), child: Align( alignment: Alignment.centerLeft, child: ListTile( leading: Icon(Icons.menu_book_outlined, color: Theme.of(context).primaryColor,), title: Text( "Dr. Health", style: TextStyle( fontWeight: FontWeight.w600, ), ), subtitle: Text( "Version 1.0.0", style: TextStyle( fontSize: 13.5, ), ), ), ), ), ], ), ), ), ); } }
0
mirrored_repositories/Dr-Health/lib/src/screens
mirrored_repositories/Dr-Health/lib/src/screens/SearchScreen/local_search.dart
import 'package:dr_health/src/screens/SearchScreen/doctors_list.dart'; import 'package:flutter/material.dart'; class LocalSearch extends StatelessWidget { @override Widget build(BuildContext context) => Scaffold ( appBar: AppBar( title: Text("Search"), centerTitle: true, actions: [ IconButton( icon: Icon(Icons.search), onPressed: () { showSearch( context: context, delegate: ServiceSearch(), ); // print(results); }, ), ], backgroundColor: Theme.of(context).primaryColor, ), body: Container ( color: Colors.white, child: DoctorSearchScreen(), ) ); } class ServiceSearch extends SearchDelegate<String> { final services = [ 'Eye and Optical Services', 'Counselling and testing for HIV and provisions of antiretroviral drugs (ARV) to people living with HIV/AIDS', 'Minor surgery', 'Reproductive and child health services', 'Prevention of mother to child transmission of HIV' 'Ambulance Services', 'Health education, communication and counselling students on adolescent reproductive health', 'Specialized clinics in Obstetrics and Gynaecology, Paediatrics, Psychiatry and Mental Health and Medical imaging. It also offers special clinic in dermatological conditions, sexually transmitted infections and diabetes.' ]; final recentServices = [ 'Eye and Optical Services', 'Ambulance Services', 'Counselling and testing for HIV and provisions of antiretroviral drugs (ARV) to people living with HIV/AIDS', ]; @override List<Widget> buildActions(BuildContext context) => [ IconButton( icon: Icon(Icons.clear), onPressed: () { if(query.isEmpty) { close(context, null); } else { query = ''; showSuggestions(context); } }, ), ]; @override Widget buildLeading(BuildContext context) => IconButton( icon: Icon(Icons.arrow_back), onPressed: () { close(context, null); }, ); @override Widget buildResults(BuildContext context) => Center ( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( query, style: TextStyle( color: Colors.black, fontSize: 42, fontWeight: FontWeight.bold, ), ), ], ), ); @override Widget buildSuggestions(BuildContext context) { final suggestions = query.isEmpty ? recentServices : services.where((service) { final serviceLower = service.toLowerCase(); final queryLower = query.toLowerCase(); return serviceLower.startsWith(queryLower); }).toList(); return buildSuggestionsSuccess(suggestions); } Widget buildSuggestionsSuccess(List<String> suggestions) => ListView.builder( itemCount: suggestions.length, itemBuilder: (context, index) { final suggestion = suggestions[index]; final queryText = suggestion.substring(0, query.length); final remainingText = suggestion.substring(query.length); return ListTile ( leading: Icon(Icons.ac_unit), // title: Text(suggestion), title: RichText( text: TextSpan( text: queryText, style: TextStyle( color: Colors.black, fontWeight: FontWeight.bold, fontSize: 18, ), children: [ TextSpan( text: remainingText, style: TextStyle( color: Colors.grey, fontSize: 18, ), ), ], ), ), subtitle: Text('Make Appointment'), trailing: Icon(Icons.book), onTap: () { query = suggestion; close(context, suggestion); // showResults(context); }, ); }, ); }
0
mirrored_repositories/Dr-Health/lib/src/screens
mirrored_repositories/Dr-Health/lib/src/screens/SearchScreen/doctors_list.dart
// @dart=2.12 import 'package:dr_health/src/provider/dkt_provider.dart'; import 'package:dr_health/src/constant.dart'; import 'package:flutter/material.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; class DoctorSearchScreen extends StatefulWidget { @override _DoctorSearchScreenState createState() => _DoctorSearchScreenState(); } class _DoctorSearchScreenState extends State<DoctorSearchScreen> { @override Widget build(BuildContext context) { final Stream<QuerySnapshot> users = FirebaseFirestore.instance.collection('doctors_details').snapshots(); String? doctorName; String? doctorPos; String? doctorProfile; String? doctorAbout; String? receptionPhone; String? receptionEmail; String? doctorAvailability; return Scaffold( backgroundColor: kWhiteColor, appBar: AppBar( backgroundColor: Theme.of(context).primaryColor, title: Text( "Doctors List", ), ), body: SafeArea( child: SingleChildScrollView( scrollDirection: Axis.vertical, child: Column( children: [ Container( padding: EdgeInsets.all(10.0), child: StreamBuilder<QuerySnapshot>( stream: users, builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) { if(snapshot.connectionState == ConnectionState.none) { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ CircularProgressIndicator(), SizedBox(height: 8.0), Text("No Connection and No Cached Data...", textAlign: TextAlign.center,), ] ), ); } if(snapshot.connectionState == ConnectionState.waiting) { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ CircularProgressIndicator(), SizedBox(height: 8.0), Text("Loading, please wait...", textAlign: TextAlign.center,), ] ), ); } final data = snapshot.requireData; return ListView.builder( itemCount: data.size, scrollDirection: Axis.vertical, shrinkWrap: true, physics: NeverScrollableScrollPhysics(), itemBuilder: (context, index) { try { doctorName = data.docs[index]['Fname'] + ' ' + data.docs[index]['Lname']; doctorPos = data.docs[index]['Position']; doctorProfile = data.docs[index]['Profile']; doctorAbout = data.docs[index]['About']; receptionPhone = data.docs[index]['Contact']; receptionEmail = data.docs[index]['Email_Address']; doctorAvailability = data.docs[index]['Available']; } catch(Ex) {print("ERROR");} return DoctorList( doctorName!, doctorPos!, doctorProfile!, doctorAbout!, receptionPhone!, receptionEmail!, doctorAvailability! ); } ); } ), ), ], ), ), ), ); } }
0
mirrored_repositories/Dr-Health/lib/src/screens
mirrored_repositories/Dr-Health/lib/src/screens/SearchScreen/search.dart
// @dart=2.12 import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:dr_health/src/handlers/firebase_search_controller.dart'; import 'package:dr_health/src/screens/DetailScreen/detail_screen.dart'; import 'package:dr_health/src/screens/SearchScreen/doctors_list.dart'; import 'package:flutter/material.dart'; import 'package:get/get.dart'; class Search extends StatefulWidget { @override _SearchState createState() => _SearchState(); } class _SearchState extends State<Search> { @override Widget build(BuildContext context) { final searchController = TextEditingController(); QuerySnapshot? snapshotData; bool isExecuted = false; Widget searchData() { return ListView.builder( itemCount: snapshotData!.docs.length, itemBuilder: (BuildContext context, int index) { return GestureDetector( onTap: () { Get.to( DetailScreen( snapshotData!.docs[index]['Fname'] + ' ' + snapshotData!.docs[index]['Lname'], snapshotData!.docs[index]['Position'], snapshotData!.docs[index]['Profile'], snapshotData!.docs[index]['About'], snapshotData!.docs[index]['Contact'], snapshotData!.docs[index]['Available'], snapshotData!.docs[index]['Email_Address']), transition: Transition.downToUp, arguments: snapshotData!.docs[index] ); }, child: ListTile( leading: CircleAvatar( backgroundImage: NetworkImage( snapshotData!.docs[index]['Profile'] ), ), title: Text( snapshotData!.docs[index]['Fname'] + ' ' + snapshotData!.docs[index]['Lname'], style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 20.0 ), ), subtitle: Text( snapshotData!.docs[index]['Profession'], style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 18.0 ), ), ), ); } ); } return Scaffold( floatingActionButton: FloatingActionButton( child: Icon(Icons.delete_sweep_outlined), onPressed: () { setState(() { isExecuted = false; } ); }, backgroundColor: Colors.green, elevation: 12.0, splashColor: Colors.lightGreenAccent[100], ), appBar: AppBar( actions: [ GetBuilder<DataController>( init: DataController(), builder: (val) { return IconButton( icon: Icon(Icons.search), onPressed: () { val.queryPosition(searchController.text).then((value) { snapshotData = value; setState(() { isExecuted = true; }); }); }, ); } ), ], title: TextField( style: TextStyle(color: Colors.white), decoration: InputDecoration( hintText: 'Search by profession', hintStyle: TextStyle(color: Colors.white, fontSize: 18.0), ), controller: searchController, ), backgroundColor: Colors.green, ), body: isExecuted ? searchData() : DoctorSearchScreen(), ); } }
0
mirrored_repositories/Dr-Health/lib/src/screens
mirrored_repositories/Dr-Health/lib/src/screens/SearchScreen/user_check.dart
// //@dart=2.9 // import 'package:cloud_firestore/cloud_firestore.dart'; // import 'package:dr_health/src/screens/index.dart'; // import 'package:flutter/material.dart'; // import 'package:flutter/services.dart'; // import 'package:flutter_fadein/flutter_fadein.dart'; // import 'package:flutter_swiper/flutter_swiper.dart'; // import 'package:flutter_spinkit/flutter_spinkit.dart'; // import 'package:fluttertoast/fluttertoast.dart'; // import 'package:get/get.dart'; // import 'package:get/get.dart'; // import 'package:get_storage/get_storage.dart'; // import 'package:dr_health/main.dart'; // import 'package:dr_health/src/auth/auth.dart'; // import 'dart:async'; // import 'package:dr_health/src/constant.dart'; // import 'package:shared_preferences/shared_preferences.dart'; // import 'package:firebase_core/firebase_core.dart'; // import 'dart:math'; // import 'package:showcaseview/showcaseview.dart'; // class SplashScreen extends StatefulWidget { // @override // _SplashScreenState createState() => _SplashScreenState(); // } // class _SplashScreenState extends State<SplashScreen> { // @override // String finalEmail; // @override // Future <void> initState() { // getValidationData().whenComplete(() async { // Timer(Duration(seconds: 15), () async { // WidgetsFlutterBinding.ensureInitialized(); // await Firebase.initializeApp(); // Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (_) => finalEmail == null ? LoginPage() : Home2())); //LoginPage // }); // super.initState(); // }); // } // Future getValidationData() async { // final SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); // var obtainedEmail = sharedPreferences.getString('email'); // setState(() { // finalEmail = obtainedEmail; // }); // } // @override // Widget build(BuildContext context) { // return Container( // decoration: BoxDecoration( // gradient: LinearGradient( // begin: Alignment.topLeft, // end: Alignment.bottomRight, // colors: [ // Colors.black, // Colors.blue[900], // Colors.green[900], // Colors.yellow[700] // ] // ) // ), // child: Scaffold( // backgroundColor: Colors.black26, // body: Padding( // padding: const EdgeInsets.fromLTRB(10, 10, 10, 80), // child: Column( // mainAxisAlignment: MainAxisAlignment.center, // children: [ // // FadeIn( // // duration: Duration(seconds: 7), // // child: Image( // // image: AssetImage("assets/images/welcome.jpg"), // // height: 260, // // ), // // ), // SpinKitRipple( // duration: Duration(seconds: 4), // color: Colors.white, // size: 100.0, // ), // SizedBox(height: 40), // FadeIn( // duration: Duration(seconds: 1), // child: Text("Welcome", // style: TextStyle( // fontSize: 18, // letterSpacing: 1.0, // color: Colors.green, // ), // ), // ), // SizedBox(height: 12), // FadeIn(duration: Duration(seconds: 4), // child: Text("To")), // SizedBox(height: 12), // FadeIn(duration: Duration(seconds: 7),child: Text('Dr. Health' , style: TextStyle( // fontSize: 20, // letterSpacing: 1.0, // color: Colors.yellow, // ),)) // ], // ), // ), // ), // ); // } // } // class Home2 extends StatefulWidget { // static const PREFERENCES_IS_FIRST_LAUNCH_STRING = "PREFERENCES_IS_FIRST_LAUNCH_STRING"; // const Home2({Key key}) : super(key: key); // @override // HomeState createState() => HomeState(); // } // class HomeState extends State<Home2> { // final _themeData = GetStorage(); // bool _isdarkMode = false; // // List<String> autoSelect = ['A' , 'B' , 'C']; // //[A, B , C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S ,T ,U, V ,W , X , Y , Z]; // GlobalKey _one = GlobalKey(); // GlobalKey _three = GlobalKey(); // GlobalKey _two = GlobalKey(); // BuildContext myContext; // @override // void initState(){ // super.initState(); // WidgetsBinding.instance.addPostFrameCallback( // (_) { // _isFirstLaunch().then((result){ // if(result) // ShowCaseWidget.of(myContext).startShowCase([_one ,_two , _three]); // }); // } // ); // _themeData.writeIfNull("darkmode", false); // _isdarkMode = _themeData.read("darkmode"); // } // bool _visible = true; // bool visible = true; // bool autoPlay = false; // int itemCount = 1; // int indexa; // List<String> Vipera = ['Methali' , 'Mafumbo', 'Vitendawili' , 'Nahau', 'Misemo', 'Mafumbo']; // List<String> alpha = ['A' , 'B' , 'C' , 'D' ,"E"]; // var rng = new Random(); // dynamic Ulizo = 'Kozi mwana Mandanda'; // List<String> Uliza = ['Kozi mwana Mandanda' , 'Asiyesikia la mkuu']; // dynamic Majibu = "Kulala na njaa kupenda"; // dynamic Maelezo = "Ahangaikaye kwa chochote kupata Riziki ya halali chochote atapata kama riziki. \n Methali inayofanana: Mtembea bure si sawa na mkaa bure"; // // String alpha = 'A'; // @override // Widget build(BuildContext context) { // // dynamic indexa = rng.nextInt(5); // // print(alpha[indexa]); // int ItemCount = 100; // // Ulizo[1]; // int itemCount = 0; // // var l = new List.generate(12, (_) => rng.nextInt(10)); // return ClipRRect( // borderRadius: BorderRadius.all( // Radius.circular(20) // ), // child: ShowCaseWidget( // builder: Builder(builder: (context) { // myContext = context; // return FadeIn( // duration: Duration(seconds: 2), // child: Scaffold( // drawer: _customDrawer(context), // backgroundColor: _isdarkMode ? Colors.black : Colors.white, // appBar: new AppBar( // // shape: RoundedRectangleBorder( // // borderRadius: BorderRadius.vertical( // // bottom: Radius.circular(90) // // ) // // ), // shadowColor: Colors.white, // toolbarHeight: 50, // elevation: 25, // backgroundColor: Colors.black26, // flexibleSpace: Container( // decoration: BoxDecoration( // borderRadius: BorderRadius.vertical(bottom: Radius.circular(12)), // gradient: LinearGradient( // colors: [ // Colors.green[900], // Colors.brown[900], // Colors.blueGrey, // ] // ) // ), // ), // // backgroundColor: Colors.black26, // title: new Text("Semi za Kiswahili", style: TextStyle(letterSpacing: 2.9)), // centerTitle: true, // ), // body: GestureDetector( // onTap: () async { // Fluttertoast.showToast(msg: ".......", toastLength: Toast.LENGTH_LONG); // DocumentSnapshot variable = await FirebaseFirestore.instance.collection('Methali').doc('A').get(); // Ulizo = variable[itemCount.toString()][0]; // Majibu = variable[itemCount.toString()][1]; // Maelezo = variable[itemCount.toString()][2]; // Fluttertoast.showToast(msg: ".", fontSize: 10); // if(itemCount >10) { // Fluttertoast.showToast(msg: "Mwisho !", backgroundColor: Colors.teal); // } // itemCount++; // }, // onLongPress: ()async { if(itemCount > 0) {itemCount--;} // Fluttertoast.showToast(msg: ".......", toastLength: Toast.LENGTH_LONG); // DocumentSnapshot variable = await FirebaseFirestore.instance.collection('Methali').doc('A').get(); // Ulizo = variable[itemCount.toString()][0]; // Majibu = variable[itemCount.toString()][1]; // Maelezo = variable[itemCount.toString()][2]; // Fluttertoast.showToast(msg: ".", fontSize: 10); // }, // child: Swiper( // // onIndexChanged: (index) async { // // Fluttertoast.showToast(msg: ".....", textColor: Colors.blue, fontSize: 10, toastLength: Toast.LENGTH_LONG); // // DocumentSnapshot variable = await FirebaseFirestore.instance.collection('Methali').doc(alpha).get(); // // Ulizo = variable[index.toString()][0]; // // Majibu = variable[index.toString()][1]; // // Maelezo = variable[index.toString()][2]; // // // itemCount++; itemCounta++; // // Fluttertoast.showToast(msg: ".", backgroundColor: Colors.black12, fontSize: 10); // // if(index==0) {Fluttertoast.showToast(msg: "Mwanzo", textColor: Colors.blue, fontSize: 10, toastLength: Toast.LENGTH_LONG);} // // // // print(index); // // } , // autoplayDisableOnInteraction: true, // duration: 2000, // itemBuilder: (BuildContext context,int index){ // return Padding( // padding: const EdgeInsets.fromLTRB(3, 0, 3, 0), // child: Column( // mainAxisAlignment: MainAxisAlignment.center, // children: [ // RaisedButton.icon(onPressed: () { // }, // color: Colors.blueGrey , icon: Icon(Icons.arrow_circle_down), label: Text("Semi za Leo")), // SizedBox(height: 90), // Showcase( // key: _one, // title: 'ili Kupata semi zaidi', // description: ' inahitaji uwe umeungwanishwa katika mtandao', // child: FadeIn( // duration: Duration(seconds: 2), // child: Text('$Ulizo', // //testMap.keys.elementAt(index), // style: TextStyle( // fontSize: 19, // letterSpacing: 1.5, // color: _isdarkMode ? Colors.green : Colors.black87, // // color: Colors.greenAccent // // color: Colors.black, // ),), // ), // ), // SizedBox(height: 25), // Showcase( // key: _three, // title: 'Kupata semi iliyotangulia:', // description: ' Bonyeza kioo na shikilia kwa mda ,kisha vuta kwenda kulia', // child: Text(''), // ), // AnimatedOpacity( // opacity: _visible ? 1.0 : 0.0, // duration: const Duration(milliseconds: 1000), // child: FadeIn( // duration: Duration(seconds: 7), // child: Text('$Majibu', // // testMap.values.elementAt(index), // style: TextStyle( // fontSize: 16, // letterSpacing: 1.9, // color: _isdarkMode ? Colors.greenAccent : Colors.black87, // // color: Colors.brown // ), // ), // ), // ), // SizedBox(height: 25), // FlatButton.icon(onPressed: (){ // setState((){ // _visible = !_visible; // }); // }, // icon: Icon(_visible ? Icons.visibility : Icons.visibility_off), label: Text('')), // SizedBox(height: 2), // Showcase( // key: _two, // title: 'Kupata semi inayofuata:', // description: 'Bonyeza kwenye kioo, subiri kidogo ,kisha vuta kwenda kushoto', // child: Text(''), // ), // FlatButton.icon(onPressed: () { // setState(() { // visible = ! visible; // }); // }, // label: Text('Maelezo'), icon: Icon(Icons.arrow_circle_down_outlined)), // FadeIn( // duration: Duration(seconds: 5), // child: Card( // shadowColor: Colors.brown, // color: Colors.black26, // child: Padding( // padding: const EdgeInsets.all(8.0), // child: Padding( // padding: const EdgeInsets.fromLTRB(5, 0, 5, 7), // child: AnimatedOpacity( // opacity: visible ? 1.0 : 0.0, // duration: const Duration(milliseconds: 1000), // child: FadeIn( duration: Duration(seconds: 3), curve: Curves.elasticIn,child: Text('$Maelezo', style: TextStyle(color: Colors.yellowAccent),)), // ), // ), // ), // ), // ), // ], // ), // ); // }, // itemCount: ItemCount,//testMap.length, // //pagination: SwiperPagination(), // control: SwiperControl(), // ), // ), // ), // ); // }), // )); // } // //Customized Navigation bar // Widget _customDrawer(BuildContext context) { // return FadeIn( // duration: Duration(seconds: 2), // child: Container( // width: 250, // padding: EdgeInsets.all(2), // child: ClipRRect( // borderRadius: BorderRadius.all( // Radius.circular(12.0), // ), // child: Drawer( // elevation: 0.0, // child: ListView( // padding: EdgeInsets.zero, // children: <Widget>[ // DrawerHeader( // child: Card( // color: Colors.black26, // child: Center( // child: Text( // "Vipera vya semi ", // style: TextStyle(color: _isdarkMode ? Colors.white : Colors.white, // fontSize: 25 // ), // ), // ), // ), // decoration: BoxDecoration( // borderRadius: BorderRadius.all(Radius.circular(10.0)), // image: DecorationImage( // fit: BoxFit.cover, // image: AssetImage('assets/images/cover.jpg'))), // ), // ListTile( // leading: Icon(Icons.border_color), // title: Text('Methali' ,style: TextStyle(fontSize: 12, letterSpacing: 2.0),), // onTap: () => { Navigator.pushNamed(context, '/mithali')}, // ), // ListTile( // leading: Icon(Icons.border_color), // title: Text('Vitendawili' , style: TextStyle(fontSize: 12, letterSpacing: 2.0),), // onTap: () => {Navigator.pushNamed(context, '/vitendawili')}, // ), // ListTile( // leading: Icon(Icons.border_color), // title: Text('Nahau' ,style: TextStyle(fontSize: 12, letterSpacing: 2.0),), // onTap: () => { // Navigator.pushNamed(context , '/nahau')}, // ), // ListTile( // leading: Icon(Icons.border_color), // title: Text('Mafumbo' , style: TextStyle(fontSize: 12, letterSpacing: 2.0),), // onTap: () => { // Navigator.pushNamed(context , '/mafumbo')}, // ), // ListTile( // leading: Icon(Icons.border_color), // title: Text('Misemo' , style: TextStyle(fontSize: 12, letterSpacing: 2.0),), // onTap: () => { // Navigator.pushNamed(context , '/misemo') // }, // ), // Divider(height: 20.0, color: Colors.black26,), // SizedBox(height: 10), // SwitchListTile( // secondary: const Icon(Icons.ac_unit), // title: const Text( // "Mandhari", // ), // value: _isdarkMode, // onChanged: (value){ // setState(() { // _isdarkMode = value; // }); // _isdarkMode // ? Get.changeTheme(ThemeData.dark()) // : Get.changeTheme(ThemeData.light()); // _themeData.write('darkmode', value); // }, // activeThumbImage: const AssetImage("assets/half-moon.png"), // inactiveThumbImage: const AssetImage("assets/sun.png"), // activeColor: Colors.blue, // inactiveTrackColor: Colors.grey, // ), // ListTile( // leading: Icon(Icons.border_color), // title: Text('Kuhusu' , style: TextStyle(fontSize: 12, letterSpacing: 2.0),), // onTap: () => { // Navigator.pushNamed(context , '/kuhusu') // }, // ), // ListTile( // leading: Icon(Icons.comment_sharp), // title: Text('Maoni / Ushauri' ,style: TextStyle(fontSize: 12, color: Colors.green , letterSpacing: 2.0),), // onTap: () => Navigator.pushNamed(context , '/maoni'), // //onTap: () => SystemNavigator.pop(), // ), // ListTile( // leading: Icon(Icons.fullscreen_exit_outlined), // title: Text('Ondoka' ,style: TextStyle(fontSize: 12, color: Colors.amber , letterSpacing: 2.0),), // onTap: () async { // final SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); // sharedPreferences.remove('email'); // Navigator.push(context , MaterialPageRoute(builder: (context) => SplashScreen())); // } // ), // ListTile( // leading: Icon(Icons.fullscreen_exit_outlined), // title: Text('funga' ,style: TextStyle(fontSize: 12, color: Colors.red , letterSpacing: 2.0),), // // onTap: () => SystemNavigator.pop(), // onTap: () => Navigator.push(context , MaterialPageRoute(builder: (context) => GoodbyeScreen())), // ), // ], // ), // ), // ), // ), // ); // } // } // // Goodbye Screen // class GoodbyeScreen extends StatefulWidget { // @override // _GoodbyeScreenState createState() => _GoodbyeScreenState(); // } // class _GoodbyeScreenState extends State<GoodbyeScreen> { // @override // Future <void> initState() { // Timer(Duration(seconds: 5), (){ // SystemNavigator.pop(); // }); // super.initState(); // } // @override // Widget build(BuildContext context) { // return Container( // decoration: BoxDecoration( // gradient: LinearGradient( // begin: Alignment.topLeft, // end: Alignment.bottomRight, // colors: [ // Colors.black, // Colors.blue[900], // Colors.green[900], // Colors.yellow[700] // ] // ) // ), // child: Scaffold( // backgroundColor: Colors.black26, // body: Padding( // padding: const EdgeInsets.fromLTRB(10, 10, 10, 80), // child: Column( // mainAxisAlignment: MainAxisAlignment.center, // children: [ // SpinKitSpinningLines ( // duration: Duration(seconds: 4), // color: Colors.white, // size: 100.0, // ), // SizedBox(height: 40), // FadeIn( // duration: Duration(seconds: 1), // child: Text("Karibu tena", // style: TextStyle( // fontSize: 18, // letterSpacing: 1.0, // color: Colors.green, // ), // ), // ), // ], // ), // ), // ), // ); // } // } // // // Display the ShowcaseView only on the first launch // // Future<bool> _isFirstLaunch() async{ // // final sharedPreferences = await SharedPreferences.getInstance(); // // bool isFirstLaunch = sharedPreferences.getBool(Home.PREFERENCES_IS_FIRST_LAUNCH_STRING) ?? true; // // if(isFirstLaunch) // // sharedPreferences.setBool(Home.PREFERENCES_IS_FIRST_LAUNCH_STRING, false); // // return isFirstLaunch; // // } // // // // // // body: GestureDetector( // // // onTap: () async { // // // if(itemCount >10) { // // // // // // Fluttertoast.showToast(msg: "Mwisho !", backgroundColor: Colors.teal); // // // } // // // indexa = rng.nextInt(3); // // // // // // Fluttertoast.showToast(msg: ".......", toastLength: Toast.LENGTH_LONG); // // // DocumentSnapshot variable = await FirebaseFirestore.instance.collection(Vipera[indexa].toString()).doc(alpha[indexa].toString()).get(); // // // Ulizo = variable[itemCount.toString()][0]; // // // Majibu = variable[itemCount.toString()][1]; // // // Maelezo = variable[itemCount.toString()][2]; // // // Fluttertoast.showToast(msg: ".", fontSize: 10); // // // itemCount++; // // // print(itemCount); // // // // // // // // // },
0
mirrored_repositories/Dr-Health/lib/src/screens
mirrored_repositories/Dr-Health/lib/src/screens/CoronaScreen/corona_stats_screen.dart
// @dart=2.12 // ignore_for_file: import_of_legacy_library_into_null_safe import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:dr_health/src/handlers/datasource_handler.dart'; import 'package:dr_health/src/screens/CoronaScreen/country_screen.dart'; import 'package:dr_health/src/components/panels/info_panel.dart'; import 'package:dr_health/src/components/panels/most_affected_countries.dart'; import 'package:dr_health/src/components/cards/cards.dart'; import 'package:http/http.dart' as http; class CoronaPage extends StatefulWidget { @override _CoronaPageState createState() => _CoronaPageState(); } class _CoronaPageState extends State<CoronaPage> { Map? worldData; fetchWorldWideData() async { try { http.Response response = await http.get(Uri.parse('https://corona.lmao.ninja/v3/covid-19/all')); setState(() { worldData = json.decode(response.body); }); } catch(Ex) { debugPrint("NO INTERNET : $Ex"); } } List? countryData; fetchCountryData() async { try { http.Response response = await http.get(Uri.parse('https://corona.lmao.ninja/v3/covid-19/countries?sort=cases')); setState(() { countryData = json.decode(response.body); }); } catch(Ex) { debugPrint("NO INTERNET : $Ex"); } } Future fetchData() async{ fetchWorldWideData(); fetchCountryData(); print('fetchData called'); } @override void initState() { try { fetchData(); super.initState(); } catch(Exception) { print('NO INTERNET : $Exception'); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Theme.of(context).primaryColor, centerTitle: true, title: Text( 'COVID-19 TRACKER', ), ), body: RefreshIndicator( onRefresh: fetchData, child: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Container( height: 100, alignment: Alignment.center, padding: EdgeInsets.all(10), color: Colors.orange[100], child: Text( DataSource.quote, style: TextStyle( color: Colors.orange[800], fontWeight: FontWeight.bold, fontSize: 16), ), ), Padding( padding: const EdgeInsets.symmetric(vertical: 10.0, horizontal: 10), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Text( 'Worldwide', style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold), ), GestureDetector( onTap: () { Navigator.push(context, MaterialPageRoute(builder: (context) => CountryPage())); }, child: Container( decoration: BoxDecoration( color: primaryBlack, borderRadius: BorderRadius.circular(15)), padding: EdgeInsets.all(10), child: Text( 'Regional', style: TextStyle( fontSize: 16, color: Colors.white, fontWeight: FontWeight.bold), )), ), ], ), ), worldData == null ? Center(child: Column( children: [ CircularProgressIndicator(), SizedBox(height: 3,), Text( '(If taking too long, check your internet connection.)', style: TextStyle( color: Colors.redAccent, fontSize: 13.0, ), ), ], )) : WorldwidePanel( worldData: worldData!, ), Padding( padding: const EdgeInsets.symmetric(horizontal: 10.0), child: Text( 'Most affected Countries', style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold), ), ), SizedBox( height: 10, ), countryData == null ? Container() : MostAffectedPanel( countryData: countryData!, ), InfoPanel(), SizedBox( height: 20, ), Center( child: Text( 'WE ARE TOGETHER IN THE FIGHT', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16), )), SizedBox( height: 50, ) ], )), ), ); } }
0
mirrored_repositories/Dr-Health/lib/src/screens
mirrored_repositories/Dr-Health/lib/src/screens/CoronaScreen/country_screen.dart
// @dart=2.12 // ignore_for_file: import_of_legacy_library_into_null_safe import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'dart:convert'; import 'package:dr_health/src/screens/CoronaScreen/search.dart'; class CountryPage extends StatefulWidget { @override _CountryPageState createState() => _CountryPageState(); } class _CountryPageState extends State<CountryPage> { List? countryData; fetchcountryData() async { try { http.Response response = await http.get(Uri.parse('https://corona.lmao.ninja/v3/covid-19/countries')); setState(() { countryData = json.decode(response.body); }); } catch(Ex) { debugPrint("NO INTERNET : $Ex"); } } @override void initState() { fetchcountryData(); super.initState(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( backgroundColor: Theme.of(context).primaryColor, actions: <Widget>[ IconButton(icon: Icon(Icons.search),onPressed: (){ showSearch(context: context, delegate: Search(countryData)); },) ], title: Text('Country Stats'), ), // ignore: unnecessary_null_comparison body: countryData == null ? Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ CircularProgressIndicator(), SizedBox(height: 5), Text( "Loading...", ), SizedBox(height: 3), Text( "(Internet is required...)", style: TextStyle( color: Colors.redAccent, ), ), ], ), ) : ListView.builder( itemBuilder: (context, index) { return Card( child: Container( height: 130, margin: EdgeInsets.symmetric(horizontal: 10, vertical: 10), child: Row( children: <Widget>[ Container( width: 200, margin: EdgeInsets.symmetric(horizontal: 10), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( countryData![index]['country'], style: TextStyle(fontWeight: FontWeight.bold), ), Image.network( countryData![index]['countryInfo']['flag'], height: 50, width: 60, ), ], ), ), Expanded( child: Container( child: Column( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ Text( 'CONFIRMED:' + countryData![index]['cases'].toString(), style: TextStyle( fontWeight: FontWeight.bold, color: Colors.red), ), Text( 'ACTIVE:' + countryData![index]['active'].toString(), style: TextStyle( fontWeight: FontWeight.bold, color: Colors.blue), ), Text( 'RECOVERED:' + countryData![index]['recovered'].toString(), style: TextStyle( fontWeight: FontWeight.bold, color: Colors.green), ), Text( 'DEATHS:' + countryData![index]['deaths'].toString(), style: TextStyle( fontWeight: FontWeight.bold, color: Theme.of(context).brightness==Brightness.dark?Colors.grey[100]:Colors.grey[900]), ), ], ), )) ], ), ), ); }, // ignore: unnecessary_null_comparison itemCount: countryData! == null ? 0 : countryData!.length, ), ); } }
0
mirrored_repositories/Dr-Health/lib/src/screens
mirrored_repositories/Dr-Health/lib/src/screens/CoronaScreen/search.dart
// @dart=1.12 import 'package:flutter/material.dart'; class Search extends SearchDelegate{ final List countryList; Search(this.countryList); @override List<Widget> buildActions(BuildContext context) { return [ IconButton(icon: Icon(Icons.clear), onPressed: (){ query=''; }) ]; } @override Widget buildLeading(BuildContext context) { return IconButton(icon: Icon(Icons.arrow_back_ios),onPressed: (){ Navigator.pop(context); },); } @override Widget buildResults(BuildContext context) { return Container(); } @override Widget buildSuggestions(BuildContext context) { try { final suggestionList = query.isEmpty? countryList: countryList.where((element) => element['country'].toString().toLowerCase().startsWith(query)).toList(); try { return ListView.builder( itemCount: suggestionList.length, itemBuilder: (context, index) { return Card( child: Container( height: 130, margin: EdgeInsets.symmetric(horizontal: 10, vertical: 10), child: Row( children: <Widget>[ Container( width: 100, margin: EdgeInsets.symmetric(horizontal: 10), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( suggestionList[index]['country'], style: TextStyle(fontWeight: FontWeight.bold), ), Image.network( suggestionList[index]['countryInfo']['flag'], height: 50, width: 60, ), ], ), ), Expanded( child: Container( child: Column( children: <Widget>[ Text( 'CONFIRMED:' + suggestionList[index]['cases'].toString(), style: TextStyle( fontWeight: FontWeight.bold, color: Colors.red), ), Text( 'ACTIVE:' + suggestionList[index]['active'].toString(), style: TextStyle( fontWeight: FontWeight.bold, color: Colors.blue), ), Text( 'RECOVERED:' + suggestionList[index]['recovered'].toString(), style: TextStyle( fontWeight: FontWeight.bold, color: Colors.green), ), Text( 'DEATHS:' + suggestionList[index]['deaths'].toString(), style: TextStyle( fontWeight: FontWeight.bold, color: Theme.of(context).brightness==Brightness.dark?Colors.grey[100]:Colors.grey[900]), ), ], ), )) ], ), ), ); }); } catch(Ex) { return Center( child: new Text( "There is currently nothing to show", ), ); } } catch(Ex) { return Center( child: new Text( "There is currently nothing to show", ), ); } } }
0
mirrored_repositories/Dr-Health/lib/src/screens
mirrored_repositories/Dr-Health/lib/src/screens/CoronaScreen/faqs.dart
// @dart=2.12 // ignore_for_file: import_of_legacy_library_into_null_safe import 'package:flutter/material.dart'; import 'package:dr_health/src/handlers/datasource_handler.dart'; class FAQPage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('FAQs'), ), body: ListView.builder( itemCount: DataSource.questionAnswers.length, itemBuilder: (context, index) { return ExpansionTile( title: Text( DataSource.questionAnswers[index]['question'], style: TextStyle(fontWeight: FontWeight.bold), ), children: <Widget>[ Padding( padding: const EdgeInsets.all(12.0), child: Text(DataSource.questionAnswers[index]['answer']), ) ], ); }), ); } }
0
mirrored_repositories/Dr-Health/lib/src/screens
mirrored_repositories/Dr-Health/lib/src/screens/MedicineScreen/add_new_medicine.dart
import 'dart:math'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_local_notifications/flutter_local_notifications.dart'; import 'package:intl/intl.dart'; import 'package:dr_health/src/database/repository.dart'; import 'package:dr_health/src/helpers/snack_bar.dart'; import 'package:dr_health/src/models/medicine_type.dart'; import 'package:dr_health/src/models/pill.dart'; import 'package:dr_health/src/handlers/notifications_handler.dart'; import 'package:dr_health/src/helpers/platform_flat_button.dart'; import 'package:dr_health/src/components/Medicine/medicine_form_fields.dart'; import 'package:dr_health/src/components/cards/medicine_type_card.dart'; import 'package:timezone/data/latest.dart' as tz; import 'package:timezone/timezone.dart' as tz; class AddNewMedicine extends StatefulWidget { @override _AddNewMedicineState createState() => _AddNewMedicineState(); } class _AddNewMedicineState extends State<AddNewMedicine> { FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin; final _scaffoldKey = GlobalKey<ScaffoldState>(); final Snackbar snackbar = Snackbar(); //medicine types final List<String> weightValues = ["pills", "ml", "mg"]; //list of medicines forms objects final List<MedicineType> medicineTypes = [ MedicineType("Syrup", Image.asset("assets/images/syrup.png"), true), MedicineType("Pill", Image.asset("assets/images/pills.png"), false), MedicineType("Capsule", Image.asset("assets/images/capsule.png"), false), MedicineType("Cream", Image.asset("assets/images/cream.png"), false), MedicineType("Drops", Image.asset("assets/images/drops.png"), false), MedicineType("Syringe", Image.asset("assets/images/syringe.png"), false), ]; //-------------Pill object------------------ // int howManyWeeks = 1; String selectWeight; DateTime setDate = DateTime.now(); final TextEditingController nameController = TextEditingController(); final TextEditingController descriptionController = TextEditingController(); final TextEditingController amountController = TextEditingController(); //========================================== //-------------- Database and notifications ------------------ final Repository _repository = Repository(); final Notifications _notifications = Notifications(); //============================================================ @override void initState() { super.initState(); selectWeight = weightValues[0]; initNotifies(); } //init notifications Future initNotifies() async => flutterLocalNotificationsPlugin = await _notifications.initNotifies(context); @override Widget build(BuildContext context) { final deviceHeight = MediaQuery.of(context).size.height - 60.0; return Scaffold( key: _scaffoldKey, resizeToAvoidBottomInset: false, backgroundColor: Color.fromRGBO(248, 248, 248, 1), appBar: AppBar( backgroundColor: Theme.of(context).primaryColor, title: Text("Add Reminder"), ), body: SafeArea( child: Padding( padding: const EdgeInsets.only( left: 20.0, right: 20.0, top: 30.0, bottom: 30.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( height: deviceHeight * 0.35, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 5.0), child: FormFields( // howManyWeeks, nameController, descriptionController, amountController, selectWeight, popUpMenuItemChanged, // sliderChanged, ), ), ), Container( height: deviceHeight * 0.035, child: Padding( padding: const EdgeInsets.only(left: 16.0), child: FittedBox( child: Text( "Medicine form", style: TextStyle( color: Colors.grey[800], fontSize: 18.0, fontWeight: FontWeight.w600), ), ), ), ), SizedBox( height: deviceHeight * 0.02, ), Container( height: 100, child: ListView( shrinkWrap: true, scrollDirection: Axis.horizontal, children: <Widget>[ ...medicineTypes.map( (type) => MedicineTypeCard(type, medicineTypeClick)) ], ), ), SizedBox( height: deviceHeight * 0.03, ), Container( width: double.infinity, height: deviceHeight * 0.1, child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Expanded( child: Container( height: double.infinity, child: PlatformFlatButton( handler: () => openTimePicker(), buttonChild: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox(width: 10), Text( DateFormat.Hm().format(this.setDate), style: TextStyle( fontSize: 32.0, color: Colors.black, fontWeight: FontWeight.w500), ), SizedBox(width: 5), Flexible( child: Icon( Icons.access_time, size: 30, color: Theme.of(context).primaryColor, ), ) ], ), color: Color.fromRGBO(7, 190, 200, 0.1), ), ), ), SizedBox( width: 20, ), Expanded( child: Container( height: double.infinity, child: PlatformFlatButton( handler: () => openDatePicker(), buttonChild: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox(width: 10), Text( DateFormat("dd.MM").format(this.setDate), style: TextStyle( fontSize: 32.0, color: Colors.black, fontWeight: FontWeight.w500), ), SizedBox(width: 10), Flexible( child: Icon( Icons.event, size: 30, color: Theme.of(context).primaryColor, ), ) ], ), color: Color.fromRGBO(7, 190, 200, 0.1), ), ), ), ], ), ), SizedBox( height: 22.0, ), Flexible( flex: 2, child: Container( height: deviceHeight * 0.09, width: double.infinity, child: Flexible( child: PlatformFlatButton( handler: () async => savePill(), color: Theme.of(context).primaryColor, buttonChild: Text( "Add My Reminder", style: TextStyle( color: Colors.white, fontWeight: FontWeight.w600, fontSize: 17.0), ), ), ), ), ), ], ), ), ), ); } //slider changer // void sliderChanged(double value) => // setState(() => this.howManyWeeks = value.round()); //choose popum menu item void popUpMenuItemChanged(String value) => setState(() => this.selectWeight = value); //------------------------OPEN TIME PICKER (SHOW)---------------------------- //------------------------CHANGE CHOOSE PILL TIME---------------------------- Future<void> openTimePicker() async { await showTimePicker( context: context, initialTime: TimeOfDay.now(), helpText: "Choose Time", confirmText: "Set Time", ).then((value) { DateTime newDate = DateTime( setDate.year, setDate.month, setDate.day, value != null ? value.hour : setDate.hour, value != null ? value.minute : setDate.minute); setState(() => setDate = newDate); print(newDate.hour); print(newDate.minute); }); } //==================================================================== //-------------------------SHOW DATE PICKER AND CHANGE CURRENT CHOOSE DATE------------------------------- Future<void> openDatePicker() async { await showDatePicker( context: context, initialDate: setDate, confirmText: "Set Date", helpText: "Choose Time", firstDate: DateTime.now(), lastDate: DateTime.now().add(Duration(days: 100000), ), ).then((value) { DateTime newDate = DateTime( value != null ? value.year : setDate.year, value != null ? value.month : setDate.month, value != null ? value.day : setDate.day, setDate.hour, setDate.minute); setState(() => setDate = newDate); print(setDate.day); print(setDate.month); print(setDate.year); }); } //======================================================================================================= //--------------------------------------SAVE PILL IN DATABASE--------------------------------------- Future savePill() async { //check if medicine name, description and amount is set if (nameController.text.isEmpty) { snackbar.showSnack( "Medicine name is required", _scaffoldKey, null); } else if(descriptionController.text.isEmpty) { snackbar.showSnack( "Medicine description is required", _scaffoldKey, null); } else if(amountController.text.isEmpty) { snackbar.showSnack( "Please provide dosage amount", _scaffoldKey, null); } //check if medicine time is lower than actual time else if (setDate.millisecondsSinceEpoch <= DateTime.now().millisecondsSinceEpoch) { snackbar.showSnack( "Check your medicine time and date", _scaffoldKey, null); } else { //create pill object Pill pill = Pill( amount: amountController.text, // howManyWeeks: howManyWeeks, medicineForm: medicineTypes[medicineTypes .indexWhere((element) => element.isChoose == true)] .name, name: nameController.text, description: descriptionController.text, time: setDate.millisecondsSinceEpoch, type: selectWeight, notifyId: Random().nextInt(10000000)); //---------------------| Save as many medicines as many user checks |---------------------- for (int i = 0; i < 1; i++) { dynamic result = await _repository.insertData("Pills", pill.pillToMap()); if (result == null) { snackbar.showSnack("Something went wrong", _scaffoldKey, null); return; } else { //set the notification schedule tz.initializeTimeZones(); tz.setLocalLocation(tz.getLocation('Africa/Nairobi')); await _notifications.showNotification( pill.name, pill.description + "\n" + pill.amount + ". " + pill.medicineForm + "Type: " + pill.type, time, pill.notifyId, flutterLocalNotificationsPlugin); setDate = setDate.add(Duration(milliseconds: 604800000)); pill.time = setDate.millisecondsSinceEpoch; pill.notifyId = Random().nextInt(10000000); } } //--------------------------------------------------------------------------------------- snackbar.showSnack("Saved", _scaffoldKey, null); // Navigator.pushReplacementNamed(context, "/home"); Navigator.pop(context); } } //================================================================================================= //----------------------------CLICK ON MEDICINE FORM CONTAINER---------------------------------------- void medicineTypeClick(MedicineType medicine) { setState(() { medicineTypes.forEach((medicineType) => medicineType.isChoose = false); medicineTypes[medicineTypes.indexOf(medicine)].isChoose = true; }); } //===================================================================================================== //get time difference int get time => setDate.millisecondsSinceEpoch - tz.TZDateTime.now(tz.local).millisecondsSinceEpoch; }
0
mirrored_repositories/Number_trivia_tdd
mirrored_repositories/Number_trivia_tdd/lib/main.dart
import 'package:flutter/material.dart'; import './features/number_trivia/presentation/pages/number_trivia_page.dart'; import './injection_container.dart' as injection; void main() async { WidgetsFlutterBinding.ensureInitialized(); await injection.init(); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) => MaterialApp( title: 'Number Trivia', debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.green, ), home: const NumberTriviaPage(), ); }
0
mirrored_repositories/Number_trivia_tdd
mirrored_repositories/Number_trivia_tdd/lib/injection_container.dart
import 'package:get_it/get_it.dart'; import 'package:http/http.dart' as http; import 'package:internet_connection_checker/internet_connection_checker.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'core/network/network_info.dart'; import 'core/util/input_converter.dart'; import 'features/number_trivia/data/datasources/number_trivia_local_data_source.dart'; import 'features/number_trivia/data/datasources/number_trivia_remote_data_source.dart'; import 'features/number_trivia/data/repositories/number_trivia_repository_impl.dart'; import 'features/number_trivia/domain/repositories/number_trivia_repository.dart'; import 'features/number_trivia/domain/usecases/get_concrete_number_trivia.dart'; import 'features/number_trivia/domain/usecases/get_random_number_trivia.dart'; import 'features/number_trivia/presentation/bloc/number_trivia_bloc.dart'; //* service locator final sl = GetIt.instance; Future<void> init() async { //! Features - NumberTrivia // Bloc sl.registerFactory(() => NumberTriviaBloc( getConcreteNumberTrivia: sl(), getRandomNumberTrivia: sl(), inputConverter: sl(), )); // Use cases sl.registerLazySingleton(() => GetConcreteNumberTrivia(sl())); sl.registerLazySingleton(() => GetRandomNumberTrivia(sl())); // Repository sl.registerLazySingleton<NumberTriviaRepository>( () => NumberTriviaRepositoryImpl( remoteDataSource: sl(), localDataSource: sl(), networkInfo: sl(), )); // Data sources sl.registerLazySingleton<NumberTriviaRemoteDataSource>( () => NumberTriviaRemoteDataSourceImpl(client: sl())); sl.registerLazySingleton<NumberTriviaLocalDataSource>( () => NumberTriviaLocalDataSourceImpl(sharedPreferences: sl())); //! Core sl.registerLazySingleton(InputConverter.new); sl.registerLazySingleton<NetworkInfo>(() => NetworkInfoImpl(sl())); //! External final sharedPreferences = await SharedPreferences.getInstance(); sl.registerLazySingleton(() => sharedPreferences); sl.registerLazySingleton(http.Client.new); sl.registerLazySingleton(InternetConnectionChecker.new); }
0
mirrored_repositories/Number_trivia_tdd/lib/features/number_trivia/data
mirrored_repositories/Number_trivia_tdd/lib/features/number_trivia/data/models/number_trivia_model.dart
import '../../domain/entities/number_trivia.dart'; class NumberTriviaModel extends NumberTrivia { const NumberTriviaModel({required String text, required int number}) : super(text: text, number: number); factory NumberTriviaModel.fromJson(Map<String, dynamic> json) => NumberTriviaModel( text: json['text'], number: (json['number']).toInt(), ); Map<String, dynamic> toJson() => {'text': text, 'number': number}; }
0
mirrored_repositories/Number_trivia_tdd/lib/features/number_trivia/data
mirrored_repositories/Number_trivia_tdd/lib/features/number_trivia/data/datasources/number_trivia_remote_data_source.dart
import 'dart:convert'; import 'package:http/http.dart' as http; import '../../../../core/error/exceptions.dart'; import '../models/number_trivia_model.dart'; abstract class NumberTriviaRemoteDataSource { /// Calls the http://numbersapi.com/{number} endpoint. /// /// Throws a [ServerException] for all error codes. Future<NumberTriviaModel>? getConcreteNumberTrivia(int? number); /// Calls the http://numbersapi.com/random endpoint. /// /// Throws a [ServerException] for all error codes. Future<NumberTriviaModel>? getRandomNumberTrivia(); } class NumberTriviaRemoteDataSourceImpl implements NumberTriviaRemoteDataSource { final http.Client client; NumberTriviaRemoteDataSourceImpl({required this.client}); @override Future<NumberTriviaModel>? getConcreteNumberTrivia(int? number) => _getTriviaFromUrl('http://www.numbersapi.com/$number'); @override Future<NumberTriviaModel>? getRandomNumberTrivia() => _getTriviaFromUrl('http://www.numbersapi.com/random'); Future<NumberTriviaModel> _getTriviaFromUrl(String url) async { final response = await client .get(Uri.parse(url), headers: {'Content-Type': 'application/json'}); if (response.statusCode == 200) { return NumberTriviaModel.fromJson(json.decode(response.body)); } else { throw ServerException(); } } }
0
mirrored_repositories/Number_trivia_tdd/lib/features/number_trivia/data
mirrored_repositories/Number_trivia_tdd/lib/features/number_trivia/data/datasources/number_trivia_local_data_source.dart
import 'dart:convert'; import 'package:shared_preferences/shared_preferences.dart'; import '../../../../core/error/exceptions.dart'; import '../models/number_trivia_model.dart'; abstract class NumberTriviaLocalDataSource { /// Gets the cached [NumberTriviaModel] which was gotten the last time /// the user had an internet connection. /// /// Throws [CacheException] if no cached data is present. Future<NumberTriviaModel>? getLastNumberTrivia(); Future<void>? cacheNumberTrivia(NumberTriviaModel triviaToCache); } const cachedNumberTrivia = 'CACHED_NUMBER_TRIVIA'; class NumberTriviaLocalDataSourceImpl implements NumberTriviaLocalDataSource { final SharedPreferences sharedPreferences; NumberTriviaLocalDataSourceImpl({required this.sharedPreferences}); @override Future<NumberTriviaModel>? getLastNumberTrivia() { final jsonString = sharedPreferences.getString(cachedNumberTrivia); if (jsonString != null) { return Future.value(NumberTriviaModel.fromJson(json.decode(jsonString))); } else { throw CacheException(); } } @override Future<void>? cacheNumberTrivia(NumberTriviaModel triviaToCache) => sharedPreferences.setString( cachedNumberTrivia, json.encode(triviaToCache.toJson())); }
0
mirrored_repositories/Number_trivia_tdd/lib/features/number_trivia/data
mirrored_repositories/Number_trivia_tdd/lib/features/number_trivia/data/repositories/number_trivia_repository_impl.dart
import 'package:dartz/dartz.dart'; import '../../../../core/error/exceptions.dart'; import '../../../../core/error/failures.dart'; import '../../../../core/network/network_info.dart'; import '../../domain/entities/number_trivia.dart'; import '../../domain/repositories/number_trivia_repository.dart'; import '../datasources/number_trivia_local_data_source.dart'; import '../datasources/number_trivia_remote_data_source.dart'; import '../models/number_trivia_model.dart'; typedef ConcreteOrRandomChooser = Future<NumberTriviaModel> Function(); class NumberTriviaRepositoryImpl implements NumberTriviaRepository { final NumberTriviaRemoteDataSource remoteDataSource; final NumberTriviaLocalDataSource localDataSource; final NetworkInfo networkInfo; NumberTriviaRepositoryImpl({ required this.remoteDataSource, required this.localDataSource, required this.networkInfo, }); @override Future<Either<Failure, NumberTrivia>> getConcreteNumberTrivia( int number) async => await _getTrivia(() => remoteDataSource.getConcreteNumberTrivia(number)!); @override Future<Either<Failure, NumberTrivia>> getRandomNumberTrivia() async => await _getTrivia(() => remoteDataSource.getRandomNumberTrivia()!); Future<Either<Failure, NumberTrivia>> _getTrivia( ConcreteOrRandomChooser getConcreteOrRandom) async { if (await networkInfo.isConnected) { try { final remoteTrivia = await getConcreteOrRandom(); await localDataSource.cacheNumberTrivia(remoteTrivia); return Right(remoteTrivia); } on ServerException { return Left(ServerFailure()); } } else { try { final localTrivia = await localDataSource.getLastNumberTrivia(); return Right(localTrivia!); } on CacheException { return Left(CacheFailure()); } } } }
0
mirrored_repositories/Number_trivia_tdd/lib/features/number_trivia/presentation
mirrored_repositories/Number_trivia_tdd/lib/features/number_trivia/presentation/widgets/trivia_controls.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import '../bloc/number_trivia_bloc.dart'; class TriviaControls extends StatefulWidget { const TriviaControls({Key? key}) : super(key: key); @override State<TriviaControls> createState() => _TriviaControlsState(); } class _TriviaControlsState extends State<TriviaControls> { final controller = TextEditingController(); String inputStr = ''; @override void dispose() { super.dispose(); controller.dispose(); } @override Widget build(BuildContext context) => Column( children: [ TextField( controller: controller, keyboardType: TextInputType.number, decoration: InputDecoration( border: const OutlineInputBorder(), hintText: 'Input a number', enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.green.shade600, width: 1.0), borderRadius: const BorderRadius.all( Radius.circular(10), ), ), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.green.shade600, width: 2.0), borderRadius: const BorderRadius.all( Radius.circular(10), ), ), errorBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.red.shade600, width: 2.0), borderRadius: const BorderRadius.all( Radius.circular(10), ), ), ), onChanged: (value) { inputStr = value; }, onSubmitted: (_) { addConcrete(); }, ), const SizedBox(height: 10), Row( children: [ Expanded( child: ElevatedButton( child: const Text('Search'), style: ElevatedButton.styleFrom( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), ), onPressed: addConcrete, ), ), const SizedBox(width: 10), Expanded( child: ElevatedButton( style: ElevatedButton.styleFrom( primary: Colors.grey.shade500, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), ), child: const Text('Get random trivia'), onPressed: addRandom, ), ), ], ) ], ); void addConcrete() { controller.clear(); context.read<NumberTriviaBloc>().add(GetTriviaForConcreteNumber(inputStr)); // BlocProvider.of<NumberTriviaBloc>(context) // .add(GetTriviaForConcreteNumber(inputStr)); inputStr = ''; } void addRandom() { controller.clear(); context.read<NumberTriviaBloc>().add(GetTriviaForRandomNumber()); inputStr = ''; } }
0