repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/Tegnordbok/lib
mirrored_repositories/Tegnordbok/lib/screens/search_screen.dart
import "package:flutter/material.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; import "package:tegnordbok/fetch.dart"; import "package:tegnordbok/models.dart"; import "package:tegnordbok/screens/player_screen.dart"; import "package:tegnordbok/screens/settings_screen.dart"; import "package:tegnordbok/widgets/loader.dart"; import "package:text_search/text_search.dart"; import "navigation.dart"; final searchControllerProvider = Provider((_) => TextEditingController()); final searchFocusProvider = Provider((_) => FocusNode()); final queryProvider = StateProvider((_) => ""); class SearchScreen extends ConsumerWidget { const SearchScreen({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { final searchController = ref.read(searchControllerProvider); final searchFocusNode = ref.read(searchFocusProvider); void onChange(String text) => ref.read(queryProvider.notifier).state = text; return Scaffold( resizeToAvoidBottomInset: false, appBar: AppBar( scrolledUnderElevation: 0, title: TextField( controller: searchController, focusNode: searchFocusNode, onChanged: onChange, autofocus: false, decoration: InputDecoration( prefixIcon: const Icon(Icons.search), border: InputBorder.none, hintText: "Søk...", suffixIcon: IconButton( icon: const Icon(Icons.clear), onPressed: () { searchFocusNode.requestFocus(); searchController.clear(); onChange(""); }, tooltip: "Tøm", )), ), actions: [ IconButton( onPressed: pushScreen(context, const SettingsScreen()), icon: const Icon(Icons.settings), tooltip: "Innstillinger", ), ], ), body: const LoaderWidget( onLoad: fetchAllWords, handler: WordListWidget.new, ), ); } } final wordListScrollControllerProvider = Provider((_) => ScrollController()); class WordListWidget extends ConsumerWidget { const WordListWidget(this.words, {super.key}); final List<Word> words; @override Widget build(BuildContext context, WidgetRef ref) { final query = ref.watch(queryProvider); final results = _search(query, words); final scrollController = ref.read(wordListScrollControllerProvider); if (scrollController.hasClients) { scrollController.jumpTo(0); } return ListView.builder( controller: scrollController, itemCount: results.length, itemBuilder: (_, index) => WordItem(word: results[index]), ); } } class WordItem extends StatelessWidget { const WordItem({super.key, required this.word}); final Word word; @override Widget build(BuildContext context) { return ListTile( title: Text(word.word), onTap: pushScreen(context, PlayerScreen(word)), ); } } List<Word> _search(String query, List<Word> words) { if (query.trim().isEmpty) { return words; } final textSearchItems = words .map((word) => TextSearchItem.fromTerms(word, word.word.split(" "))) .toList(); return TextSearch(textSearchItems).fastSearch(query, matchThreshold: 0.4); }
0
mirrored_repositories/Tegnordbok/lib
mirrored_repositories/Tegnordbok/lib/screens/player_screen.dart
import "package:flutter/material.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; import "package:tegnordbok/models.dart"; import "package:tegnordbok/screens/example_screen.dart"; import "package:tegnordbok/screens/navigation.dart"; import "package:tegnordbok/widgets/player.dart"; class PlayerScreen extends ConsumerWidget { const PlayerScreen(this.word, {super.key}); final Word word; @override Widget build(BuildContext context, WidgetRef ref) { return Scaffold( appBar: AppBar( title: Text(word.word), ), body: SingleChildScrollView( child: Column( children: [ PlayerWidget(word.stream.getUrl), if (word.comment != null) Padding( padding: const EdgeInsets.symmetric(horizontal: 20), child: Card( child: Padding( padding: const EdgeInsets.all(14), child: Text(word.comment!), )), ), if (word.examples.isNotEmpty) ...word.examples .asMap() .entries .map((entry) => ElevatedButton( onPressed: pushScreen( context, ExampleScreen(entry.value, entry.key + 1)), child: Text("Eksempel ${entry.key + 1}"))) .toList(), ], ), ), ); } }
0
mirrored_repositories/Tegnordbok/lib
mirrored_repositories/Tegnordbok/lib/screens/navigation.dart
import "package:flutter/material.dart"; void Function() pushScreen(BuildContext context, Widget screen) => () => Navigator.of(context).push(MaterialPageRoute(builder: (_) => screen));
0
mirrored_repositories/Tegnordbok
mirrored_repositories/Tegnordbok/test/fetch_test.dart
import "package:flutter_test/flutter_test.dart"; import "package:tegnordbok/fetch.dart"; void main() { test("word", () async { final allWords = await fetchAllWords(); final word = allWords.first; expect(word.word, "0"); }); }
0
mirrored_repositories/Tegnordbok
mirrored_repositories/Tegnordbok/test/piped_test.dart
import "package:flutter_test/flutter_test.dart"; import "package:tegnordbok/piped.dart"; void main() { test("OXbn6kVS4C0", () async { expect(await Piped.main.getStreamUrl("OXbn6kVS4C0"), contains("https://pipedproxy")); }); }
0
mirrored_repositories/find_anime
mirrored_repositories/find_anime/lib/runner_io.dart
import 'package:flutter/material.dart'; import 'package:intl/intl_standalone.dart'; import 'src/core/widget/app.dart'; // starting app in io mode Future<void> run() async { await findSystemLocale(); // find device language runApp(FindAnimeApp()); }
0
mirrored_repositories/find_anime
mirrored_repositories/find_anime/lib/runner_stub.dart
void run() => throw UnsupportedError('Unknown host platform');
0
mirrored_repositories/find_anime
mirrored_repositories/find_anime/lib/main.dart
import 'dart:async'; import 'package:bloc_concurrency/bloc_concurrency.dart' as bloc_concurrency; import 'package:flutter/foundation.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'runner_stub.dart' if (dart.library.io) 'runner_io.dart' if (dart.library.html) 'runner_web.dart' as runner; import 'src/core/bloc/app_observer.dart'; Future<void> main() async { runZonedGuarded( () { Bloc.observer = AppObserver.instance(); Bloc.transformer = bloc_concurrency.sequential<Object?>(); runner.run(); }, (error, stack) { debugPrint('Error: $error\n\nStacktrace: $stack'); }, ); }
0
mirrored_repositories/find_anime
mirrored_repositories/find_anime/lib/runner_web.dart
import 'package:flutter/material.dart'; import 'package:intl/intl_browser.dart'; import 'package:url_strategy/url_strategy.dart'; import 'src/core/widget/app.dart'; // starting app in web mode Future<void> run() async { setPathUrlStrategy(); // remove "#" from url await findSystemLocale(); // find language for web platform runApp(FindAnimeApp()); }
0
mirrored_repositories/find_anime/lib/src/core
mirrored_repositories/find_anime/lib/src/core/router/app_router.dart
import 'package:beamer/beamer.dart'; import '../../feature/search/search.dart'; class AppRouter { static final beamerParser = BeamerParser(); static final beamerDelegate = BeamerDelegate( locationBuilder: RoutesLocationBuilder(routes: { '/': (context, state, data) => const BeamPage( title: 'Search', child: SearchScreen(), ), }), ); }
0
mirrored_repositories/find_anime/lib/src/core
mirrored_repositories/find_anime/lib/src/core/bloc/app_observer.dart
import 'package:flutter/foundation.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class AppObserver extends BlocObserver { static AppObserver? _singleton; factory AppObserver.instance() => _singleton ??= AppObserver._(); AppObserver._(); @override void onChange(BlocBase bloc, Change change) { super.onChange(bloc, change); debugPrint('Bloc change: \n$change'); } @override void onTransition(Bloc bloc, Transition transition) { debugPrint('Bloc transition:\n $transition'); super.onTransition(bloc, transition); } @override void onError(BlocBase bloc, Object error, StackTrace stackTrace) { debugPrint('Error:$error\n\nStackTrace: $stackTrace'); super.onError(bloc, error, stackTrace); } }
0
mirrored_repositories/find_anime/lib/src/core
mirrored_repositories/find_anime/lib/src/core/theme/theme.dart
// ignore_for_file: unused_local_variable import 'package:flutter/material.dart'; const FontWeight thin = FontWeight.w100; const FontWeight extraLight = FontWeight.w200; const FontWeight light = FontWeight.w300; const FontWeight regular = FontWeight.w400; const FontWeight medium = FontWeight.w500; const FontWeight semiBold = FontWeight.w600; const FontWeight bold = FontWeight.w700; const FontWeight extraBold = FontWeight.w800; const FontWeight black = FontWeight.w900; ThemeData themeData() { //light theme const backgroundColor = Color(0xFFE8E8E8); const firstLevelColor = Color(0xFFF5F5F5); const secondLevelColor = Color(0xFFFFFFFF); const accentColor = Color(0xFF133676); const highContrast = Colors.black87; const mediumContrast = Color(0x99000000); const lowContrast = Colors.black38; return ThemeData( navigationBarTheme: NavigationBarThemeData( backgroundColor: secondLevelColor, height: 65, indicatorColor: accentColor, labelTextStyle: MaterialStateProperty.all(const TextStyle( fontFamily: 'Montserrat', fontWeight: semiBold, fontSize: 12, color: accentColor, overflow: TextOverflow.ellipsis, )), iconTheme: MaterialStateProperty.resolveWith((states) => IconThemeData( color: states.contains(MaterialState.selected) ? secondLevelColor : highContrast, )), labelBehavior: NavigationDestinationLabelBehavior.onlyShowSelected, ), tabBarTheme: const TabBarTheme( labelColor: accentColor, unselectedLabelColor: mediumContrast, indicatorSize: TabBarIndicatorSize.label, ), appBarTheme: const AppBarTheme( elevation: 0.0, backgroundColor: backgroundColor, foregroundColor: highContrast, ), cardTheme: const CardTheme(margin: EdgeInsets.zero), pageTransitionsTheme: const PageTransitionsTheme(builders: { TargetPlatform.android: CupertinoPageTransitionsBuilder(), TargetPlatform.iOS: CupertinoPageTransitionsBuilder(), }), brightness: Brightness.light, textSelectionTheme: TextSelectionThemeData( selectionColor: accentColor.withOpacity(0.5), selectionHandleColor: accentColor, ), primaryColor: secondLevelColor, cardColor: firstLevelColor, splashColor: accentColor.withOpacity(0.2), colorScheme: const ColorScheme( primary: accentColor, secondary: accentColor, surface: secondLevelColor, background: accentColor, error: Colors.red, onPrimary: backgroundColor, onSecondary: backgroundColor, onSurface: highContrast, onBackground: highContrast, onError: backgroundColor, brightness: Brightness.light, ), dialogBackgroundColor: firstLevelColor, textTheme: const TextTheme( subtitle1: TextStyle(fontSize: 15, color: mediumContrast, fontWeight: medium), bodyText1: TextStyle(color: highContrast, fontSize: 17, fontWeight: regular), headline3: TextStyle( //News Card Title color: highContrast, fontSize: 16, fontFamily: 'Montserrat', fontWeight: medium, ), headline4: TextStyle( //Alert Card Title color: highContrast, fontSize: 17, fontFamily: 'Montserrat', fontWeight: semiBold, ), headline5: TextStyle( //used in time schedule for any time color: highContrast, fontSize: 36, fontFamily: 'Montserrat', fontWeight: semiBold, ), headline6: TextStyle( //used in time schedule for any other color: highContrast, fontSize: 18, fontFamily: 'Montserrat', fontWeight: semiBold, ), ), iconTheme: const IconThemeData( size: 24.0, ), textButtonTheme: TextButtonThemeData( style: TextButton.styleFrom( textStyle: const TextStyle(fontFamily: 'Montserrat', fontWeight: semiBold), shape: const StadiumBorder(), primary: accentColor, ), ), outlinedButtonTheme: OutlinedButtonThemeData( style: OutlinedButton.styleFrom( textStyle: const TextStyle(fontFamily: 'Montserrat', fontWeight: semiBold), shape: const StadiumBorder(), side: const BorderSide( width: 1.5, color: accentColor, ), ), ), elevatedButtonTheme: ElevatedButtonThemeData( style: ElevatedButton.styleFrom( textStyle: const TextStyle(fontFamily: 'Montserrat', fontWeight: semiBold), shape: const StadiumBorder(), primary: accentColor, onPrimary: backgroundColor, ), ), inputDecorationTheme: const InputDecorationTheme( alignLabelWithHint: true, errorStyle: TextStyle( color: Colors.red, fontFamily: 'Montserrat', fontWeight: semiBold, ), helperStyle: TextStyle(fontFamily: 'Montserrat', fontWeight: semiBold), labelStyle: TextStyle(fontFamily: 'Montserrat', fontWeight: semiBold), hintStyle: TextStyle(fontFamily: 'Montserrat', fontWeight: semiBold), contentPadding: EdgeInsets.symmetric(horizontal: 20, vertical: 15), border: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(20)), ), errorBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.red, width: 1), borderRadius: BorderRadius.all(Radius.circular(20)), ), focusedErrorBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.red, width: 1.5), borderRadius: BorderRadius.all(Radius.circular(20)), ), enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: accentColor, width: 1), borderRadius: BorderRadius.all(Radius.circular(20)), ), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: accentColor, width: 1.5), borderRadius: BorderRadius.all(Radius.circular(20)), ), ), scaffoldBackgroundColor: backgroundColor, floatingActionButtonTheme: const FloatingActionButtonThemeData( backgroundColor: secondLevelColor, foregroundColor: accentColor, ), bottomNavigationBarTheme: const BottomNavigationBarThemeData( selectedItemColor: accentColor, unselectedItemColor: mediumContrast, backgroundColor: secondLevelColor, ), bottomSheetTheme: const BottomSheetThemeData(backgroundColor: firstLevelColor), ); } ThemeData darkThemeData() { //dark theme const backgroundColor = Color(0xFF121212); const firstLevelColor = Color(0xFF1F1F1F); const secondLevelColor = Color(0xFF292929); const accentColor = Color(0xFF7B9DDB); const highContrast = Color(0xDEFFFFFF); const mediumContrast = Colors.white60; const lowContrast = Color(0x61FFFFFF); return ThemeData.dark().copyWith( navigationBarTheme: NavigationBarThemeData( backgroundColor: secondLevelColor, height: 65, indicatorColor: accentColor, labelTextStyle: MaterialStateProperty.all(const TextStyle( fontFamily: 'Montserrat', fontWeight: semiBold, fontSize: 12, color: accentColor, overflow: TextOverflow.ellipsis, )), iconTheme: MaterialStateProperty.resolveWith((states) => IconThemeData( color: states.contains(MaterialState.selected) ? secondLevelColor : highContrast, )), labelBehavior: NavigationDestinationLabelBehavior.onlyShowSelected, ), tabBarTheme: const TabBarTheme( labelColor: accentColor, unselectedLabelColor: mediumContrast, indicatorSize: TabBarIndicatorSize.label, ), appBarTheme: const AppBarTheme( elevation: 0.0, backgroundColor: backgroundColor, foregroundColor: highContrast, ), cardTheme: const CardTheme(margin: EdgeInsets.zero), pageTransitionsTheme: const PageTransitionsTheme(builders: { TargetPlatform.android: CupertinoPageTransitionsBuilder(), TargetPlatform.iOS: CupertinoPageTransitionsBuilder(), }), brightness: Brightness.dark, textSelectionTheme: TextSelectionThemeData( selectionColor: accentColor.withOpacity(0.5), selectionHandleColor: accentColor, ), primaryColor: secondLevelColor, cardColor: firstLevelColor, splashColor: accentColor.withOpacity(0.2), colorScheme: const ColorScheme( primary: accentColor, secondary: accentColor, surface: secondLevelColor, background: backgroundColor, error: Colors.redAccent, onPrimary: backgroundColor, onSecondary: backgroundColor, onSurface: highContrast, onBackground: highContrast, onError: backgroundColor, brightness: Brightness.dark, ), dialogBackgroundColor: firstLevelColor, textTheme: const TextTheme( subtitle1: TextStyle(fontSize: 15, color: mediumContrast, fontWeight: medium), bodyText1: TextStyle(color: highContrast, fontSize: 17, fontWeight: regular), headline3: TextStyle( //News Card Title color: highContrast, fontSize: 16, fontFamily: 'Montserrat', fontWeight: medium, ), headline4: TextStyle( //Alert Card Title color: highContrast, fontSize: 17, fontFamily: 'Montserrat', fontWeight: semiBold, ), headline5: TextStyle( //used in time schedule for any time color: highContrast, fontSize: 36, fontFamily: 'Montserrat', fontWeight: semiBold, ), headline6: TextStyle( //used in time schedule for any other color: highContrast, fontSize: 18, fontFamily: 'Montserrat', fontWeight: semiBold, ), ), iconTheme: const IconThemeData( size: 24.0, ), textButtonTheme: TextButtonThemeData( style: TextButton.styleFrom( textStyle: const TextStyle(fontFamily: 'Montserrat', fontWeight: semiBold), shape: const StadiumBorder(), primary: accentColor, ), ), outlinedButtonTheme: OutlinedButtonThemeData( style: OutlinedButton.styleFrom( textStyle: const TextStyle(fontFamily: 'Montserrat', fontWeight: semiBold), shape: const StadiumBorder(), side: const BorderSide( width: 1.5, color: accentColor, ), ), ), elevatedButtonTheme: ElevatedButtonThemeData( style: ElevatedButton.styleFrom( textStyle: const TextStyle(fontFamily: 'Montserrat', fontWeight: semiBold), shape: const StadiumBorder(), primary: accentColor, onPrimary: backgroundColor, ), ), inputDecorationTheme: const InputDecorationTheme( alignLabelWithHint: true, errorStyle: TextStyle( color: Colors.redAccent, fontFamily: 'Montserrat', fontWeight: semiBold, ), helperStyle: TextStyle(fontFamily: 'Montserrat', fontWeight: semiBold), labelStyle: TextStyle(fontFamily: 'Montserrat', fontWeight: semiBold), hintStyle: TextStyle(fontFamily: 'Montserrat', fontWeight: semiBold), contentPadding: EdgeInsets.symmetric(horizontal: 20, vertical: 15), border: OutlineInputBorder( borderRadius: BorderRadius.all(Radius.circular(20)), ), errorBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.redAccent, width: 1), borderRadius: BorderRadius.all(Radius.circular(20)), ), focusedErrorBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.redAccent, width: 1.5), borderRadius: BorderRadius.all(Radius.circular(20)), ), enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: accentColor, width: 1), borderRadius: BorderRadius.all(Radius.circular(20)), ), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: accentColor, width: 1.5), borderRadius: BorderRadius.all(Radius.circular(20)), ), ), scaffoldBackgroundColor: backgroundColor, floatingActionButtonTheme: const FloatingActionButtonThemeData( backgroundColor: secondLevelColor, foregroundColor: accentColor, ), bottomNavigationBarTheme: const BottomNavigationBarThemeData( selectedItemColor: accentColor, unselectedItemColor: mediumContrast, backgroundColor: secondLevelColor, ), bottomSheetTheme: const BottomSheetThemeData(backgroundColor: firstLevelColor), ); }
0
mirrored_repositories/find_anime/lib/src/core/generated
mirrored_repositories/find_anime/lib/src/core/generated/localization/l10n.dart
// GENERATED CODE - DO NOT MODIFY BY HAND import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'intl/messages_all.dart'; // ************************************************************************** // Generator: Flutter Intl IDE plugin // Made by Localizely // ************************************************************************** // ignore_for_file: non_constant_identifier_names, lines_longer_than_80_chars // ignore_for_file: join_return_with_assignment, prefer_final_in_for_each // ignore_for_file: avoid_redundant_argument_values, avoid_escaping_inner_quotes class S { S(); static S? _current; static S get current { assert(_current != null, 'No instance of S was loaded. Try to initialize the S delegate before accessing S.current.'); return _current!; } static const AppLocalizationDelegate delegate = AppLocalizationDelegate(); static Future<S> load(Locale locale) { final name = (locale.countryCode?.isEmpty ?? false) ? locale.languageCode : locale.toString(); final localeName = Intl.canonicalizedLocale(name); return initializeMessages(localeName).then((_) { Intl.defaultLocale = localeName; final instance = S(); S._current = instance; return instance; }); } static S of(BuildContext context) { final instance = S.maybeOf(context); assert(instance != null, 'No instance of S present in the widget tree. Did you add S.delegate in localizationsDelegates?'); return instance!; } static S? maybeOf(BuildContext context) { return Localizations.of<S>(context, S); } /// `New search` String get newSearch { return Intl.message( 'New search', name: 'newSearch', desc: 'Title on the search page', args: [], ); } /// `Enter URL, drop file to window or select file via button` String get newSearchHint { return Intl.message( 'Enter URL, drop file to window or select file via button', name: 'newSearchHint', desc: 'Informs the user about possible search methods', args: [], ); } /// `Enter image URL` String get enterImageUrl { return Intl.message( 'Enter image URL', name: 'enterImageUrl', desc: 'Placeholder text in text form for pasting image URL', args: [], ); } /// `Link should be direct to image` String get enterImageUrlHint { return Intl.message( 'Link should be direct to image', name: 'enterImageUrlHint', desc: 'Hint text under text form for pasting image URL', args: [], ); } /// `Search` String get searchButtonText { return Intl.message( 'Search', name: 'searchButtonText', desc: 'Text on search button', args: [], ); } /// `Select file` String get selectFileButtonText { return Intl.message( 'Select file', name: 'selectFileButtonText', desc: 'Text on button for file selecting', args: [], ); } /// `Open search` String get openSearchButton { return Intl.message( 'Open search', name: 'openSearchButton', desc: 'Text on float action button that open search view', args: [], ); } /// `Copy name` String get copyNameButton { return Intl.message( 'Copy name', name: 'copyNameButton', desc: 'Text on copy name button', args: [], ); } /// `Copied!` String get copiedText { return Intl.message( 'Copied!', name: 'copiedText', desc: 'Show text with successful name copy', args: [], ); } /// `No romaji name` String get noRomajiName { return Intl.message( 'No romaji name', name: 'noRomajiName', desc: 'Indicates that there is no romaji name', args: [], ); } /// `No japanese name` String get noJapaneseName { return Intl.message( 'No japanese name', name: 'noJapaneseName', desc: 'Indicates that there is no japanese name', args: [], ); } /// `View in anilist` String get viewInAnilist { return Intl.message( 'View in anilist', name: 'viewInAnilist', desc: 'Text on view in anilist button', args: [], ); } /// `Similarity: {similarityNum}%` String similarityText(String similarityNum) { return Intl.message( 'Similarity: $similarityNum%', name: 'similarityText', desc: 'text showing the percentage of result match', args: [similarityNum], ); } /// `Episode {episodeNumber}, moment at {momentTime}` String episodeText(int episodeNumber, String momentTime) { return Intl.message( 'Episode $episodeNumber, moment at $momentTime', name: 'episodeText', desc: 'e.x: Episode 1, moment at 8m, 42s', args: [episodeNumber, momentTime], ); } /// `Adult only!` String get adultOnly { return Intl.message( 'Adult only!', name: 'adultOnly', desc: 'Indicates that this title is NSFW', args: [], ); } /// `Provided image is empty` String get error400 { return Intl.message( 'Provided image is empty', name: 'error400', desc: 'An error, indicates that provided image is empty', args: [], ); } /// `Too many requests, please try again later` String get error402 { return Intl.message( 'Too many requests, please try again later', name: 'error402', desc: 'An error, indicates too many requests by user', args: [], ); } /// `Something wrong on server` String get error500 { return Intl.message( 'Something wrong on server', name: 'error500', desc: 'An error, indicates something wrong on server', args: [], ); } /// `Search queue is full` String get error503 { return Intl.message( 'Search queue is full', name: 'error503', desc: 'An error, indicates search queue is full', args: [], ); } /// `Server is overload, try again later` String get error504 { return Intl.message( 'Server is overload, try again later', name: 'error504', desc: 'An error, indicates something wrong on server', args: [], ); } /// `Response timed out` String get errorTimeOut { return Intl.message( 'Response timed out', name: 'errorTimeOut', desc: 'response timed out error', args: [], ); } /// `Unexpected error has occurred\nError: {error}` String errorUnexpected(Object error) { return Intl.message( 'Unexpected error has occurred\nError: $error', name: 'errorUnexpected', desc: 'An error, indicates unexpected error has occurred', args: [error], ); } /// `Something went wrong` String get errorUnknown { return Intl.message( 'Something went wrong', name: 'errorUnknown', desc: 'An error, when something unknown went wrong', args: [], ); } } class AppLocalizationDelegate extends LocalizationsDelegate<S> { const AppLocalizationDelegate(); List<Locale> get supportedLocales { return const <Locale>[ Locale.fromSubtags(languageCode: 'en'), Locale.fromSubtags(languageCode: 'ru'), ]; } @override bool isSupported(Locale locale) => _isSupported(locale); @override Future<S> load(Locale locale) => S.load(locale); @override bool shouldReload(AppLocalizationDelegate old) => false; bool _isSupported(Locale locale) { for (var supportedLocale in supportedLocales) { if (supportedLocale.languageCode == locale.languageCode) { return true; } } return false; } }
0
mirrored_repositories/find_anime/lib/src/core/generated/localization
mirrored_repositories/find_anime/lib/src/core/generated/localization/intl/messages_en.dart
// DO NOT EDIT. This is code generated via package:intl/generate_localized.dart // This is a library that provides messages for a en locale. All the // messages from the main program should be duplicated here with the same // function name. // Ignore issues from commonly used lints in this file. // ignore_for_file:unnecessary_brace_in_string_interps, unnecessary_new // ignore_for_file:prefer_single_quotes,comment_references, directives_ordering // ignore_for_file:annotate_overrides,prefer_generic_function_type_aliases // ignore_for_file:unused_import, file_names, avoid_escaping_inner_quotes // ignore_for_file:unnecessary_string_interpolations, unnecessary_string_escapes import 'package:intl/intl.dart'; import 'package:intl/message_lookup_by_library.dart'; final messages = new MessageLookup(); typedef String MessageIfAbsent(String messageStr, List<dynamic> args); class MessageLookup extends MessageLookupByLibrary { String get localeName => 'en'; static String m0(episodeNumber, momentTime) => "Episode ${episodeNumber}, moment at ${momentTime}"; static String m1(error) => "Unexpected error has occurred\nError: ${error}"; static String m2(similarityNum) => "Similarity: ${similarityNum}%"; final messages = _notInlinedMessages(_notInlinedMessages); static Map<String, Function> _notInlinedMessages(_) => <String, Function>{ "adultOnly": MessageLookupByLibrary.simpleMessage("Adult only!"), "copiedText": MessageLookupByLibrary.simpleMessage("Copied!"), "copyNameButton": MessageLookupByLibrary.simpleMessage("Copy name"), "enterImageUrl": MessageLookupByLibrary.simpleMessage("Enter image URL"), "enterImageUrlHint": MessageLookupByLibrary.simpleMessage( "Link should be direct to image"), "episodeText": m0, "error400": MessageLookupByLibrary.simpleMessage("Provided image is empty"), "error402": MessageLookupByLibrary.simpleMessage( "Too many requests, please try again later"), "error500": MessageLookupByLibrary.simpleMessage("Something wrong on server"), "error503": MessageLookupByLibrary.simpleMessage("Search queue is full"), "error504": MessageLookupByLibrary.simpleMessage( "Server is overload, try again later"), "errorTimeOut": MessageLookupByLibrary.simpleMessage("Response timed out"), "errorUnexpected": m1, "errorUnknown": MessageLookupByLibrary.simpleMessage("Something went wrong"), "newSearch": MessageLookupByLibrary.simpleMessage("New search"), "newSearchHint": MessageLookupByLibrary.simpleMessage( "Enter URL, drop file to window or select file via button"), "noJapaneseName": MessageLookupByLibrary.simpleMessage("No japanese name"), "noRomajiName": MessageLookupByLibrary.simpleMessage("No romaji name"), "openSearchButton": MessageLookupByLibrary.simpleMessage("Open search"), "searchButtonText": MessageLookupByLibrary.simpleMessage("Search"), "selectFileButtonText": MessageLookupByLibrary.simpleMessage("Select file"), "similarityText": m2, "viewInAnilist": MessageLookupByLibrary.simpleMessage("View in anilist") }; }
0
mirrored_repositories/find_anime/lib/src/core/generated/localization
mirrored_repositories/find_anime/lib/src/core/generated/localization/intl/messages_all.dart
// DO NOT EDIT. This is code generated via package:intl/generate_localized.dart // This is a library that looks up messages for specific locales by // delegating to the appropriate library. // Ignore issues from commonly used lints in this file. // ignore_for_file:implementation_imports, file_names, unnecessary_new // ignore_for_file:unnecessary_brace_in_string_interps, directives_ordering // ignore_for_file:argument_type_not_assignable, invalid_assignment // ignore_for_file:prefer_single_quotes, prefer_generic_function_type_aliases // ignore_for_file:comment_references import 'dart:async'; import 'package:intl/intl.dart'; import 'package:intl/message_lookup_by_library.dart'; import 'package:intl/src/intl_helpers.dart'; import 'messages_en.dart' as messages_en; import 'messages_ru.dart' as messages_ru; typedef Future<dynamic> LibraryLoader(); Map<String, LibraryLoader> _deferredLibraries = { 'en': () => new Future.value(null), 'ru': () => new Future.value(null), }; MessageLookupByLibrary? _findExact(String localeName) { switch (localeName) { case 'en': return messages_en.messages; case 'ru': return messages_ru.messages; default: return null; } } /// User programs should call this before using [localeName] for messages. Future<bool> initializeMessages(String localeName) async { var availableLocale = Intl.verifiedLocale( localeName, (locale) => _deferredLibraries[locale] != null, onFailure: (_) => null); if (availableLocale == null) { return new Future.value(false); } var lib = _deferredLibraries[availableLocale]; await (lib == null ? new Future.value(false) : lib()); initializeInternalMessageLookup(() => new CompositeMessageLookup()); messageLookup.addLocale(availableLocale, _findGeneratedMessagesFor); return new Future.value(true); } bool _messagesExistFor(String locale) { try { return _findExact(locale) != null; } catch (e) { return false; } } MessageLookupByLibrary? _findGeneratedMessagesFor(String locale) { var actualLocale = Intl.verifiedLocale(locale, _messagesExistFor, onFailure: (_) => null); if (actualLocale == null) return null; return _findExact(actualLocale); }
0
mirrored_repositories/find_anime/lib/src/core/generated/localization
mirrored_repositories/find_anime/lib/src/core/generated/localization/intl/messages_ru.dart
// DO NOT EDIT. This is code generated via package:intl/generate_localized.dart // This is a library that provides messages for a ru locale. All the // messages from the main program should be duplicated here with the same // function name. // Ignore issues from commonly used lints in this file. // ignore_for_file:unnecessary_brace_in_string_interps, unnecessary_new // ignore_for_file:prefer_single_quotes,comment_references, directives_ordering // ignore_for_file:annotate_overrides,prefer_generic_function_type_aliases // ignore_for_file:unused_import, file_names, avoid_escaping_inner_quotes // ignore_for_file:unnecessary_string_interpolations, unnecessary_string_escapes import 'package:intl/intl.dart'; import 'package:intl/message_lookup_by_library.dart'; final messages = new MessageLookup(); typedef String MessageIfAbsent(String messageStr, List<dynamic> args); class MessageLookup extends MessageLookupByLibrary { String get localeName => 'ru'; static String m0(episodeNumber, momentTime) => "Эпизод ${episodeNumber}, момент на ${momentTime}"; static String m1(error) => "Произошла неожиданная ошибка\nКод ошибки: ${error}"; static String m2(similarityNum) => "Схожесть: ${similarityNum}%"; final messages = _notInlinedMessages(_notInlinedMessages); static Map<String, Function> _notInlinedMessages(_) => <String, Function>{ "adultOnly": MessageLookupByLibrary.simpleMessage("Только для взрослых!"), "copiedText": MessageLookupByLibrary.simpleMessage("Скопировано!"), "copyNameButton": MessageLookupByLibrary.simpleMessage("Копировать название"), "enterImageUrl": MessageLookupByLibrary.simpleMessage("Введите URL изображения"), "enterImageUrlHint": MessageLookupByLibrary.simpleMessage( "Ссылка на изображение дожна быть прямой"), "episodeText": m0, "error400": MessageLookupByLibrary.simpleMessage( "Предоставленное изображение пустое"), "error402": MessageLookupByLibrary.simpleMessage( "Слишком много запросов, попробуйте позже"), "error500": MessageLookupByLibrary.simpleMessage( "Что-то пошло не так на сервере"), "error503": MessageLookupByLibrary.simpleMessage("Поисковая очередь заполнена"), "error504": MessageLookupByLibrary.simpleMessage( "Сервер перегружен, попробуйте повторить запрос позже"), "errorTimeOut": MessageLookupByLibrary.simpleMessage( "Время ответа сервера истекло"), "errorUnexpected": m1, "errorUnknown": MessageLookupByLibrary.simpleMessage("Что-то пошло не так"), "newSearch": MessageLookupByLibrary.simpleMessage("Новый поиск"), "newSearchHint": MessageLookupByLibrary.simpleMessage( "Введите URL, перетащите файл на окно или выберите файл с помощью кнопки"), "noJapaneseName": MessageLookupByLibrary.simpleMessage( "Японское название не найдено"), "noRomajiName": MessageLookupByLibrary.simpleMessage("Ромадзи название не найдено"), "openSearchButton": MessageLookupByLibrary.simpleMessage("Открыть поиск"), "searchButtonText": MessageLookupByLibrary.simpleMessage("Найти"), "selectFileButtonText": MessageLookupByLibrary.simpleMessage("Выбрать файл"), "similarityText": m2, "viewInAnilist": MessageLookupByLibrary.simpleMessage("Открыть на anilist") }; }
0
mirrored_repositories/find_anime/lib/src/core
mirrored_repositories/find_anime/lib/src/core/widget/app.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import '../../feature/localization/app_language_bloc.dart'; import '../../feature/theme/app_theme_bloc.dart'; import '../generated/localization/l10n.dart'; import '../router/app_router.dart'; import '../theme/theme.dart'; class FindAnimeApp extends StatelessWidget { FindAnimeApp({ Key? key, AppThemeBloc? themeBloc, AppLanguageBloc? languageBloc, }) : _theme = themeBloc ??= AppThemeBloc(Brightness.dark), _language = languageBloc ??= AppLanguageBloc(const Locale('en')), super(key: key); final AppThemeBloc _theme; final AppLanguageBloc _language; @override Widget build(BuildContext context) { return MultiBlocProvider( providers: [ BlocProvider(create: (_) => _theme), BlocProvider(create: (_) => _language), ], child: Builder( builder: (context) { return MaterialApp.router( title: 'FindAnime', routerDelegate: AppRouter.beamerDelegate, routeInformationParser: AppRouter.beamerParser, theme: themeData(), darkTheme: darkThemeData(), themeMode: context.watch<AppThemeBloc>().state.themeMode, locale: context.watch<AppLanguageBloc>().state.getCurrentLocaleOrNull, supportedLocales: const AppLocalizationDelegate().supportedLocales, localizationsDelegates: const [ AppLocalizationDelegate(), GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, GlobalCupertinoLocalizations.delegate, ], ); }, ), ); } }
0
mirrored_repositories/find_anime/lib/src/feature
mirrored_repositories/find_anime/lib/src/feature/theme/app_theme_bloc.freezed.dart
// coverage:ignore-file // GENERATED CODE - DO NOT MODIFY BY HAND // ignore_for_file: type=lint // ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target part of 'app_theme_bloc.dart'; // ************************************************************************** // FreezedGenerator // ************************************************************************** T _$identity<T>(T value) => value; final _privateConstructorUsedError = UnsupportedError( 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#custom-getters-and-methods'); /// @nodoc mixin _$AppThemeState { @optionalTypeArgs TResult when<TResult extends Object?>({ required TResult Function() system, required TResult Function() light, required TResult Function() dark, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({ TResult Function()? system, TResult Function()? light, TResult Function()? dark, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult maybeWhen<TResult extends Object?>({ TResult Function()? system, TResult Function()? light, TResult Function()? dark, required TResult orElse(), }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult map<TResult extends Object?>({ required TResult Function(_SystemAppThemeState value) system, required TResult Function(_LightAppThemeState value) light, required TResult Function(_DarkAppThemeState value) dark, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult? mapOrNull<TResult extends Object?>({ TResult Function(_SystemAppThemeState value)? system, TResult Function(_LightAppThemeState value)? light, TResult Function(_DarkAppThemeState value)? dark, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult maybeMap<TResult extends Object?>({ TResult Function(_SystemAppThemeState value)? system, TResult Function(_LightAppThemeState value)? light, TResult Function(_DarkAppThemeState value)? dark, required TResult orElse(), }) => throw _privateConstructorUsedError; } /// @nodoc abstract class $AppThemeStateCopyWith<$Res> { factory $AppThemeStateCopyWith( AppThemeState value, $Res Function(AppThemeState) then) = _$AppThemeStateCopyWithImpl<$Res>; } /// @nodoc class _$AppThemeStateCopyWithImpl<$Res> implements $AppThemeStateCopyWith<$Res> { _$AppThemeStateCopyWithImpl(this._value, this._then); final AppThemeState _value; // ignore: unused_field final $Res Function(AppThemeState) _then; } /// @nodoc abstract class _$$_SystemAppThemeStateCopyWith<$Res> { factory _$$_SystemAppThemeStateCopyWith(_$_SystemAppThemeState value, $Res Function(_$_SystemAppThemeState) then) = __$$_SystemAppThemeStateCopyWithImpl<$Res>; } /// @nodoc class __$$_SystemAppThemeStateCopyWithImpl<$Res> extends _$AppThemeStateCopyWithImpl<$Res> implements _$$_SystemAppThemeStateCopyWith<$Res> { __$$_SystemAppThemeStateCopyWithImpl(_$_SystemAppThemeState _value, $Res Function(_$_SystemAppThemeState) _then) : super(_value, (v) => _then(v as _$_SystemAppThemeState)); @override _$_SystemAppThemeState get _value => super._value as _$_SystemAppThemeState; } /// @nodoc class _$_SystemAppThemeState extends _SystemAppThemeState { const _$_SystemAppThemeState() : super._(); @override String toString() { return 'AppThemeState.system()'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_SystemAppThemeState); } @override int get hashCode => runtimeType.hashCode; @override @optionalTypeArgs TResult when<TResult extends Object?>({ required TResult Function() system, required TResult Function() light, required TResult Function() dark, }) { return system(); } @override @optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({ TResult Function()? system, TResult Function()? light, TResult Function()? dark, }) { return system?.call(); } @override @optionalTypeArgs TResult maybeWhen<TResult extends Object?>({ TResult Function()? system, TResult Function()? light, TResult Function()? dark, required TResult orElse(), }) { if (system != null) { return system(); } return orElse(); } @override @optionalTypeArgs TResult map<TResult extends Object?>({ required TResult Function(_SystemAppThemeState value) system, required TResult Function(_LightAppThemeState value) light, required TResult Function(_DarkAppThemeState value) dark, }) { return system(this); } @override @optionalTypeArgs TResult? mapOrNull<TResult extends Object?>({ TResult Function(_SystemAppThemeState value)? system, TResult Function(_LightAppThemeState value)? light, TResult Function(_DarkAppThemeState value)? dark, }) { return system?.call(this); } @override @optionalTypeArgs TResult maybeMap<TResult extends Object?>({ TResult Function(_SystemAppThemeState value)? system, TResult Function(_LightAppThemeState value)? light, TResult Function(_DarkAppThemeState value)? dark, required TResult orElse(), }) { if (system != null) { return system(this); } return orElse(); } } abstract class _SystemAppThemeState extends AppThemeState { const factory _SystemAppThemeState() = _$_SystemAppThemeState; const _SystemAppThemeState._() : super._(); } /// @nodoc abstract class _$$_LightAppThemeStateCopyWith<$Res> { factory _$$_LightAppThemeStateCopyWith(_$_LightAppThemeState value, $Res Function(_$_LightAppThemeState) then) = __$$_LightAppThemeStateCopyWithImpl<$Res>; } /// @nodoc class __$$_LightAppThemeStateCopyWithImpl<$Res> extends _$AppThemeStateCopyWithImpl<$Res> implements _$$_LightAppThemeStateCopyWith<$Res> { __$$_LightAppThemeStateCopyWithImpl( _$_LightAppThemeState _value, $Res Function(_$_LightAppThemeState) _then) : super(_value, (v) => _then(v as _$_LightAppThemeState)); @override _$_LightAppThemeState get _value => super._value as _$_LightAppThemeState; } /// @nodoc class _$_LightAppThemeState extends _LightAppThemeState { const _$_LightAppThemeState() : super._(); @override String toString() { return 'AppThemeState.light()'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_LightAppThemeState); } @override int get hashCode => runtimeType.hashCode; @override @optionalTypeArgs TResult when<TResult extends Object?>({ required TResult Function() system, required TResult Function() light, required TResult Function() dark, }) { return light(); } @override @optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({ TResult Function()? system, TResult Function()? light, TResult Function()? dark, }) { return light?.call(); } @override @optionalTypeArgs TResult maybeWhen<TResult extends Object?>({ TResult Function()? system, TResult Function()? light, TResult Function()? dark, required TResult orElse(), }) { if (light != null) { return light(); } return orElse(); } @override @optionalTypeArgs TResult map<TResult extends Object?>({ required TResult Function(_SystemAppThemeState value) system, required TResult Function(_LightAppThemeState value) light, required TResult Function(_DarkAppThemeState value) dark, }) { return light(this); } @override @optionalTypeArgs TResult? mapOrNull<TResult extends Object?>({ TResult Function(_SystemAppThemeState value)? system, TResult Function(_LightAppThemeState value)? light, TResult Function(_DarkAppThemeState value)? dark, }) { return light?.call(this); } @override @optionalTypeArgs TResult maybeMap<TResult extends Object?>({ TResult Function(_SystemAppThemeState value)? system, TResult Function(_LightAppThemeState value)? light, TResult Function(_DarkAppThemeState value)? dark, required TResult orElse(), }) { if (light != null) { return light(this); } return orElse(); } } abstract class _LightAppThemeState extends AppThemeState { const factory _LightAppThemeState() = _$_LightAppThemeState; const _LightAppThemeState._() : super._(); } /// @nodoc abstract class _$$_DarkAppThemeStateCopyWith<$Res> { factory _$$_DarkAppThemeStateCopyWith(_$_DarkAppThemeState value, $Res Function(_$_DarkAppThemeState) then) = __$$_DarkAppThemeStateCopyWithImpl<$Res>; } /// @nodoc class __$$_DarkAppThemeStateCopyWithImpl<$Res> extends _$AppThemeStateCopyWithImpl<$Res> implements _$$_DarkAppThemeStateCopyWith<$Res> { __$$_DarkAppThemeStateCopyWithImpl( _$_DarkAppThemeState _value, $Res Function(_$_DarkAppThemeState) _then) : super(_value, (v) => _then(v as _$_DarkAppThemeState)); @override _$_DarkAppThemeState get _value => super._value as _$_DarkAppThemeState; } /// @nodoc class _$_DarkAppThemeState extends _DarkAppThemeState { const _$_DarkAppThemeState() : super._(); @override String toString() { return 'AppThemeState.dark()'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_DarkAppThemeState); } @override int get hashCode => runtimeType.hashCode; @override @optionalTypeArgs TResult when<TResult extends Object?>({ required TResult Function() system, required TResult Function() light, required TResult Function() dark, }) { return dark(); } @override @optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({ TResult Function()? system, TResult Function()? light, TResult Function()? dark, }) { return dark?.call(); } @override @optionalTypeArgs TResult maybeWhen<TResult extends Object?>({ TResult Function()? system, TResult Function()? light, TResult Function()? dark, required TResult orElse(), }) { if (dark != null) { return dark(); } return orElse(); } @override @optionalTypeArgs TResult map<TResult extends Object?>({ required TResult Function(_SystemAppThemeState value) system, required TResult Function(_LightAppThemeState value) light, required TResult Function(_DarkAppThemeState value) dark, }) { return dark(this); } @override @optionalTypeArgs TResult? mapOrNull<TResult extends Object?>({ TResult Function(_SystemAppThemeState value)? system, TResult Function(_LightAppThemeState value)? light, TResult Function(_DarkAppThemeState value)? dark, }) { return dark?.call(this); } @override @optionalTypeArgs TResult maybeMap<TResult extends Object?>({ TResult Function(_SystemAppThemeState value)? system, TResult Function(_LightAppThemeState value)? light, TResult Function(_DarkAppThemeState value)? dark, required TResult orElse(), }) { if (dark != null) { return dark(this); } return orElse(); } } abstract class _DarkAppThemeState extends AppThemeState { const factory _DarkAppThemeState() = _$_DarkAppThemeState; const _DarkAppThemeState._() : super._(); } /// @nodoc mixin _$AppThemeEvent { @optionalTypeArgs TResult when<TResult extends Object?>({ required TResult Function() changedToLight, required TResult Function() changedToDark, required TResult Function() changedToSystem, required TResult Function() themeToggled, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({ TResult Function()? changedToLight, TResult Function()? changedToDark, TResult Function()? changedToSystem, TResult Function()? themeToggled, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult maybeWhen<TResult extends Object?>({ TResult Function()? changedToLight, TResult Function()? changedToDark, TResult Function()? changedToSystem, TResult Function()? themeToggled, required TResult orElse(), }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult map<TResult extends Object?>({ required TResult Function(_ChangedToLightAppThemeEvent value) changedToLight, required TResult Function(_ChangedToDarkAppThemeEvent value) changedToDark, required TResult Function(_ChangedToSystemAppThemeEvent value) changedToSystem, required TResult Function(_ThemeToggledAppThemeEvent value) themeToggled, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult? mapOrNull<TResult extends Object?>({ TResult Function(_ChangedToLightAppThemeEvent value)? changedToLight, TResult Function(_ChangedToDarkAppThemeEvent value)? changedToDark, TResult Function(_ChangedToSystemAppThemeEvent value)? changedToSystem, TResult Function(_ThemeToggledAppThemeEvent value)? themeToggled, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult maybeMap<TResult extends Object?>({ TResult Function(_ChangedToLightAppThemeEvent value)? changedToLight, TResult Function(_ChangedToDarkAppThemeEvent value)? changedToDark, TResult Function(_ChangedToSystemAppThemeEvent value)? changedToSystem, TResult Function(_ThemeToggledAppThemeEvent value)? themeToggled, required TResult orElse(), }) => throw _privateConstructorUsedError; } /// @nodoc abstract class $AppThemeEventCopyWith<$Res> { factory $AppThemeEventCopyWith( AppThemeEvent value, $Res Function(AppThemeEvent) then) = _$AppThemeEventCopyWithImpl<$Res>; } /// @nodoc class _$AppThemeEventCopyWithImpl<$Res> implements $AppThemeEventCopyWith<$Res> { _$AppThemeEventCopyWithImpl(this._value, this._then); final AppThemeEvent _value; // ignore: unused_field final $Res Function(AppThemeEvent) _then; } /// @nodoc abstract class _$$_ChangedToLightAppThemeEventCopyWith<$Res> { factory _$$_ChangedToLightAppThemeEventCopyWith( _$_ChangedToLightAppThemeEvent value, $Res Function(_$_ChangedToLightAppThemeEvent) then) = __$$_ChangedToLightAppThemeEventCopyWithImpl<$Res>; } /// @nodoc class __$$_ChangedToLightAppThemeEventCopyWithImpl<$Res> extends _$AppThemeEventCopyWithImpl<$Res> implements _$$_ChangedToLightAppThemeEventCopyWith<$Res> { __$$_ChangedToLightAppThemeEventCopyWithImpl( _$_ChangedToLightAppThemeEvent _value, $Res Function(_$_ChangedToLightAppThemeEvent) _then) : super(_value, (v) => _then(v as _$_ChangedToLightAppThemeEvent)); @override _$_ChangedToLightAppThemeEvent get _value => super._value as _$_ChangedToLightAppThemeEvent; } /// @nodoc class _$_ChangedToLightAppThemeEvent extends _ChangedToLightAppThemeEvent { const _$_ChangedToLightAppThemeEvent() : super._(); @override String toString() { return 'AppThemeEvent.changedToLight()'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_ChangedToLightAppThemeEvent); } @override int get hashCode => runtimeType.hashCode; @override @optionalTypeArgs TResult when<TResult extends Object?>({ required TResult Function() changedToLight, required TResult Function() changedToDark, required TResult Function() changedToSystem, required TResult Function() themeToggled, }) { return changedToLight(); } @override @optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({ TResult Function()? changedToLight, TResult Function()? changedToDark, TResult Function()? changedToSystem, TResult Function()? themeToggled, }) { return changedToLight?.call(); } @override @optionalTypeArgs TResult maybeWhen<TResult extends Object?>({ TResult Function()? changedToLight, TResult Function()? changedToDark, TResult Function()? changedToSystem, TResult Function()? themeToggled, required TResult orElse(), }) { if (changedToLight != null) { return changedToLight(); } return orElse(); } @override @optionalTypeArgs TResult map<TResult extends Object?>({ required TResult Function(_ChangedToLightAppThemeEvent value) changedToLight, required TResult Function(_ChangedToDarkAppThemeEvent value) changedToDark, required TResult Function(_ChangedToSystemAppThemeEvent value) changedToSystem, required TResult Function(_ThemeToggledAppThemeEvent value) themeToggled, }) { return changedToLight(this); } @override @optionalTypeArgs TResult? mapOrNull<TResult extends Object?>({ TResult Function(_ChangedToLightAppThemeEvent value)? changedToLight, TResult Function(_ChangedToDarkAppThemeEvent value)? changedToDark, TResult Function(_ChangedToSystemAppThemeEvent value)? changedToSystem, TResult Function(_ThemeToggledAppThemeEvent value)? themeToggled, }) { return changedToLight?.call(this); } @override @optionalTypeArgs TResult maybeMap<TResult extends Object?>({ TResult Function(_ChangedToLightAppThemeEvent value)? changedToLight, TResult Function(_ChangedToDarkAppThemeEvent value)? changedToDark, TResult Function(_ChangedToSystemAppThemeEvent value)? changedToSystem, TResult Function(_ThemeToggledAppThemeEvent value)? themeToggled, required TResult orElse(), }) { if (changedToLight != null) { return changedToLight(this); } return orElse(); } } abstract class _ChangedToLightAppThemeEvent extends AppThemeEvent { const factory _ChangedToLightAppThemeEvent() = _$_ChangedToLightAppThemeEvent; const _ChangedToLightAppThemeEvent._() : super._(); } /// @nodoc abstract class _$$_ChangedToDarkAppThemeEventCopyWith<$Res> { factory _$$_ChangedToDarkAppThemeEventCopyWith( _$_ChangedToDarkAppThemeEvent value, $Res Function(_$_ChangedToDarkAppThemeEvent) then) = __$$_ChangedToDarkAppThemeEventCopyWithImpl<$Res>; } /// @nodoc class __$$_ChangedToDarkAppThemeEventCopyWithImpl<$Res> extends _$AppThemeEventCopyWithImpl<$Res> implements _$$_ChangedToDarkAppThemeEventCopyWith<$Res> { __$$_ChangedToDarkAppThemeEventCopyWithImpl( _$_ChangedToDarkAppThemeEvent _value, $Res Function(_$_ChangedToDarkAppThemeEvent) _then) : super(_value, (v) => _then(v as _$_ChangedToDarkAppThemeEvent)); @override _$_ChangedToDarkAppThemeEvent get _value => super._value as _$_ChangedToDarkAppThemeEvent; } /// @nodoc class _$_ChangedToDarkAppThemeEvent extends _ChangedToDarkAppThemeEvent { const _$_ChangedToDarkAppThemeEvent() : super._(); @override String toString() { return 'AppThemeEvent.changedToDark()'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_ChangedToDarkAppThemeEvent); } @override int get hashCode => runtimeType.hashCode; @override @optionalTypeArgs TResult when<TResult extends Object?>({ required TResult Function() changedToLight, required TResult Function() changedToDark, required TResult Function() changedToSystem, required TResult Function() themeToggled, }) { return changedToDark(); } @override @optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({ TResult Function()? changedToLight, TResult Function()? changedToDark, TResult Function()? changedToSystem, TResult Function()? themeToggled, }) { return changedToDark?.call(); } @override @optionalTypeArgs TResult maybeWhen<TResult extends Object?>({ TResult Function()? changedToLight, TResult Function()? changedToDark, TResult Function()? changedToSystem, TResult Function()? themeToggled, required TResult orElse(), }) { if (changedToDark != null) { return changedToDark(); } return orElse(); } @override @optionalTypeArgs TResult map<TResult extends Object?>({ required TResult Function(_ChangedToLightAppThemeEvent value) changedToLight, required TResult Function(_ChangedToDarkAppThemeEvent value) changedToDark, required TResult Function(_ChangedToSystemAppThemeEvent value) changedToSystem, required TResult Function(_ThemeToggledAppThemeEvent value) themeToggled, }) { return changedToDark(this); } @override @optionalTypeArgs TResult? mapOrNull<TResult extends Object?>({ TResult Function(_ChangedToLightAppThemeEvent value)? changedToLight, TResult Function(_ChangedToDarkAppThemeEvent value)? changedToDark, TResult Function(_ChangedToSystemAppThemeEvent value)? changedToSystem, TResult Function(_ThemeToggledAppThemeEvent value)? themeToggled, }) { return changedToDark?.call(this); } @override @optionalTypeArgs TResult maybeMap<TResult extends Object?>({ TResult Function(_ChangedToLightAppThemeEvent value)? changedToLight, TResult Function(_ChangedToDarkAppThemeEvent value)? changedToDark, TResult Function(_ChangedToSystemAppThemeEvent value)? changedToSystem, TResult Function(_ThemeToggledAppThemeEvent value)? themeToggled, required TResult orElse(), }) { if (changedToDark != null) { return changedToDark(this); } return orElse(); } } abstract class _ChangedToDarkAppThemeEvent extends AppThemeEvent { const factory _ChangedToDarkAppThemeEvent() = _$_ChangedToDarkAppThemeEvent; const _ChangedToDarkAppThemeEvent._() : super._(); } /// @nodoc abstract class _$$_ChangedToSystemAppThemeEventCopyWith<$Res> { factory _$$_ChangedToSystemAppThemeEventCopyWith( _$_ChangedToSystemAppThemeEvent value, $Res Function(_$_ChangedToSystemAppThemeEvent) then) = __$$_ChangedToSystemAppThemeEventCopyWithImpl<$Res>; } /// @nodoc class __$$_ChangedToSystemAppThemeEventCopyWithImpl<$Res> extends _$AppThemeEventCopyWithImpl<$Res> implements _$$_ChangedToSystemAppThemeEventCopyWith<$Res> { __$$_ChangedToSystemAppThemeEventCopyWithImpl( _$_ChangedToSystemAppThemeEvent _value, $Res Function(_$_ChangedToSystemAppThemeEvent) _then) : super(_value, (v) => _then(v as _$_ChangedToSystemAppThemeEvent)); @override _$_ChangedToSystemAppThemeEvent get _value => super._value as _$_ChangedToSystemAppThemeEvent; } /// @nodoc class _$_ChangedToSystemAppThemeEvent extends _ChangedToSystemAppThemeEvent { const _$_ChangedToSystemAppThemeEvent() : super._(); @override String toString() { return 'AppThemeEvent.changedToSystem()'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_ChangedToSystemAppThemeEvent); } @override int get hashCode => runtimeType.hashCode; @override @optionalTypeArgs TResult when<TResult extends Object?>({ required TResult Function() changedToLight, required TResult Function() changedToDark, required TResult Function() changedToSystem, required TResult Function() themeToggled, }) { return changedToSystem(); } @override @optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({ TResult Function()? changedToLight, TResult Function()? changedToDark, TResult Function()? changedToSystem, TResult Function()? themeToggled, }) { return changedToSystem?.call(); } @override @optionalTypeArgs TResult maybeWhen<TResult extends Object?>({ TResult Function()? changedToLight, TResult Function()? changedToDark, TResult Function()? changedToSystem, TResult Function()? themeToggled, required TResult orElse(), }) { if (changedToSystem != null) { return changedToSystem(); } return orElse(); } @override @optionalTypeArgs TResult map<TResult extends Object?>({ required TResult Function(_ChangedToLightAppThemeEvent value) changedToLight, required TResult Function(_ChangedToDarkAppThemeEvent value) changedToDark, required TResult Function(_ChangedToSystemAppThemeEvent value) changedToSystem, required TResult Function(_ThemeToggledAppThemeEvent value) themeToggled, }) { return changedToSystem(this); } @override @optionalTypeArgs TResult? mapOrNull<TResult extends Object?>({ TResult Function(_ChangedToLightAppThemeEvent value)? changedToLight, TResult Function(_ChangedToDarkAppThemeEvent value)? changedToDark, TResult Function(_ChangedToSystemAppThemeEvent value)? changedToSystem, TResult Function(_ThemeToggledAppThemeEvent value)? themeToggled, }) { return changedToSystem?.call(this); } @override @optionalTypeArgs TResult maybeMap<TResult extends Object?>({ TResult Function(_ChangedToLightAppThemeEvent value)? changedToLight, TResult Function(_ChangedToDarkAppThemeEvent value)? changedToDark, TResult Function(_ChangedToSystemAppThemeEvent value)? changedToSystem, TResult Function(_ThemeToggledAppThemeEvent value)? themeToggled, required TResult orElse(), }) { if (changedToSystem != null) { return changedToSystem(this); } return orElse(); } } abstract class _ChangedToSystemAppThemeEvent extends AppThemeEvent { const factory _ChangedToSystemAppThemeEvent() = _$_ChangedToSystemAppThemeEvent; const _ChangedToSystemAppThemeEvent._() : super._(); } /// @nodoc abstract class _$$_ThemeToggledAppThemeEventCopyWith<$Res> { factory _$$_ThemeToggledAppThemeEventCopyWith( _$_ThemeToggledAppThemeEvent value, $Res Function(_$_ThemeToggledAppThemeEvent) then) = __$$_ThemeToggledAppThemeEventCopyWithImpl<$Res>; } /// @nodoc class __$$_ThemeToggledAppThemeEventCopyWithImpl<$Res> extends _$AppThemeEventCopyWithImpl<$Res> implements _$$_ThemeToggledAppThemeEventCopyWith<$Res> { __$$_ThemeToggledAppThemeEventCopyWithImpl( _$_ThemeToggledAppThemeEvent _value, $Res Function(_$_ThemeToggledAppThemeEvent) _then) : super(_value, (v) => _then(v as _$_ThemeToggledAppThemeEvent)); @override _$_ThemeToggledAppThemeEvent get _value => super._value as _$_ThemeToggledAppThemeEvent; } /// @nodoc class _$_ThemeToggledAppThemeEvent extends _ThemeToggledAppThemeEvent { const _$_ThemeToggledAppThemeEvent() : super._(); @override String toString() { return 'AppThemeEvent.themeToggled()'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_ThemeToggledAppThemeEvent); } @override int get hashCode => runtimeType.hashCode; @override @optionalTypeArgs TResult when<TResult extends Object?>({ required TResult Function() changedToLight, required TResult Function() changedToDark, required TResult Function() changedToSystem, required TResult Function() themeToggled, }) { return themeToggled(); } @override @optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({ TResult Function()? changedToLight, TResult Function()? changedToDark, TResult Function()? changedToSystem, TResult Function()? themeToggled, }) { return themeToggled?.call(); } @override @optionalTypeArgs TResult maybeWhen<TResult extends Object?>({ TResult Function()? changedToLight, TResult Function()? changedToDark, TResult Function()? changedToSystem, TResult Function()? themeToggled, required TResult orElse(), }) { if (themeToggled != null) { return themeToggled(); } return orElse(); } @override @optionalTypeArgs TResult map<TResult extends Object?>({ required TResult Function(_ChangedToLightAppThemeEvent value) changedToLight, required TResult Function(_ChangedToDarkAppThemeEvent value) changedToDark, required TResult Function(_ChangedToSystemAppThemeEvent value) changedToSystem, required TResult Function(_ThemeToggledAppThemeEvent value) themeToggled, }) { return themeToggled(this); } @override @optionalTypeArgs TResult? mapOrNull<TResult extends Object?>({ TResult Function(_ChangedToLightAppThemeEvent value)? changedToLight, TResult Function(_ChangedToDarkAppThemeEvent value)? changedToDark, TResult Function(_ChangedToSystemAppThemeEvent value)? changedToSystem, TResult Function(_ThemeToggledAppThemeEvent value)? themeToggled, }) { return themeToggled?.call(this); } @override @optionalTypeArgs TResult maybeMap<TResult extends Object?>({ TResult Function(_ChangedToLightAppThemeEvent value)? changedToLight, TResult Function(_ChangedToDarkAppThemeEvent value)? changedToDark, TResult Function(_ChangedToSystemAppThemeEvent value)? changedToSystem, TResult Function(_ThemeToggledAppThemeEvent value)? themeToggled, required TResult orElse(), }) { if (themeToggled != null) { return themeToggled(this); } return orElse(); } } abstract class _ThemeToggledAppThemeEvent extends AppThemeEvent { const factory _ThemeToggledAppThemeEvent() = _$_ThemeToggledAppThemeEvent; const _ThemeToggledAppThemeEvent._() : super._(); }
0
mirrored_repositories/find_anime/lib/src/feature
mirrored_repositories/find_anime/lib/src/feature/theme/app_theme_bloc.dart
import 'package:flutter/material.dart'; // used only for ThemeMode import 'package:flutter/scheduler.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; part 'app_theme_bloc.freezed.dart'; @freezed class AppThemeState with _$AppThemeState { const AppThemeState._(); ThemeMode get themeMode => when( system: () => ThemeMode.system, light: () => ThemeMode.light, dark: () => ThemeMode.dark, ); /// App theme is matching system const factory AppThemeState.system() = _SystemAppThemeState; /// App theme is light const factory AppThemeState.light() = _LightAppThemeState; /// App theme is dark const factory AppThemeState.dark() = _DarkAppThemeState; } @freezed class AppThemeEvent with _$AppThemeEvent { const AppThemeEvent._(); /// User changed app theme to light const factory AppThemeEvent.changedToLight() = _ChangedToLightAppThemeEvent; /// User changed app theme to dark const factory AppThemeEvent.changedToDark() = _ChangedToDarkAppThemeEvent; /// User changed app theme to matching system const factory AppThemeEvent.changedToSystem() = _ChangedToSystemAppThemeEvent; /// User toggle theme const factory AppThemeEvent.themeToggled() = _ThemeToggledAppThemeEvent; } class AppThemeBloc extends Bloc<AppThemeEvent, AppThemeState> { AppThemeBloc( Brightness brightness, ) : super( brightness == Brightness.light ? const AppThemeState.light() : const AppThemeState.dark(), ) { on<AppThemeEvent>( (event, emit) => event.map<Future<void>>( changedToDark: (event) => _changedToDark(event, emit), changedToLight: (event) => _changedToLight(event, emit), changedToSystem: (event) => _changedToSystem(event, emit), themeToggled: (event) => _themeToggled(event, emit), ), ); } Future<void> _changedToDark( _ChangedToDarkAppThemeEvent event, Emitter<AppThemeState> emitter, ) async => emitter(const AppThemeState.dark()); Future<void> _changedToLight( _ChangedToLightAppThemeEvent event, Emitter<AppThemeState> emitter, ) async => emitter(const AppThemeState.light()); Future<void> _changedToSystem( _ChangedToSystemAppThemeEvent event, Emitter<AppThemeState> emitter, ) async => emitter(const AppThemeState.system()); Future<void> _themeToggled( _ThemeToggledAppThemeEvent event, Emitter<AppThemeState> emitter, ) async { state.when( system: () => emitter(_isDeviceInDarkMode ? const AppThemeState.light() : const AppThemeState.dark()), light: () => emitter(const AppThemeState.dark()), dark: () => emitter(const AppThemeState.light()), ); } bool get _isDeviceInDarkMode { Brightness deviceBrightness = SchedulerBinding.instance.window.platformBrightness; return deviceBrightness == Brightness.dark; } }
0
mirrored_repositories/find_anime/lib/src/feature
mirrored_repositories/find_anime/lib/src/feature/localization/app_language_bloc.dart
import 'dart:ui'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; import '../../core/generated/localization/l10n.dart'; part 'app_language_bloc.freezed.dart'; @freezed class AppLanguageState with _$AppLanguageState { const AppLanguageState._(); /// Returns current used language. Can be null, if something went wrong /// while changing language Locale? get getCurrentLocaleOrNull => maybeWhen( usingLocale: (locale) => locale, orElse: () => null, ); /// Application using [locale] const factory AppLanguageState.usingLocale(Locale locale) = _InitialAppLanguageState; /// Something went wrong with language const factory AppLanguageState.failure({ @Default('An error while changed language has occurred') String message, }) = _FailureAppLanguageState; /// Language changing was successful const factory AppLanguageState.successful() = _SuccessfulAppLanguageState; } @freezed class AppLanguageEvent with _$AppLanguageEvent { const AppLanguageEvent._(); /// User changed app language to [newLocale] const factory AppLanguageEvent.changeToLocale(Locale newLocale) = _ChangeToLocaleAppLanguageEvent; /// User toggled language const factory AppLanguageEvent.languageToggled() = _LanguageToggledAppLanguageEvent; } class AppLanguageBloc extends Bloc<AppLanguageEvent, AppLanguageState> { AppLanguageBloc(Locale locale) : super(AppLanguageState.usingLocale(locale)) { on<AppLanguageEvent>( (event, emit) => event.map<Future<void>>( changeToLocale: (event) => _changeToLocale(event, emit), languageToggled: (event) => _languageToggled(event, emit), ), ); } /// Sets app language to new Future<void> _changeToLocale( _ChangeToLocaleAppLanguageEvent event, Emitter<AppLanguageState> emitter, ) async { try { // load new locale to app await S.load(event.newLocale); // notify about new language emitter(AppLanguageState.usingLocale(event.newLocale)); // notify about successful changing emitter(const AppLanguageState.successful()); } on Object catch (error) { // something went wrong while changing language emitter(AppLanguageState.failure(message: error.toString())); // rethrow error to observer rethrow; } } // this method used only for bloc training, in real app // you should use [_changeToLocale] with GUI for user. Do not just // toggle language /// Toggles current app language Future<void> _languageToggled( _LanguageToggledAppLanguageEvent event, Emitter<AppLanguageState> emitter, ) async { List<Locale> locales = const AppLocalizationDelegate().supportedLocales; int currentLocale = locales.indexOf(state.getCurrentLocaleOrNull!); if (currentLocale + 1 >= locales.length) { emitter(AppLanguageState.usingLocale(locales[0])); } else { emitter(AppLanguageState.usingLocale(locales[currentLocale + 1])); } } }
0
mirrored_repositories/find_anime/lib/src/feature
mirrored_repositories/find_anime/lib/src/feature/localization/app_language_bloc.freezed.dart
// coverage:ignore-file // GENERATED CODE - DO NOT MODIFY BY HAND // ignore_for_file: type=lint // ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target part of 'app_language_bloc.dart'; // ************************************************************************** // FreezedGenerator // ************************************************************************** T _$identity<T>(T value) => value; final _privateConstructorUsedError = UnsupportedError( 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#custom-getters-and-methods'); /// @nodoc mixin _$AppLanguageState { @optionalTypeArgs TResult when<TResult extends Object?>({ required TResult Function(Locale locale) usingLocale, required TResult Function(String message) failure, required TResult Function() successful, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({ TResult Function(Locale locale)? usingLocale, TResult Function(String message)? failure, TResult Function()? successful, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult maybeWhen<TResult extends Object?>({ TResult Function(Locale locale)? usingLocale, TResult Function(String message)? failure, TResult Function()? successful, required TResult orElse(), }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult map<TResult extends Object?>({ required TResult Function(_InitialAppLanguageState value) usingLocale, required TResult Function(_FailureAppLanguageState value) failure, required TResult Function(_SuccessfulAppLanguageState value) successful, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult? mapOrNull<TResult extends Object?>({ TResult Function(_InitialAppLanguageState value)? usingLocale, TResult Function(_FailureAppLanguageState value)? failure, TResult Function(_SuccessfulAppLanguageState value)? successful, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult maybeMap<TResult extends Object?>({ TResult Function(_InitialAppLanguageState value)? usingLocale, TResult Function(_FailureAppLanguageState value)? failure, TResult Function(_SuccessfulAppLanguageState value)? successful, required TResult orElse(), }) => throw _privateConstructorUsedError; } /// @nodoc abstract class $AppLanguageStateCopyWith<$Res> { factory $AppLanguageStateCopyWith( AppLanguageState value, $Res Function(AppLanguageState) then) = _$AppLanguageStateCopyWithImpl<$Res>; } /// @nodoc class _$AppLanguageStateCopyWithImpl<$Res> implements $AppLanguageStateCopyWith<$Res> { _$AppLanguageStateCopyWithImpl(this._value, this._then); final AppLanguageState _value; // ignore: unused_field final $Res Function(AppLanguageState) _then; } /// @nodoc abstract class _$$_InitialAppLanguageStateCopyWith<$Res> { factory _$$_InitialAppLanguageStateCopyWith(_$_InitialAppLanguageState value, $Res Function(_$_InitialAppLanguageState) then) = __$$_InitialAppLanguageStateCopyWithImpl<$Res>; $Res call({Locale locale}); } /// @nodoc class __$$_InitialAppLanguageStateCopyWithImpl<$Res> extends _$AppLanguageStateCopyWithImpl<$Res> implements _$$_InitialAppLanguageStateCopyWith<$Res> { __$$_InitialAppLanguageStateCopyWithImpl(_$_InitialAppLanguageState _value, $Res Function(_$_InitialAppLanguageState) _then) : super(_value, (v) => _then(v as _$_InitialAppLanguageState)); @override _$_InitialAppLanguageState get _value => super._value as _$_InitialAppLanguageState; @override $Res call({ Object? locale = freezed, }) { return _then(_$_InitialAppLanguageState( locale == freezed ? _value.locale : locale // ignore: cast_nullable_to_non_nullable as Locale, )); } } /// @nodoc class _$_InitialAppLanguageState extends _InitialAppLanguageState { const _$_InitialAppLanguageState(this.locale) : super._(); @override final Locale locale; @override String toString() { return 'AppLanguageState.usingLocale(locale: $locale)'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_InitialAppLanguageState && const DeepCollectionEquality().equals(other.locale, locale)); } @override int get hashCode => Object.hash(runtimeType, const DeepCollectionEquality().hash(locale)); @JsonKey(ignore: true) @override _$$_InitialAppLanguageStateCopyWith<_$_InitialAppLanguageState> get copyWith => __$$_InitialAppLanguageStateCopyWithImpl<_$_InitialAppLanguageState>( this, _$identity); @override @optionalTypeArgs TResult when<TResult extends Object?>({ required TResult Function(Locale locale) usingLocale, required TResult Function(String message) failure, required TResult Function() successful, }) { return usingLocale(locale); } @override @optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({ TResult Function(Locale locale)? usingLocale, TResult Function(String message)? failure, TResult Function()? successful, }) { return usingLocale?.call(locale); } @override @optionalTypeArgs TResult maybeWhen<TResult extends Object?>({ TResult Function(Locale locale)? usingLocale, TResult Function(String message)? failure, TResult Function()? successful, required TResult orElse(), }) { if (usingLocale != null) { return usingLocale(locale); } return orElse(); } @override @optionalTypeArgs TResult map<TResult extends Object?>({ required TResult Function(_InitialAppLanguageState value) usingLocale, required TResult Function(_FailureAppLanguageState value) failure, required TResult Function(_SuccessfulAppLanguageState value) successful, }) { return usingLocale(this); } @override @optionalTypeArgs TResult? mapOrNull<TResult extends Object?>({ TResult Function(_InitialAppLanguageState value)? usingLocale, TResult Function(_FailureAppLanguageState value)? failure, TResult Function(_SuccessfulAppLanguageState value)? successful, }) { return usingLocale?.call(this); } @override @optionalTypeArgs TResult maybeMap<TResult extends Object?>({ TResult Function(_InitialAppLanguageState value)? usingLocale, TResult Function(_FailureAppLanguageState value)? failure, TResult Function(_SuccessfulAppLanguageState value)? successful, required TResult orElse(), }) { if (usingLocale != null) { return usingLocale(this); } return orElse(); } } abstract class _InitialAppLanguageState extends AppLanguageState { const factory _InitialAppLanguageState(final Locale locale) = _$_InitialAppLanguageState; const _InitialAppLanguageState._() : super._(); Locale get locale; @JsonKey(ignore: true) _$$_InitialAppLanguageStateCopyWith<_$_InitialAppLanguageState> get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class _$$_FailureAppLanguageStateCopyWith<$Res> { factory _$$_FailureAppLanguageStateCopyWith(_$_FailureAppLanguageState value, $Res Function(_$_FailureAppLanguageState) then) = __$$_FailureAppLanguageStateCopyWithImpl<$Res>; $Res call({String message}); } /// @nodoc class __$$_FailureAppLanguageStateCopyWithImpl<$Res> extends _$AppLanguageStateCopyWithImpl<$Res> implements _$$_FailureAppLanguageStateCopyWith<$Res> { __$$_FailureAppLanguageStateCopyWithImpl(_$_FailureAppLanguageState _value, $Res Function(_$_FailureAppLanguageState) _then) : super(_value, (v) => _then(v as _$_FailureAppLanguageState)); @override _$_FailureAppLanguageState get _value => super._value as _$_FailureAppLanguageState; @override $Res call({ Object? message = freezed, }) { return _then(_$_FailureAppLanguageState( message: message == freezed ? _value.message : message // ignore: cast_nullable_to_non_nullable as String, )); } } /// @nodoc class _$_FailureAppLanguageState extends _FailureAppLanguageState { const _$_FailureAppLanguageState( {this.message = 'An error while changed language has occurred'}) : super._(); @override @JsonKey() final String message; @override String toString() { return 'AppLanguageState.failure(message: $message)'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_FailureAppLanguageState && const DeepCollectionEquality().equals(other.message, message)); } @override int get hashCode => Object.hash(runtimeType, const DeepCollectionEquality().hash(message)); @JsonKey(ignore: true) @override _$$_FailureAppLanguageStateCopyWith<_$_FailureAppLanguageState> get copyWith => __$$_FailureAppLanguageStateCopyWithImpl<_$_FailureAppLanguageState>( this, _$identity); @override @optionalTypeArgs TResult when<TResult extends Object?>({ required TResult Function(Locale locale) usingLocale, required TResult Function(String message) failure, required TResult Function() successful, }) { return failure(message); } @override @optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({ TResult Function(Locale locale)? usingLocale, TResult Function(String message)? failure, TResult Function()? successful, }) { return failure?.call(message); } @override @optionalTypeArgs TResult maybeWhen<TResult extends Object?>({ TResult Function(Locale locale)? usingLocale, TResult Function(String message)? failure, TResult Function()? successful, required TResult orElse(), }) { if (failure != null) { return failure(message); } return orElse(); } @override @optionalTypeArgs TResult map<TResult extends Object?>({ required TResult Function(_InitialAppLanguageState value) usingLocale, required TResult Function(_FailureAppLanguageState value) failure, required TResult Function(_SuccessfulAppLanguageState value) successful, }) { return failure(this); } @override @optionalTypeArgs TResult? mapOrNull<TResult extends Object?>({ TResult Function(_InitialAppLanguageState value)? usingLocale, TResult Function(_FailureAppLanguageState value)? failure, TResult Function(_SuccessfulAppLanguageState value)? successful, }) { return failure?.call(this); } @override @optionalTypeArgs TResult maybeMap<TResult extends Object?>({ TResult Function(_InitialAppLanguageState value)? usingLocale, TResult Function(_FailureAppLanguageState value)? failure, TResult Function(_SuccessfulAppLanguageState value)? successful, required TResult orElse(), }) { if (failure != null) { return failure(this); } return orElse(); } } abstract class _FailureAppLanguageState extends AppLanguageState { const factory _FailureAppLanguageState({final String message}) = _$_FailureAppLanguageState; const _FailureAppLanguageState._() : super._(); String get message; @JsonKey(ignore: true) _$$_FailureAppLanguageStateCopyWith<_$_FailureAppLanguageState> get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class _$$_SuccessfulAppLanguageStateCopyWith<$Res> { factory _$$_SuccessfulAppLanguageStateCopyWith( _$_SuccessfulAppLanguageState value, $Res Function(_$_SuccessfulAppLanguageState) then) = __$$_SuccessfulAppLanguageStateCopyWithImpl<$Res>; } /// @nodoc class __$$_SuccessfulAppLanguageStateCopyWithImpl<$Res> extends _$AppLanguageStateCopyWithImpl<$Res> implements _$$_SuccessfulAppLanguageStateCopyWith<$Res> { __$$_SuccessfulAppLanguageStateCopyWithImpl( _$_SuccessfulAppLanguageState _value, $Res Function(_$_SuccessfulAppLanguageState) _then) : super(_value, (v) => _then(v as _$_SuccessfulAppLanguageState)); @override _$_SuccessfulAppLanguageState get _value => super._value as _$_SuccessfulAppLanguageState; } /// @nodoc class _$_SuccessfulAppLanguageState extends _SuccessfulAppLanguageState { const _$_SuccessfulAppLanguageState() : super._(); @override String toString() { return 'AppLanguageState.successful()'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_SuccessfulAppLanguageState); } @override int get hashCode => runtimeType.hashCode; @override @optionalTypeArgs TResult when<TResult extends Object?>({ required TResult Function(Locale locale) usingLocale, required TResult Function(String message) failure, required TResult Function() successful, }) { return successful(); } @override @optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({ TResult Function(Locale locale)? usingLocale, TResult Function(String message)? failure, TResult Function()? successful, }) { return successful?.call(); } @override @optionalTypeArgs TResult maybeWhen<TResult extends Object?>({ TResult Function(Locale locale)? usingLocale, TResult Function(String message)? failure, TResult Function()? successful, required TResult orElse(), }) { if (successful != null) { return successful(); } return orElse(); } @override @optionalTypeArgs TResult map<TResult extends Object?>({ required TResult Function(_InitialAppLanguageState value) usingLocale, required TResult Function(_FailureAppLanguageState value) failure, required TResult Function(_SuccessfulAppLanguageState value) successful, }) { return successful(this); } @override @optionalTypeArgs TResult? mapOrNull<TResult extends Object?>({ TResult Function(_InitialAppLanguageState value)? usingLocale, TResult Function(_FailureAppLanguageState value)? failure, TResult Function(_SuccessfulAppLanguageState value)? successful, }) { return successful?.call(this); } @override @optionalTypeArgs TResult maybeMap<TResult extends Object?>({ TResult Function(_InitialAppLanguageState value)? usingLocale, TResult Function(_FailureAppLanguageState value)? failure, TResult Function(_SuccessfulAppLanguageState value)? successful, required TResult orElse(), }) { if (successful != null) { return successful(this); } return orElse(); } } abstract class _SuccessfulAppLanguageState extends AppLanguageState { const factory _SuccessfulAppLanguageState() = _$_SuccessfulAppLanguageState; const _SuccessfulAppLanguageState._() : super._(); } /// @nodoc mixin _$AppLanguageEvent { @optionalTypeArgs TResult when<TResult extends Object?>({ required TResult Function(Locale newLocale) changeToLocale, required TResult Function() languageToggled, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({ TResult Function(Locale newLocale)? changeToLocale, TResult Function()? languageToggled, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult maybeWhen<TResult extends Object?>({ TResult Function(Locale newLocale)? changeToLocale, TResult Function()? languageToggled, required TResult orElse(), }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult map<TResult extends Object?>({ required TResult Function(_ChangeToLocaleAppLanguageEvent value) changeToLocale, required TResult Function(_LanguageToggledAppLanguageEvent value) languageToggled, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult? mapOrNull<TResult extends Object?>({ TResult Function(_ChangeToLocaleAppLanguageEvent value)? changeToLocale, TResult Function(_LanguageToggledAppLanguageEvent value)? languageToggled, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult maybeMap<TResult extends Object?>({ TResult Function(_ChangeToLocaleAppLanguageEvent value)? changeToLocale, TResult Function(_LanguageToggledAppLanguageEvent value)? languageToggled, required TResult orElse(), }) => throw _privateConstructorUsedError; } /// @nodoc abstract class $AppLanguageEventCopyWith<$Res> { factory $AppLanguageEventCopyWith( AppLanguageEvent value, $Res Function(AppLanguageEvent) then) = _$AppLanguageEventCopyWithImpl<$Res>; } /// @nodoc class _$AppLanguageEventCopyWithImpl<$Res> implements $AppLanguageEventCopyWith<$Res> { _$AppLanguageEventCopyWithImpl(this._value, this._then); final AppLanguageEvent _value; // ignore: unused_field final $Res Function(AppLanguageEvent) _then; } /// @nodoc abstract class _$$_ChangeToLocaleAppLanguageEventCopyWith<$Res> { factory _$$_ChangeToLocaleAppLanguageEventCopyWith( _$_ChangeToLocaleAppLanguageEvent value, $Res Function(_$_ChangeToLocaleAppLanguageEvent) then) = __$$_ChangeToLocaleAppLanguageEventCopyWithImpl<$Res>; $Res call({Locale newLocale}); } /// @nodoc class __$$_ChangeToLocaleAppLanguageEventCopyWithImpl<$Res> extends _$AppLanguageEventCopyWithImpl<$Res> implements _$$_ChangeToLocaleAppLanguageEventCopyWith<$Res> { __$$_ChangeToLocaleAppLanguageEventCopyWithImpl( _$_ChangeToLocaleAppLanguageEvent _value, $Res Function(_$_ChangeToLocaleAppLanguageEvent) _then) : super(_value, (v) => _then(v as _$_ChangeToLocaleAppLanguageEvent)); @override _$_ChangeToLocaleAppLanguageEvent get _value => super._value as _$_ChangeToLocaleAppLanguageEvent; @override $Res call({ Object? newLocale = freezed, }) { return _then(_$_ChangeToLocaleAppLanguageEvent( newLocale == freezed ? _value.newLocale : newLocale // ignore: cast_nullable_to_non_nullable as Locale, )); } } /// @nodoc class _$_ChangeToLocaleAppLanguageEvent extends _ChangeToLocaleAppLanguageEvent { const _$_ChangeToLocaleAppLanguageEvent(this.newLocale) : super._(); @override final Locale newLocale; @override String toString() { return 'AppLanguageEvent.changeToLocale(newLocale: $newLocale)'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_ChangeToLocaleAppLanguageEvent && const DeepCollectionEquality().equals(other.newLocale, newLocale)); } @override int get hashCode => Object.hash(runtimeType, const DeepCollectionEquality().hash(newLocale)); @JsonKey(ignore: true) @override _$$_ChangeToLocaleAppLanguageEventCopyWith<_$_ChangeToLocaleAppLanguageEvent> get copyWith => __$$_ChangeToLocaleAppLanguageEventCopyWithImpl< _$_ChangeToLocaleAppLanguageEvent>(this, _$identity); @override @optionalTypeArgs TResult when<TResult extends Object?>({ required TResult Function(Locale newLocale) changeToLocale, required TResult Function() languageToggled, }) { return changeToLocale(newLocale); } @override @optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({ TResult Function(Locale newLocale)? changeToLocale, TResult Function()? languageToggled, }) { return changeToLocale?.call(newLocale); } @override @optionalTypeArgs TResult maybeWhen<TResult extends Object?>({ TResult Function(Locale newLocale)? changeToLocale, TResult Function()? languageToggled, required TResult orElse(), }) { if (changeToLocale != null) { return changeToLocale(newLocale); } return orElse(); } @override @optionalTypeArgs TResult map<TResult extends Object?>({ required TResult Function(_ChangeToLocaleAppLanguageEvent value) changeToLocale, required TResult Function(_LanguageToggledAppLanguageEvent value) languageToggled, }) { return changeToLocale(this); } @override @optionalTypeArgs TResult? mapOrNull<TResult extends Object?>({ TResult Function(_ChangeToLocaleAppLanguageEvent value)? changeToLocale, TResult Function(_LanguageToggledAppLanguageEvent value)? languageToggled, }) { return changeToLocale?.call(this); } @override @optionalTypeArgs TResult maybeMap<TResult extends Object?>({ TResult Function(_ChangeToLocaleAppLanguageEvent value)? changeToLocale, TResult Function(_LanguageToggledAppLanguageEvent value)? languageToggled, required TResult orElse(), }) { if (changeToLocale != null) { return changeToLocale(this); } return orElse(); } } abstract class _ChangeToLocaleAppLanguageEvent extends AppLanguageEvent { const factory _ChangeToLocaleAppLanguageEvent(final Locale newLocale) = _$_ChangeToLocaleAppLanguageEvent; const _ChangeToLocaleAppLanguageEvent._() : super._(); Locale get newLocale; @JsonKey(ignore: true) _$$_ChangeToLocaleAppLanguageEventCopyWith<_$_ChangeToLocaleAppLanguageEvent> get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class _$$_LanguageToggledAppLanguageEventCopyWith<$Res> { factory _$$_LanguageToggledAppLanguageEventCopyWith( _$_LanguageToggledAppLanguageEvent value, $Res Function(_$_LanguageToggledAppLanguageEvent) then) = __$$_LanguageToggledAppLanguageEventCopyWithImpl<$Res>; } /// @nodoc class __$$_LanguageToggledAppLanguageEventCopyWithImpl<$Res> extends _$AppLanguageEventCopyWithImpl<$Res> implements _$$_LanguageToggledAppLanguageEventCopyWith<$Res> { __$$_LanguageToggledAppLanguageEventCopyWithImpl( _$_LanguageToggledAppLanguageEvent _value, $Res Function(_$_LanguageToggledAppLanguageEvent) _then) : super(_value, (v) => _then(v as _$_LanguageToggledAppLanguageEvent)); @override _$_LanguageToggledAppLanguageEvent get _value => super._value as _$_LanguageToggledAppLanguageEvent; } /// @nodoc class _$_LanguageToggledAppLanguageEvent extends _LanguageToggledAppLanguageEvent { const _$_LanguageToggledAppLanguageEvent() : super._(); @override String toString() { return 'AppLanguageEvent.languageToggled()'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_LanguageToggledAppLanguageEvent); } @override int get hashCode => runtimeType.hashCode; @override @optionalTypeArgs TResult when<TResult extends Object?>({ required TResult Function(Locale newLocale) changeToLocale, required TResult Function() languageToggled, }) { return languageToggled(); } @override @optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({ TResult Function(Locale newLocale)? changeToLocale, TResult Function()? languageToggled, }) { return languageToggled?.call(); } @override @optionalTypeArgs TResult maybeWhen<TResult extends Object?>({ TResult Function(Locale newLocale)? changeToLocale, TResult Function()? languageToggled, required TResult orElse(), }) { if (languageToggled != null) { return languageToggled(); } return orElse(); } @override @optionalTypeArgs TResult map<TResult extends Object?>({ required TResult Function(_ChangeToLocaleAppLanguageEvent value) changeToLocale, required TResult Function(_LanguageToggledAppLanguageEvent value) languageToggled, }) { return languageToggled(this); } @override @optionalTypeArgs TResult? mapOrNull<TResult extends Object?>({ TResult Function(_ChangeToLocaleAppLanguageEvent value)? changeToLocale, TResult Function(_LanguageToggledAppLanguageEvent value)? languageToggled, }) { return languageToggled?.call(this); } @override @optionalTypeArgs TResult maybeMap<TResult extends Object?>({ TResult Function(_ChangeToLocaleAppLanguageEvent value)? changeToLocale, TResult Function(_LanguageToggledAppLanguageEvent value)? languageToggled, required TResult orElse(), }) { if (languageToggled != null) { return languageToggled(this); } return orElse(); } } abstract class _LanguageToggledAppLanguageEvent extends AppLanguageEvent { const factory _LanguageToggledAppLanguageEvent() = _$_LanguageToggledAppLanguageEvent; const _LanguageToggledAppLanguageEvent._() : super._(); }
0
mirrored_repositories/find_anime/lib/src/feature
mirrored_repositories/find_anime/lib/src/feature/search/search.dart
export 'bloc/search_bloc.dart'; export 'view/search_page.dart';
0
mirrored_repositories/find_anime/lib/src/feature/search
mirrored_repositories/find_anime/lib/src/feature/search/view/search_view.dart
import 'package:breakpoint/breakpoint.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dropzone/flutter_dropzone.dart'; import 'package:pasteboard/pasteboard.dart'; import 'package:tracemoe_repository/tracemoe_repository.dart'; import 'package:waterfall_flow/waterfall_flow.dart'; import '../../../core/generated/localization/l10n.dart'; import '../../localization/app_language_bloc.dart'; import '../../theme/app_theme_bloc.dart'; import '../bloc/dropzone_cubit.dart'; import '../search.dart'; import '../widgets/result_list_item.dart'; class SearchView extends StatelessWidget { const SearchView({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return BlocConsumer<SearchBloc, SearchState>( builder: (context, state) { return state.when( initial: () => const InitialSearchView(), loading: () => const BuildLoadingIndicator(), failure: (message) => BuildError(errorText: message), showingResult: (result) => ResultList(result: result), userInputFailure: (_) => const InitialSearchView(), ); }, listener: (context, state) { state.maybeWhen( userInputFailure: (message) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text(message), ), ); }, orElse: () { return; }, ); }, ); } } /// View with search view, initial view class InitialSearchView extends StatefulWidget { const InitialSearchView({ Key? key, }) : super(key: key); @override State<InitialSearchView> createState() => _InitialSearchViewState(); } class _InitialSearchViewState extends State<InitialSearchView> { final TextEditingController _textEditingController = TextEditingController(); @override Widget build(BuildContext context) { MediaQueryData mediaQuery = MediaQuery.of(context); bool isMobile = mediaQuery.size.width < 600; return Scaffold( appBar: AppBar( actions: [ IconButton( tooltip: 'Change app language', onPressed: () => context.read<AppLanguageBloc>().add( const AppLanguageEvent.languageToggled(), ), icon: const Icon(Icons.language_outlined), ), const SizedBox( width: 24.0, ), IconButton( tooltip: 'Change app theme', onPressed: () => context.read<AppThemeBloc>().add( const AppThemeEvent.themeToggled(), ), icon: const Icon(Icons.brightness_6_outlined), ), ], ), body: SafeArea( minimum: EdgeInsets.symmetric( horizontal: isMobile ? 12.0 : mediaQuery.size.longestSide / 10, ), child: Focus( autofocus: true, canRequestFocus: true, onKey: (_, event) { if (event.isControlPressed && event.physicalKey == PhysicalKeyboardKey.keyV && !event.repeat) { context.read<SearchBloc>().add( SearchEvent.pastedContent( Pasteboard.image, Pasteboard.text, ), ); } return KeyEventResult.ignored; }, child: Stack( children: [ if (kIsWeb) DropzoneView( operation: DragOperation.move, onCreated: context.read<DropZoneCubit>().setController, onDrop: (file) => context .read<SearchBloc>() .add(SearchEvent.searchViaFile(file)), onError: print, ), Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Text( S.of(context).newSearch, style: Theme.of(context) .textTheme .headline4! .copyWith(fontSize: 24.0), ), const SizedBox( height: 8.0, ), Text( S.of(context).newSearchHint, textAlign: TextAlign.center, style: Theme.of(context) .textTheme .headline4! .copyWith(fontSize: 18.0), ), Padding( padding: const EdgeInsets.all(28.0), child: SizedBox( width: double.infinity, child: TextFormField( controller: _textEditingController, textInputAction: TextInputAction.next, style: Theme.of(context).textTheme.headline4, decoration: InputDecoration( labelText: S.of(context).enterImageUrl, helperText: S.of(context).enterImageUrlHint, ), ), ), ), ButtonBar( alignment: MainAxisAlignment.center, children: [ if (kIsWeb) SizedBox( height: 42.0, width: mediaQuery.size.width / 4, child: OutlinedButton( onPressed: () async { // awaiting to pick up file final htmlFile = (await context .read<DropZoneCubit>() .state .getControllerOrNull! .pickFiles()) .first; if (!mounted) return; // widget is not at tree context.read<SearchBloc>().add( SearchEvent.searchViaFile((await context .read<DropZoneCubit>() .state .convertFile(htmlFile))!), ); }, child: Text(S.of(context).selectFileButtonText), ), ), SizedBox( height: 42.0, width: mediaQuery.size.width / 4, child: ElevatedButton( onPressed: () => context.read<SearchBloc>().add( SearchEvent.searchViaDirectUrl( _textEditingController.value.text, ), ), child: Text(S.of(context).searchButtonText), ), ), ], ), ], ), ], ), ), ), ); } } /// Loading indicator class BuildLoadingIndicator extends StatelessWidget { const BuildLoadingIndicator({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return const Scaffold(body: Center(child: CircularProgressIndicator())); } } /// Show error text class BuildError extends StatelessWidget { const BuildError({Key? key, required this.errorText}) : super(key: key); final String errorText; @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ Text( errorText, style: Theme.of(context) .textTheme .headline4! .copyWith(fontSize: 24.0), ), Padding( padding: const EdgeInsets.all(18.0), child: SizedBox( height: 42.0, child: ElevatedButton( onPressed: () => context .read<SearchBloc>() .add(const SearchEvent.openSearch()), child: Text(S.of(context).openSearchButton), ), ), ), ], ), ), ); } } class ResultList extends StatelessWidget { const ResultList({Key? key, required this.result}) : super(key: key); final List<Result> result; @override Widget build(BuildContext context) { return BreakpointBuilder( builder: (context, breakpoint) { final LayoutClass device = breakpoint.device; final int columns = device == LayoutClass.desktop ? 2 : 1; return Scaffold( body: WaterfallFlow.builder( itemCount: result.length, padding: EdgeInsets.only( top: device != LayoutClass.desktop ? MediaQuery.of(context).padding.top : 0.0, left: getPaddings(breakpoint.window), right: getPaddings(breakpoint.window), ), //cacheExtent: 0.0, gridDelegate: SliverWaterfallFlowDelegateWithFixedCrossAxisCount( crossAxisCount: columns, crossAxisSpacing: 5.0, mainAxisSpacing: 5.0, lastChildLayoutTypeBuilder: (index) => index == result.length ? LastChildLayoutType.foot : LastChildLayoutType.none, ), itemBuilder: (context, index) => ResultListItem( result: result[index], device: breakpoint.device, ), ), floatingActionButton: FloatingActionButton.extended( onPressed: () => context.read<SearchBloc>().add(const SearchEvent.openSearch()), label: Text(S.of(context).openSearchButton), icon: const Icon(Icons.search_outlined), ), ); }, ); } double getPaddings(WindowSize size) { switch (size) { case WindowSize.xsmall: return 12.0; case WindowSize.small: return 18.0; case WindowSize.medium: return 24.0; case WindowSize.large: return 240.0; case WindowSize.xlarge: return 546.0; } } }
0
mirrored_repositories/find_anime/lib/src/feature/search
mirrored_repositories/find_anime/lib/src/feature/search/view/search_page.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:tracemoe_repository/tracemoe_repository.dart'; import '../bloc/dropzone_cubit.dart'; import '../search.dart'; import 'search_view.dart'; class SearchScreen extends StatelessWidget { const SearchScreen({Key? key, this.traceMoeRepository}) : super(key: key); final TraceMoeRepository? traceMoeRepository; @override Widget build(BuildContext context) { return MultiBlocProvider( providers: [ BlocProvider<SearchBloc>( create: (_) => SearchBloc(traceMoeRepository ?? TraceMoeRepository()), ), BlocProvider<DropZoneCubit>(create: (_) => DropZoneCubit()), ], child: const SearchView(), ); } }
0
mirrored_repositories/find_anime/lib/src/feature/search
mirrored_repositories/find_anime/lib/src/feature/search/widgets/result_list_item.dart
import 'package:breakpoint/breakpoint.dart'; import 'package:colorize_text_avatar/colorize_text_avatar.dart'; import 'package:duration/duration.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:tracemoe_repository/tracemoe_repository.dart'; import 'package:url_launcher/url_launcher.dart'; import 'package:video_player/video_player.dart'; import '../../../core/generated/localization/l10n.dart'; class ResultListItem extends StatelessWidget { const ResultListItem({ Key? key, required this.result, required this.device, }) : super(key: key); final Result result; final LayoutClass device; @override Widget build(BuildContext context) { final double verticalPadding = device == LayoutClass.desktop ? 12.0 : 8.0; final double horizontalPadding = device == LayoutClass.desktop ? 24.0 : 8.0; return Padding( padding: EdgeInsets.symmetric( vertical: verticalPadding, horizontal: horizontalPadding, ), child: Card( clipBehavior: Clip.antiAlias, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: const [ Padding( padding: EdgeInsets.symmetric( horizontal: 12.0, vertical: 20.0, ), child: ResultTitleBlock(), ), ResultMediaViewer(), Padding( padding: EdgeInsets.all(16.0), child: ResultInfoText(), ), Padding( padding: EdgeInsets.all(16.0), child: ResultEpisodeInfo(), ), Padding( padding: EdgeInsets.all(16.0), child: ResultButtonBar(), ), ], ), ), ); } static Result getResultOf(BuildContext context) => context.findAncestorWidgetOfExactType<ResultListItem>()!.result; } class ResultButtonBar extends StatelessWidget { const ResultButtonBar({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { return ButtonBar( children: [ SizedBox( height: 42.0, child: OutlinedButton( onPressed: () => launchUrl(Uri.parse( 'https://anilist.co/anime/${ResultListItem.getResultOf(context).idMal}', )), child: Text(S.of(context).viewInAnilist), ), ), SizedBox( height: 42.0, child: ElevatedButton( onPressed: () { Clipboard.setData( ClipboardData( text: ResultListItem.getResultOf(context).romajiName ?? ResultListItem.getResultOf(context).japaneseName ?? '', ), ); ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Text(S.of(context).copiedText), behavior: SnackBarBehavior.floating, )); }, child: Text(S.of(context).copyNameButton), ), ), ], ); } } class ResultTitleBlock extends StatelessWidget { const ResultTitleBlock({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { return ListTile( leading: TextAvatar( shape: Shape.Circular, text: ResultListItem.getResultOf(context).romajiName ?? S.of(context).noRomajiName, ), title: SelectableText( ResultListItem.getResultOf(context).romajiName ?? S.of(context).noRomajiName, style: TextStyle( fontSize: 24.0, fontFamily: 'Roboto', color: Theme.of(context).colorScheme.onBackground, ), ), subtitle: SelectableText( ResultListItem.getResultOf(context).japaneseName ?? S.of(context).noJapaneseName, style: TextStyle( fontSize: 14.0, fontFamily: 'Roboto', color: Theme.of(context).colorScheme.onBackground, ), ), ); } } class ResultMediaViewer extends StatefulWidget { const ResultMediaViewer({ Key? key, }) : super(key: key); @override State<ResultMediaViewer> createState() => _ResultMediaViewerState(); } class _ResultMediaViewerState extends State<ResultMediaViewer> { late VideoPlayerController _controller; @override void initState() { _controller = VideoPlayerController.network( ResultListItem.getResultOf(context).video, )..initialize().then((value) { _controller.setVolume(0.0).then((_) => _controller.pause()); setState; }); super.initState(); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return LayoutBuilder( builder: (context, constraints) { return SizedBox( width: double.infinity, height: constraints.maxWidth / 1.78, // 1.78 cuz aspect ratio is 16:9 child: Stack( alignment: AlignmentDirectional.bottomCenter, children: [ MouseRegion( onExit: (event) async { await _controller.setLooping(false); await _controller.setVolume(0.0); await _controller.pause(); }, onHover: (event) async { await _controller.setLooping(true); await _controller.setVolume(0.1); await _controller.play(); }, child: VideoPlayer( _controller, ), ), VideoProgressIndicator( _controller, allowScrubbing: true, padding: EdgeInsets.zero, ), ], ), ); }, ); } } class ResultInfoText extends StatelessWidget { const ResultInfoText({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( S .of(context) .similarityText(ResultListItem.getResultOf(context).similarity), style: TextStyle( fontSize: 22.0, fontFamily: 'Roboto', color: Theme.of(context).colorScheme.onBackground, ), ), const SizedBox( height: 8.0, ), if (ResultListItem.getResultOf(context).adultOnly) Text( S.of(context).adultOnly, style: TextStyle( fontSize: 16.0, fontFamily: 'Roboto', color: Theme.of(context).colorScheme.error, ), ), ], ); } } class ResultEpisodeInfo extends StatelessWidget { const ResultEpisodeInfo({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { return Column( children: [ Text( S.of(context).episodeText( ResultListItem.getResultOf(context).episode.toInt(), prettyDuration( Duration( seconds: ResultListItem.getResultOf(context).moment.toInt(), ), abbreviated: true, ), ), style: TextStyle( fontSize: 18.0, fontFamily: 'Roboto', color: Theme.of(context).colorScheme.onBackground, ), ), ], ); } }
0
mirrored_repositories/find_anime/lib/src/feature/search
mirrored_repositories/find_anime/lib/src/feature/search/bloc/search_bloc.dart
import 'dart:typed_data'; import 'package:bloc_concurrency/bloc_concurrency.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:mime/mime.dart'; import 'package:tracemoe_api/tracemoe_api.dart'; import 'package:tracemoe_repository/tracemoe_repository.dart'; import '../../../core/generated/localization/l10n.dart'; part 'search_bloc.freezed.dart'; @freezed class SearchState with _$SearchState { const SearchState._(); /// Initial state of screen const factory SearchState.initial() = _InitialSearchState; /// Loading data const factory SearchState.loading() = _LoadingSearchState; /// Users input (file or url) is incorrect const factory SearchState.userInputFailure(String message) = _UserInputFailureSearchState; /// Something went from const factory SearchState.failure({ @Default('An error has occurred') String message, }) = _FailureSearchState; /// Show result const factory SearchState.showingResult(List<Result> result) = _ShowingResultSearchState; } @freezed class SearchEvent with _$SearchEvent { const SearchEvent._(); /// User want to search via image url const factory SearchEvent.searchViaDirectUrl(String imageUrl) = _SearchViaDirectUrlSearchEvent; /// User want to search via file const factory SearchEvent.searchViaFile(Uint8List bytes) = _SearchViaFileSearchEvent; /// User want to open search (e.x. from result) const factory SearchEvent.openSearch() = _OpenSearchSearchEvent; /// User pasted some content (url or file) const factory SearchEvent.pastedContent( Future<Uint8List?>? mediaBytes, Future<String?>? text, ) = _PastedContentSearchEvent; } class SearchBloc extends Bloc<SearchEvent, SearchState> { final TraceMoeRepository _repository; SearchBloc(TraceMoeRepository repository) : _repository = repository, super(const SearchState.initial()) { on<SearchEvent>( (event, emit) => event.map<Future<void>>( searchViaDirectUrl: (event) => _searchViaDirectUrl(event, emit), searchViaFile: (event) => _searchViaFile(event, emit), openSearch: (event) => _openSearch(event, emit), pastedContent: (event) => _pastedContent(event, emit), ), transformer: droppable<SearchEvent>(), ); } /// Starts search via image url Future<void> _searchViaDirectUrl( _SearchViaDirectUrlSearchEvent event, Emitter<SearchState> emitter, ) async { emitter(const SearchState.loading()); try { final List<Result> resultList = await __makeSearchByUrl(event.imageUrl); return emitter(SearchState.showingResult(resultList)); } on InvalidImageUrlFailure { emitter(const SearchState.userInputFailure('Entered URL is not direct')); } on Object catch (e, _) { emitter(const SearchState.failure(message: 'Something went wrong')); rethrow; } } /// Starts search via file Future<void> _searchViaFile( _SearchViaFileSearchEvent event, Emitter<SearchState> emitter, ) async { emitter(const SearchState.loading()); try { final List<Result> resultList = await __makeSearchByFile(event.bytes); return emitter(SearchState.showingResult(resultList)); } on InvalidImageUrlFailure { return emitter( const SearchState.userInputFailure('Cant search with given file'), ); } on Object { emitter( const SearchState.userInputFailure('Something went wrong'), ); rethrow; } } /// Opens search view via resetting state Future<void> _openSearch( _OpenSearchSearchEvent event, Emitter<SearchState> emitter, ) async { emitter(const SearchState.initial()); } /// Makes search via file or url depend on pasted content Future<void> _pastedContent( _PastedContentSearchEvent event, Emitter<SearchState> emitter, ) async { // show loading while reading data from clipboard emitter(const SearchState.loading()); // we do not know what user pasted final Uint8List? bytes = await event.mediaBytes; final String? url = await event.text; if (bytes == null && url == null) { return emitter( const SearchState.failure( message: 'Error while reading clipboard', ), ); } else { try { final List<Result> resultList = await (url != null ? __makeSearchByUrl(url) : __makeSearchByFile(bytes!)); // only one item can be null return emitter(SearchState.showingResult(resultList)); } on InvalidImageUrlFailure { emitter( SearchState.failure( message: 'Pasted content cannot be proceed\n\n' 'Url: $url\n\nDetected file: ${bytes != null}', ), ); } on Object { emitter(const SearchState.failure()); rethrow; } } } /// Perform search via image url. /// /// Will throw [InvalidImageUrlFailure] if imageUrl is not absolute Future<List<Result>> __makeSearchByUrl(String imageURL) async { if (Uri.parse(imageURL).isAbsolute) { List<Result> resultList = await _repository.getResultByImageUrl(imageURL); return resultList; } else { throw InvalidImageUrlFailure(); } } /// Perform search via file. /// /// Media can be an **image/\***, **video/\*** or **gif**. /// If a different file type is sent, [InvalidImageUrlFailure] will be thrown. /// /// May throw exceptions according to the API documentation: /// https://soruly.github.io/trace.moe-api/#/docs?id=error-codes Future<List<Result>> __makeSearchByFile( Uint8List bytes, ) async { String mimeType = lookupMimeType( '', // no path for file, look for mime with bytes headerBytes: bytes, ) ?? 'application/octet-stream'; List<Result> resultList = await _repository.getResultByFile( bytes, mimeType: mimeType, ); return resultList; } /// Use for get localed text for error description String __getErrorText(Object e) { if (e is InvalidImageUrlFailure) { return S().error400; } else if (e is SearchQuotaDepletedFailure) { return S().error402; } else if (e is SearchInternalErrorFailure) { return S().error500; } else if (e is SearchQueueIsFullFailure) { return S().error503; } else if (e is SearchServerOverloadFailure) { return S().error504; } else { return S().errorUnknown; } } }
0
mirrored_repositories/find_anime/lib/src/feature/search
mirrored_repositories/find_anime/lib/src/feature/search/bloc/dropzone_cubit.freezed.dart
// coverage:ignore-file // GENERATED CODE - DO NOT MODIFY BY HAND // ignore_for_file: type=lint // ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target part of 'dropzone_cubit.dart'; // ************************************************************************** // FreezedGenerator // ************************************************************************** T _$identity<T>(T value) => value; final _privateConstructorUsedError = UnsupportedError( 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#custom-getters-and-methods'); /// @nodoc mixin _$DropZoneState { @optionalTypeArgs TResult when<TResult extends Object?>({ required TResult Function() initial, required TResult Function(DropzoneViewController controller) createdController, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({ TResult Function()? initial, TResult Function(DropzoneViewController controller)? createdController, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult maybeWhen<TResult extends Object?>({ TResult Function()? initial, TResult Function(DropzoneViewController controller)? createdController, required TResult orElse(), }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult map<TResult extends Object?>({ required TResult Function(_InitialState value) initial, required TResult Function(_CreatedControllerDropZoneState value) createdController, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult? mapOrNull<TResult extends Object?>({ TResult Function(_InitialState value)? initial, TResult Function(_CreatedControllerDropZoneState value)? createdController, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult maybeMap<TResult extends Object?>({ TResult Function(_InitialState value)? initial, TResult Function(_CreatedControllerDropZoneState value)? createdController, required TResult orElse(), }) => throw _privateConstructorUsedError; } /// @nodoc abstract class $DropZoneStateCopyWith<$Res> { factory $DropZoneStateCopyWith( DropZoneState value, $Res Function(DropZoneState) then) = _$DropZoneStateCopyWithImpl<$Res>; } /// @nodoc class _$DropZoneStateCopyWithImpl<$Res> implements $DropZoneStateCopyWith<$Res> { _$DropZoneStateCopyWithImpl(this._value, this._then); final DropZoneState _value; // ignore: unused_field final $Res Function(DropZoneState) _then; } /// @nodoc abstract class _$$_InitialStateCopyWith<$Res> { factory _$$_InitialStateCopyWith( _$_InitialState value, $Res Function(_$_InitialState) then) = __$$_InitialStateCopyWithImpl<$Res>; } /// @nodoc class __$$_InitialStateCopyWithImpl<$Res> extends _$DropZoneStateCopyWithImpl<$Res> implements _$$_InitialStateCopyWith<$Res> { __$$_InitialStateCopyWithImpl( _$_InitialState _value, $Res Function(_$_InitialState) _then) : super(_value, (v) => _then(v as _$_InitialState)); @override _$_InitialState get _value => super._value as _$_InitialState; } /// @nodoc class _$_InitialState extends _InitialState { const _$_InitialState() : super._(); @override String toString() { return 'DropZoneState.initial()'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_InitialState); } @override int get hashCode => runtimeType.hashCode; @override @optionalTypeArgs TResult when<TResult extends Object?>({ required TResult Function() initial, required TResult Function(DropzoneViewController controller) createdController, }) { return initial(); } @override @optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({ TResult Function()? initial, TResult Function(DropzoneViewController controller)? createdController, }) { return initial?.call(); } @override @optionalTypeArgs TResult maybeWhen<TResult extends Object?>({ TResult Function()? initial, TResult Function(DropzoneViewController controller)? createdController, required TResult orElse(), }) { if (initial != null) { return initial(); } return orElse(); } @override @optionalTypeArgs TResult map<TResult extends Object?>({ required TResult Function(_InitialState value) initial, required TResult Function(_CreatedControllerDropZoneState value) createdController, }) { return initial(this); } @override @optionalTypeArgs TResult? mapOrNull<TResult extends Object?>({ TResult Function(_InitialState value)? initial, TResult Function(_CreatedControllerDropZoneState value)? createdController, }) { return initial?.call(this); } @override @optionalTypeArgs TResult maybeMap<TResult extends Object?>({ TResult Function(_InitialState value)? initial, TResult Function(_CreatedControllerDropZoneState value)? createdController, required TResult orElse(), }) { if (initial != null) { return initial(this); } return orElse(); } } abstract class _InitialState extends DropZoneState { const factory _InitialState() = _$_InitialState; const _InitialState._() : super._(); } /// @nodoc abstract class _$$_CreatedControllerDropZoneStateCopyWith<$Res> { factory _$$_CreatedControllerDropZoneStateCopyWith( _$_CreatedControllerDropZoneState value, $Res Function(_$_CreatedControllerDropZoneState) then) = __$$_CreatedControllerDropZoneStateCopyWithImpl<$Res>; $Res call({DropzoneViewController controller}); } /// @nodoc class __$$_CreatedControllerDropZoneStateCopyWithImpl<$Res> extends _$DropZoneStateCopyWithImpl<$Res> implements _$$_CreatedControllerDropZoneStateCopyWith<$Res> { __$$_CreatedControllerDropZoneStateCopyWithImpl( _$_CreatedControllerDropZoneState _value, $Res Function(_$_CreatedControllerDropZoneState) _then) : super(_value, (v) => _then(v as _$_CreatedControllerDropZoneState)); @override _$_CreatedControllerDropZoneState get _value => super._value as _$_CreatedControllerDropZoneState; @override $Res call({ Object? controller = freezed, }) { return _then(_$_CreatedControllerDropZoneState( controller == freezed ? _value.controller : controller // ignore: cast_nullable_to_non_nullable as DropzoneViewController, )); } } /// @nodoc class _$_CreatedControllerDropZoneState extends _CreatedControllerDropZoneState { const _$_CreatedControllerDropZoneState(this.controller) : super._(); @override final DropzoneViewController controller; @override String toString() { return 'DropZoneState.createdController(controller: $controller)'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_CreatedControllerDropZoneState && const DeepCollectionEquality() .equals(other.controller, controller)); } @override int get hashCode => Object.hash(runtimeType, const DeepCollectionEquality().hash(controller)); @JsonKey(ignore: true) @override _$$_CreatedControllerDropZoneStateCopyWith<_$_CreatedControllerDropZoneState> get copyWith => __$$_CreatedControllerDropZoneStateCopyWithImpl< _$_CreatedControllerDropZoneState>(this, _$identity); @override @optionalTypeArgs TResult when<TResult extends Object?>({ required TResult Function() initial, required TResult Function(DropzoneViewController controller) createdController, }) { return createdController(controller); } @override @optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({ TResult Function()? initial, TResult Function(DropzoneViewController controller)? createdController, }) { return createdController?.call(controller); } @override @optionalTypeArgs TResult maybeWhen<TResult extends Object?>({ TResult Function()? initial, TResult Function(DropzoneViewController controller)? createdController, required TResult orElse(), }) { if (createdController != null) { return createdController(controller); } return orElse(); } @override @optionalTypeArgs TResult map<TResult extends Object?>({ required TResult Function(_InitialState value) initial, required TResult Function(_CreatedControllerDropZoneState value) createdController, }) { return createdController(this); } @override @optionalTypeArgs TResult? mapOrNull<TResult extends Object?>({ TResult Function(_InitialState value)? initial, TResult Function(_CreatedControllerDropZoneState value)? createdController, }) { return createdController?.call(this); } @override @optionalTypeArgs TResult maybeMap<TResult extends Object?>({ TResult Function(_InitialState value)? initial, TResult Function(_CreatedControllerDropZoneState value)? createdController, required TResult orElse(), }) { if (createdController != null) { return createdController(this); } return orElse(); } } abstract class _CreatedControllerDropZoneState extends DropZoneState { const factory _CreatedControllerDropZoneState( final DropzoneViewController controller) = _$_CreatedControllerDropZoneState; const _CreatedControllerDropZoneState._() : super._(); DropzoneViewController get controller; @JsonKey(ignore: true) _$$_CreatedControllerDropZoneStateCopyWith<_$_CreatedControllerDropZoneState> get copyWith => throw _privateConstructorUsedError; }
0
mirrored_repositories/find_anime/lib/src/feature/search
mirrored_repositories/find_anime/lib/src/feature/search/bloc/dropzone_cubit.dart
import 'dart:typed_data'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dropzone/flutter_dropzone.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; part 'dropzone_cubit.freezed.dart'; @freezed class DropZoneState with _$DropZoneState { const DropZoneState._(); DropzoneViewController? get getControllerOrNull => maybeWhen( createdController: (controller) => controller, orElse: () => null, ); Future<Uint8List?> convertFile(Object htmlFile) async => maybeWhen( createdController: (controller) async => await controller.getFileData(htmlFile), orElse: () => null, ); const factory DropZoneState.initial() = _InitialState; const factory DropZoneState.createdController( DropzoneViewController controller, ) = _CreatedControllerDropZoneState; } class DropZoneCubit extends Cubit<DropZoneState> { DropZoneCubit() : super(const DropZoneState.initial()); void setController(DropzoneViewController controller) { emit(DropZoneState.createdController(controller)); } }
0
mirrored_repositories/find_anime/lib/src/feature/search
mirrored_repositories/find_anime/lib/src/feature/search/bloc/search_bloc.freezed.dart
// coverage:ignore-file // GENERATED CODE - DO NOT MODIFY BY HAND // ignore_for_file: type=lint // ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target part of 'search_bloc.dart'; // ************************************************************************** // FreezedGenerator // ************************************************************************** T _$identity<T>(T value) => value; final _privateConstructorUsedError = UnsupportedError( 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#custom-getters-and-methods'); /// @nodoc mixin _$SearchState { @optionalTypeArgs TResult when<TResult extends Object?>({ required TResult Function() initial, required TResult Function() loading, required TResult Function(String message) userInputFailure, required TResult Function(String message) failure, required TResult Function(List<Result> result) showingResult, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({ TResult Function()? initial, TResult Function()? loading, TResult Function(String message)? userInputFailure, TResult Function(String message)? failure, TResult Function(List<Result> result)? showingResult, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult maybeWhen<TResult extends Object?>({ TResult Function()? initial, TResult Function()? loading, TResult Function(String message)? userInputFailure, TResult Function(String message)? failure, TResult Function(List<Result> result)? showingResult, required TResult orElse(), }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult map<TResult extends Object?>({ required TResult Function(_InitialSearchState value) initial, required TResult Function(_LoadingSearchState value) loading, required TResult Function(_UserInputFailureSearchState value) userInputFailure, required TResult Function(_FailureSearchState value) failure, required TResult Function(_ShowingResultSearchState value) showingResult, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult? mapOrNull<TResult extends Object?>({ TResult Function(_InitialSearchState value)? initial, TResult Function(_LoadingSearchState value)? loading, TResult Function(_UserInputFailureSearchState value)? userInputFailure, TResult Function(_FailureSearchState value)? failure, TResult Function(_ShowingResultSearchState value)? showingResult, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult maybeMap<TResult extends Object?>({ TResult Function(_InitialSearchState value)? initial, TResult Function(_LoadingSearchState value)? loading, TResult Function(_UserInputFailureSearchState value)? userInputFailure, TResult Function(_FailureSearchState value)? failure, TResult Function(_ShowingResultSearchState value)? showingResult, required TResult orElse(), }) => throw _privateConstructorUsedError; } /// @nodoc abstract class $SearchStateCopyWith<$Res> { factory $SearchStateCopyWith( SearchState value, $Res Function(SearchState) then) = _$SearchStateCopyWithImpl<$Res>; } /// @nodoc class _$SearchStateCopyWithImpl<$Res> implements $SearchStateCopyWith<$Res> { _$SearchStateCopyWithImpl(this._value, this._then); final SearchState _value; // ignore: unused_field final $Res Function(SearchState) _then; } /// @nodoc abstract class _$$_InitialSearchStateCopyWith<$Res> { factory _$$_InitialSearchStateCopyWith(_$_InitialSearchState value, $Res Function(_$_InitialSearchState) then) = __$$_InitialSearchStateCopyWithImpl<$Res>; } /// @nodoc class __$$_InitialSearchStateCopyWithImpl<$Res> extends _$SearchStateCopyWithImpl<$Res> implements _$$_InitialSearchStateCopyWith<$Res> { __$$_InitialSearchStateCopyWithImpl( _$_InitialSearchState _value, $Res Function(_$_InitialSearchState) _then) : super(_value, (v) => _then(v as _$_InitialSearchState)); @override _$_InitialSearchState get _value => super._value as _$_InitialSearchState; } /// @nodoc class _$_InitialSearchState extends _InitialSearchState { const _$_InitialSearchState() : super._(); @override String toString() { return 'SearchState.initial()'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_InitialSearchState); } @override int get hashCode => runtimeType.hashCode; @override @optionalTypeArgs TResult when<TResult extends Object?>({ required TResult Function() initial, required TResult Function() loading, required TResult Function(String message) userInputFailure, required TResult Function(String message) failure, required TResult Function(List<Result> result) showingResult, }) { return initial(); } @override @optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({ TResult Function()? initial, TResult Function()? loading, TResult Function(String message)? userInputFailure, TResult Function(String message)? failure, TResult Function(List<Result> result)? showingResult, }) { return initial?.call(); } @override @optionalTypeArgs TResult maybeWhen<TResult extends Object?>({ TResult Function()? initial, TResult Function()? loading, TResult Function(String message)? userInputFailure, TResult Function(String message)? failure, TResult Function(List<Result> result)? showingResult, required TResult orElse(), }) { if (initial != null) { return initial(); } return orElse(); } @override @optionalTypeArgs TResult map<TResult extends Object?>({ required TResult Function(_InitialSearchState value) initial, required TResult Function(_LoadingSearchState value) loading, required TResult Function(_UserInputFailureSearchState value) userInputFailure, required TResult Function(_FailureSearchState value) failure, required TResult Function(_ShowingResultSearchState value) showingResult, }) { return initial(this); } @override @optionalTypeArgs TResult? mapOrNull<TResult extends Object?>({ TResult Function(_InitialSearchState value)? initial, TResult Function(_LoadingSearchState value)? loading, TResult Function(_UserInputFailureSearchState value)? userInputFailure, TResult Function(_FailureSearchState value)? failure, TResult Function(_ShowingResultSearchState value)? showingResult, }) { return initial?.call(this); } @override @optionalTypeArgs TResult maybeMap<TResult extends Object?>({ TResult Function(_InitialSearchState value)? initial, TResult Function(_LoadingSearchState value)? loading, TResult Function(_UserInputFailureSearchState value)? userInputFailure, TResult Function(_FailureSearchState value)? failure, TResult Function(_ShowingResultSearchState value)? showingResult, required TResult orElse(), }) { if (initial != null) { return initial(this); } return orElse(); } } abstract class _InitialSearchState extends SearchState { const factory _InitialSearchState() = _$_InitialSearchState; const _InitialSearchState._() : super._(); } /// @nodoc abstract class _$$_LoadingSearchStateCopyWith<$Res> { factory _$$_LoadingSearchStateCopyWith(_$_LoadingSearchState value, $Res Function(_$_LoadingSearchState) then) = __$$_LoadingSearchStateCopyWithImpl<$Res>; } /// @nodoc class __$$_LoadingSearchStateCopyWithImpl<$Res> extends _$SearchStateCopyWithImpl<$Res> implements _$$_LoadingSearchStateCopyWith<$Res> { __$$_LoadingSearchStateCopyWithImpl( _$_LoadingSearchState _value, $Res Function(_$_LoadingSearchState) _then) : super(_value, (v) => _then(v as _$_LoadingSearchState)); @override _$_LoadingSearchState get _value => super._value as _$_LoadingSearchState; } /// @nodoc class _$_LoadingSearchState extends _LoadingSearchState { const _$_LoadingSearchState() : super._(); @override String toString() { return 'SearchState.loading()'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_LoadingSearchState); } @override int get hashCode => runtimeType.hashCode; @override @optionalTypeArgs TResult when<TResult extends Object?>({ required TResult Function() initial, required TResult Function() loading, required TResult Function(String message) userInputFailure, required TResult Function(String message) failure, required TResult Function(List<Result> result) showingResult, }) { return loading(); } @override @optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({ TResult Function()? initial, TResult Function()? loading, TResult Function(String message)? userInputFailure, TResult Function(String message)? failure, TResult Function(List<Result> result)? showingResult, }) { return loading?.call(); } @override @optionalTypeArgs TResult maybeWhen<TResult extends Object?>({ TResult Function()? initial, TResult Function()? loading, TResult Function(String message)? userInputFailure, TResult Function(String message)? failure, TResult Function(List<Result> result)? showingResult, required TResult orElse(), }) { if (loading != null) { return loading(); } return orElse(); } @override @optionalTypeArgs TResult map<TResult extends Object?>({ required TResult Function(_InitialSearchState value) initial, required TResult Function(_LoadingSearchState value) loading, required TResult Function(_UserInputFailureSearchState value) userInputFailure, required TResult Function(_FailureSearchState value) failure, required TResult Function(_ShowingResultSearchState value) showingResult, }) { return loading(this); } @override @optionalTypeArgs TResult? mapOrNull<TResult extends Object?>({ TResult Function(_InitialSearchState value)? initial, TResult Function(_LoadingSearchState value)? loading, TResult Function(_UserInputFailureSearchState value)? userInputFailure, TResult Function(_FailureSearchState value)? failure, TResult Function(_ShowingResultSearchState value)? showingResult, }) { return loading?.call(this); } @override @optionalTypeArgs TResult maybeMap<TResult extends Object?>({ TResult Function(_InitialSearchState value)? initial, TResult Function(_LoadingSearchState value)? loading, TResult Function(_UserInputFailureSearchState value)? userInputFailure, TResult Function(_FailureSearchState value)? failure, TResult Function(_ShowingResultSearchState value)? showingResult, required TResult orElse(), }) { if (loading != null) { return loading(this); } return orElse(); } } abstract class _LoadingSearchState extends SearchState { const factory _LoadingSearchState() = _$_LoadingSearchState; const _LoadingSearchState._() : super._(); } /// @nodoc abstract class _$$_UserInputFailureSearchStateCopyWith<$Res> { factory _$$_UserInputFailureSearchStateCopyWith( _$_UserInputFailureSearchState value, $Res Function(_$_UserInputFailureSearchState) then) = __$$_UserInputFailureSearchStateCopyWithImpl<$Res>; $Res call({String message}); } /// @nodoc class __$$_UserInputFailureSearchStateCopyWithImpl<$Res> extends _$SearchStateCopyWithImpl<$Res> implements _$$_UserInputFailureSearchStateCopyWith<$Res> { __$$_UserInputFailureSearchStateCopyWithImpl( _$_UserInputFailureSearchState _value, $Res Function(_$_UserInputFailureSearchState) _then) : super(_value, (v) => _then(v as _$_UserInputFailureSearchState)); @override _$_UserInputFailureSearchState get _value => super._value as _$_UserInputFailureSearchState; @override $Res call({ Object? message = freezed, }) { return _then(_$_UserInputFailureSearchState( message == freezed ? _value.message : message // ignore: cast_nullable_to_non_nullable as String, )); } } /// @nodoc class _$_UserInputFailureSearchState extends _UserInputFailureSearchState { const _$_UserInputFailureSearchState(this.message) : super._(); @override final String message; @override String toString() { return 'SearchState.userInputFailure(message: $message)'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_UserInputFailureSearchState && const DeepCollectionEquality().equals(other.message, message)); } @override int get hashCode => Object.hash(runtimeType, const DeepCollectionEquality().hash(message)); @JsonKey(ignore: true) @override _$$_UserInputFailureSearchStateCopyWith<_$_UserInputFailureSearchState> get copyWith => __$$_UserInputFailureSearchStateCopyWithImpl< _$_UserInputFailureSearchState>(this, _$identity); @override @optionalTypeArgs TResult when<TResult extends Object?>({ required TResult Function() initial, required TResult Function() loading, required TResult Function(String message) userInputFailure, required TResult Function(String message) failure, required TResult Function(List<Result> result) showingResult, }) { return userInputFailure(message); } @override @optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({ TResult Function()? initial, TResult Function()? loading, TResult Function(String message)? userInputFailure, TResult Function(String message)? failure, TResult Function(List<Result> result)? showingResult, }) { return userInputFailure?.call(message); } @override @optionalTypeArgs TResult maybeWhen<TResult extends Object?>({ TResult Function()? initial, TResult Function()? loading, TResult Function(String message)? userInputFailure, TResult Function(String message)? failure, TResult Function(List<Result> result)? showingResult, required TResult orElse(), }) { if (userInputFailure != null) { return userInputFailure(message); } return orElse(); } @override @optionalTypeArgs TResult map<TResult extends Object?>({ required TResult Function(_InitialSearchState value) initial, required TResult Function(_LoadingSearchState value) loading, required TResult Function(_UserInputFailureSearchState value) userInputFailure, required TResult Function(_FailureSearchState value) failure, required TResult Function(_ShowingResultSearchState value) showingResult, }) { return userInputFailure(this); } @override @optionalTypeArgs TResult? mapOrNull<TResult extends Object?>({ TResult Function(_InitialSearchState value)? initial, TResult Function(_LoadingSearchState value)? loading, TResult Function(_UserInputFailureSearchState value)? userInputFailure, TResult Function(_FailureSearchState value)? failure, TResult Function(_ShowingResultSearchState value)? showingResult, }) { return userInputFailure?.call(this); } @override @optionalTypeArgs TResult maybeMap<TResult extends Object?>({ TResult Function(_InitialSearchState value)? initial, TResult Function(_LoadingSearchState value)? loading, TResult Function(_UserInputFailureSearchState value)? userInputFailure, TResult Function(_FailureSearchState value)? failure, TResult Function(_ShowingResultSearchState value)? showingResult, required TResult orElse(), }) { if (userInputFailure != null) { return userInputFailure(this); } return orElse(); } } abstract class _UserInputFailureSearchState extends SearchState { const factory _UserInputFailureSearchState(final String message) = _$_UserInputFailureSearchState; const _UserInputFailureSearchState._() : super._(); String get message; @JsonKey(ignore: true) _$$_UserInputFailureSearchStateCopyWith<_$_UserInputFailureSearchState> get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class _$$_FailureSearchStateCopyWith<$Res> { factory _$$_FailureSearchStateCopyWith(_$_FailureSearchState value, $Res Function(_$_FailureSearchState) then) = __$$_FailureSearchStateCopyWithImpl<$Res>; $Res call({String message}); } /// @nodoc class __$$_FailureSearchStateCopyWithImpl<$Res> extends _$SearchStateCopyWithImpl<$Res> implements _$$_FailureSearchStateCopyWith<$Res> { __$$_FailureSearchStateCopyWithImpl( _$_FailureSearchState _value, $Res Function(_$_FailureSearchState) _then) : super(_value, (v) => _then(v as _$_FailureSearchState)); @override _$_FailureSearchState get _value => super._value as _$_FailureSearchState; @override $Res call({ Object? message = freezed, }) { return _then(_$_FailureSearchState( message: message == freezed ? _value.message : message // ignore: cast_nullable_to_non_nullable as String, )); } } /// @nodoc class _$_FailureSearchState extends _FailureSearchState { const _$_FailureSearchState({this.message = 'An error has occurred'}) : super._(); @override @JsonKey() final String message; @override String toString() { return 'SearchState.failure(message: $message)'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_FailureSearchState && const DeepCollectionEquality().equals(other.message, message)); } @override int get hashCode => Object.hash(runtimeType, const DeepCollectionEquality().hash(message)); @JsonKey(ignore: true) @override _$$_FailureSearchStateCopyWith<_$_FailureSearchState> get copyWith => __$$_FailureSearchStateCopyWithImpl<_$_FailureSearchState>( this, _$identity); @override @optionalTypeArgs TResult when<TResult extends Object?>({ required TResult Function() initial, required TResult Function() loading, required TResult Function(String message) userInputFailure, required TResult Function(String message) failure, required TResult Function(List<Result> result) showingResult, }) { return failure(message); } @override @optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({ TResult Function()? initial, TResult Function()? loading, TResult Function(String message)? userInputFailure, TResult Function(String message)? failure, TResult Function(List<Result> result)? showingResult, }) { return failure?.call(message); } @override @optionalTypeArgs TResult maybeWhen<TResult extends Object?>({ TResult Function()? initial, TResult Function()? loading, TResult Function(String message)? userInputFailure, TResult Function(String message)? failure, TResult Function(List<Result> result)? showingResult, required TResult orElse(), }) { if (failure != null) { return failure(message); } return orElse(); } @override @optionalTypeArgs TResult map<TResult extends Object?>({ required TResult Function(_InitialSearchState value) initial, required TResult Function(_LoadingSearchState value) loading, required TResult Function(_UserInputFailureSearchState value) userInputFailure, required TResult Function(_FailureSearchState value) failure, required TResult Function(_ShowingResultSearchState value) showingResult, }) { return failure(this); } @override @optionalTypeArgs TResult? mapOrNull<TResult extends Object?>({ TResult Function(_InitialSearchState value)? initial, TResult Function(_LoadingSearchState value)? loading, TResult Function(_UserInputFailureSearchState value)? userInputFailure, TResult Function(_FailureSearchState value)? failure, TResult Function(_ShowingResultSearchState value)? showingResult, }) { return failure?.call(this); } @override @optionalTypeArgs TResult maybeMap<TResult extends Object?>({ TResult Function(_InitialSearchState value)? initial, TResult Function(_LoadingSearchState value)? loading, TResult Function(_UserInputFailureSearchState value)? userInputFailure, TResult Function(_FailureSearchState value)? failure, TResult Function(_ShowingResultSearchState value)? showingResult, required TResult orElse(), }) { if (failure != null) { return failure(this); } return orElse(); } } abstract class _FailureSearchState extends SearchState { const factory _FailureSearchState({final String message}) = _$_FailureSearchState; const _FailureSearchState._() : super._(); String get message; @JsonKey(ignore: true) _$$_FailureSearchStateCopyWith<_$_FailureSearchState> get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class _$$_ShowingResultSearchStateCopyWith<$Res> { factory _$$_ShowingResultSearchStateCopyWith( _$_ShowingResultSearchState value, $Res Function(_$_ShowingResultSearchState) then) = __$$_ShowingResultSearchStateCopyWithImpl<$Res>; $Res call({List<Result> result}); } /// @nodoc class __$$_ShowingResultSearchStateCopyWithImpl<$Res> extends _$SearchStateCopyWithImpl<$Res> implements _$$_ShowingResultSearchStateCopyWith<$Res> { __$$_ShowingResultSearchStateCopyWithImpl(_$_ShowingResultSearchState _value, $Res Function(_$_ShowingResultSearchState) _then) : super(_value, (v) => _then(v as _$_ShowingResultSearchState)); @override _$_ShowingResultSearchState get _value => super._value as _$_ShowingResultSearchState; @override $Res call({ Object? result = freezed, }) { return _then(_$_ShowingResultSearchState( result == freezed ? _value._result : result // ignore: cast_nullable_to_non_nullable as List<Result>, )); } } /// @nodoc class _$_ShowingResultSearchState extends _ShowingResultSearchState { const _$_ShowingResultSearchState(final List<Result> result) : _result = result, super._(); final List<Result> _result; @override List<Result> get result { // ignore: implicit_dynamic_type return EqualUnmodifiableListView(_result); } @override String toString() { return 'SearchState.showingResult(result: $result)'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_ShowingResultSearchState && const DeepCollectionEquality().equals(other._result, _result)); } @override int get hashCode => Object.hash(runtimeType, const DeepCollectionEquality().hash(_result)); @JsonKey(ignore: true) @override _$$_ShowingResultSearchStateCopyWith<_$_ShowingResultSearchState> get copyWith => __$$_ShowingResultSearchStateCopyWithImpl< _$_ShowingResultSearchState>(this, _$identity); @override @optionalTypeArgs TResult when<TResult extends Object?>({ required TResult Function() initial, required TResult Function() loading, required TResult Function(String message) userInputFailure, required TResult Function(String message) failure, required TResult Function(List<Result> result) showingResult, }) { return showingResult(result); } @override @optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({ TResult Function()? initial, TResult Function()? loading, TResult Function(String message)? userInputFailure, TResult Function(String message)? failure, TResult Function(List<Result> result)? showingResult, }) { return showingResult?.call(result); } @override @optionalTypeArgs TResult maybeWhen<TResult extends Object?>({ TResult Function()? initial, TResult Function()? loading, TResult Function(String message)? userInputFailure, TResult Function(String message)? failure, TResult Function(List<Result> result)? showingResult, required TResult orElse(), }) { if (showingResult != null) { return showingResult(result); } return orElse(); } @override @optionalTypeArgs TResult map<TResult extends Object?>({ required TResult Function(_InitialSearchState value) initial, required TResult Function(_LoadingSearchState value) loading, required TResult Function(_UserInputFailureSearchState value) userInputFailure, required TResult Function(_FailureSearchState value) failure, required TResult Function(_ShowingResultSearchState value) showingResult, }) { return showingResult(this); } @override @optionalTypeArgs TResult? mapOrNull<TResult extends Object?>({ TResult Function(_InitialSearchState value)? initial, TResult Function(_LoadingSearchState value)? loading, TResult Function(_UserInputFailureSearchState value)? userInputFailure, TResult Function(_FailureSearchState value)? failure, TResult Function(_ShowingResultSearchState value)? showingResult, }) { return showingResult?.call(this); } @override @optionalTypeArgs TResult maybeMap<TResult extends Object?>({ TResult Function(_InitialSearchState value)? initial, TResult Function(_LoadingSearchState value)? loading, TResult Function(_UserInputFailureSearchState value)? userInputFailure, TResult Function(_FailureSearchState value)? failure, TResult Function(_ShowingResultSearchState value)? showingResult, required TResult orElse(), }) { if (showingResult != null) { return showingResult(this); } return orElse(); } } abstract class _ShowingResultSearchState extends SearchState { const factory _ShowingResultSearchState(final List<Result> result) = _$_ShowingResultSearchState; const _ShowingResultSearchState._() : super._(); List<Result> get result; @JsonKey(ignore: true) _$$_ShowingResultSearchStateCopyWith<_$_ShowingResultSearchState> get copyWith => throw _privateConstructorUsedError; } /// @nodoc mixin _$SearchEvent { @optionalTypeArgs TResult when<TResult extends Object?>({ required TResult Function(String imageUrl) searchViaDirectUrl, required TResult Function(Uint8List bytes) searchViaFile, required TResult Function() openSearch, required TResult Function( Future<Uint8List?>? mediaBytes, Future<String?>? text) pastedContent, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({ TResult Function(String imageUrl)? searchViaDirectUrl, TResult Function(Uint8List bytes)? searchViaFile, TResult Function()? openSearch, TResult Function(Future<Uint8List?>? mediaBytes, Future<String?>? text)? pastedContent, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult maybeWhen<TResult extends Object?>({ TResult Function(String imageUrl)? searchViaDirectUrl, TResult Function(Uint8List bytes)? searchViaFile, TResult Function()? openSearch, TResult Function(Future<Uint8List?>? mediaBytes, Future<String?>? text)? pastedContent, required TResult orElse(), }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult map<TResult extends Object?>({ required TResult Function(_SearchViaDirectUrlSearchEvent value) searchViaDirectUrl, required TResult Function(_SearchViaFileSearchEvent value) searchViaFile, required TResult Function(_OpenSearchSearchEvent value) openSearch, required TResult Function(_PastedContentSearchEvent value) pastedContent, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult? mapOrNull<TResult extends Object?>({ TResult Function(_SearchViaDirectUrlSearchEvent value)? searchViaDirectUrl, TResult Function(_SearchViaFileSearchEvent value)? searchViaFile, TResult Function(_OpenSearchSearchEvent value)? openSearch, TResult Function(_PastedContentSearchEvent value)? pastedContent, }) => throw _privateConstructorUsedError; @optionalTypeArgs TResult maybeMap<TResult extends Object?>({ TResult Function(_SearchViaDirectUrlSearchEvent value)? searchViaDirectUrl, TResult Function(_SearchViaFileSearchEvent value)? searchViaFile, TResult Function(_OpenSearchSearchEvent value)? openSearch, TResult Function(_PastedContentSearchEvent value)? pastedContent, required TResult orElse(), }) => throw _privateConstructorUsedError; } /// @nodoc abstract class $SearchEventCopyWith<$Res> { factory $SearchEventCopyWith( SearchEvent value, $Res Function(SearchEvent) then) = _$SearchEventCopyWithImpl<$Res>; } /// @nodoc class _$SearchEventCopyWithImpl<$Res> implements $SearchEventCopyWith<$Res> { _$SearchEventCopyWithImpl(this._value, this._then); final SearchEvent _value; // ignore: unused_field final $Res Function(SearchEvent) _then; } /// @nodoc abstract class _$$_SearchViaDirectUrlSearchEventCopyWith<$Res> { factory _$$_SearchViaDirectUrlSearchEventCopyWith( _$_SearchViaDirectUrlSearchEvent value, $Res Function(_$_SearchViaDirectUrlSearchEvent) then) = __$$_SearchViaDirectUrlSearchEventCopyWithImpl<$Res>; $Res call({String imageUrl}); } /// @nodoc class __$$_SearchViaDirectUrlSearchEventCopyWithImpl<$Res> extends _$SearchEventCopyWithImpl<$Res> implements _$$_SearchViaDirectUrlSearchEventCopyWith<$Res> { __$$_SearchViaDirectUrlSearchEventCopyWithImpl( _$_SearchViaDirectUrlSearchEvent _value, $Res Function(_$_SearchViaDirectUrlSearchEvent) _then) : super(_value, (v) => _then(v as _$_SearchViaDirectUrlSearchEvent)); @override _$_SearchViaDirectUrlSearchEvent get _value => super._value as _$_SearchViaDirectUrlSearchEvent; @override $Res call({ Object? imageUrl = freezed, }) { return _then(_$_SearchViaDirectUrlSearchEvent( imageUrl == freezed ? _value.imageUrl : imageUrl // ignore: cast_nullable_to_non_nullable as String, )); } } /// @nodoc class _$_SearchViaDirectUrlSearchEvent extends _SearchViaDirectUrlSearchEvent { const _$_SearchViaDirectUrlSearchEvent(this.imageUrl) : super._(); @override final String imageUrl; @override String toString() { return 'SearchEvent.searchViaDirectUrl(imageUrl: $imageUrl)'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_SearchViaDirectUrlSearchEvent && const DeepCollectionEquality().equals(other.imageUrl, imageUrl)); } @override int get hashCode => Object.hash(runtimeType, const DeepCollectionEquality().hash(imageUrl)); @JsonKey(ignore: true) @override _$$_SearchViaDirectUrlSearchEventCopyWith<_$_SearchViaDirectUrlSearchEvent> get copyWith => __$$_SearchViaDirectUrlSearchEventCopyWithImpl< _$_SearchViaDirectUrlSearchEvent>(this, _$identity); @override @optionalTypeArgs TResult when<TResult extends Object?>({ required TResult Function(String imageUrl) searchViaDirectUrl, required TResult Function(Uint8List bytes) searchViaFile, required TResult Function() openSearch, required TResult Function( Future<Uint8List?>? mediaBytes, Future<String?>? text) pastedContent, }) { return searchViaDirectUrl(imageUrl); } @override @optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({ TResult Function(String imageUrl)? searchViaDirectUrl, TResult Function(Uint8List bytes)? searchViaFile, TResult Function()? openSearch, TResult Function(Future<Uint8List?>? mediaBytes, Future<String?>? text)? pastedContent, }) { return searchViaDirectUrl?.call(imageUrl); } @override @optionalTypeArgs TResult maybeWhen<TResult extends Object?>({ TResult Function(String imageUrl)? searchViaDirectUrl, TResult Function(Uint8List bytes)? searchViaFile, TResult Function()? openSearch, TResult Function(Future<Uint8List?>? mediaBytes, Future<String?>? text)? pastedContent, required TResult orElse(), }) { if (searchViaDirectUrl != null) { return searchViaDirectUrl(imageUrl); } return orElse(); } @override @optionalTypeArgs TResult map<TResult extends Object?>({ required TResult Function(_SearchViaDirectUrlSearchEvent value) searchViaDirectUrl, required TResult Function(_SearchViaFileSearchEvent value) searchViaFile, required TResult Function(_OpenSearchSearchEvent value) openSearch, required TResult Function(_PastedContentSearchEvent value) pastedContent, }) { return searchViaDirectUrl(this); } @override @optionalTypeArgs TResult? mapOrNull<TResult extends Object?>({ TResult Function(_SearchViaDirectUrlSearchEvent value)? searchViaDirectUrl, TResult Function(_SearchViaFileSearchEvent value)? searchViaFile, TResult Function(_OpenSearchSearchEvent value)? openSearch, TResult Function(_PastedContentSearchEvent value)? pastedContent, }) { return searchViaDirectUrl?.call(this); } @override @optionalTypeArgs TResult maybeMap<TResult extends Object?>({ TResult Function(_SearchViaDirectUrlSearchEvent value)? searchViaDirectUrl, TResult Function(_SearchViaFileSearchEvent value)? searchViaFile, TResult Function(_OpenSearchSearchEvent value)? openSearch, TResult Function(_PastedContentSearchEvent value)? pastedContent, required TResult orElse(), }) { if (searchViaDirectUrl != null) { return searchViaDirectUrl(this); } return orElse(); } } abstract class _SearchViaDirectUrlSearchEvent extends SearchEvent { const factory _SearchViaDirectUrlSearchEvent(final String imageUrl) = _$_SearchViaDirectUrlSearchEvent; const _SearchViaDirectUrlSearchEvent._() : super._(); String get imageUrl; @JsonKey(ignore: true) _$$_SearchViaDirectUrlSearchEventCopyWith<_$_SearchViaDirectUrlSearchEvent> get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class _$$_SearchViaFileSearchEventCopyWith<$Res> { factory _$$_SearchViaFileSearchEventCopyWith( _$_SearchViaFileSearchEvent value, $Res Function(_$_SearchViaFileSearchEvent) then) = __$$_SearchViaFileSearchEventCopyWithImpl<$Res>; $Res call({Uint8List bytes}); } /// @nodoc class __$$_SearchViaFileSearchEventCopyWithImpl<$Res> extends _$SearchEventCopyWithImpl<$Res> implements _$$_SearchViaFileSearchEventCopyWith<$Res> { __$$_SearchViaFileSearchEventCopyWithImpl(_$_SearchViaFileSearchEvent _value, $Res Function(_$_SearchViaFileSearchEvent) _then) : super(_value, (v) => _then(v as _$_SearchViaFileSearchEvent)); @override _$_SearchViaFileSearchEvent get _value => super._value as _$_SearchViaFileSearchEvent; @override $Res call({ Object? bytes = freezed, }) { return _then(_$_SearchViaFileSearchEvent( bytes == freezed ? _value.bytes : bytes // ignore: cast_nullable_to_non_nullable as Uint8List, )); } } /// @nodoc class _$_SearchViaFileSearchEvent extends _SearchViaFileSearchEvent { const _$_SearchViaFileSearchEvent(this.bytes) : super._(); @override final Uint8List bytes; @override String toString() { return 'SearchEvent.searchViaFile(bytes: $bytes)'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_SearchViaFileSearchEvent && const DeepCollectionEquality().equals(other.bytes, bytes)); } @override int get hashCode => Object.hash(runtimeType, const DeepCollectionEquality().hash(bytes)); @JsonKey(ignore: true) @override _$$_SearchViaFileSearchEventCopyWith<_$_SearchViaFileSearchEvent> get copyWith => __$$_SearchViaFileSearchEventCopyWithImpl< _$_SearchViaFileSearchEvent>(this, _$identity); @override @optionalTypeArgs TResult when<TResult extends Object?>({ required TResult Function(String imageUrl) searchViaDirectUrl, required TResult Function(Uint8List bytes) searchViaFile, required TResult Function() openSearch, required TResult Function( Future<Uint8List?>? mediaBytes, Future<String?>? text) pastedContent, }) { return searchViaFile(bytes); } @override @optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({ TResult Function(String imageUrl)? searchViaDirectUrl, TResult Function(Uint8List bytes)? searchViaFile, TResult Function()? openSearch, TResult Function(Future<Uint8List?>? mediaBytes, Future<String?>? text)? pastedContent, }) { return searchViaFile?.call(bytes); } @override @optionalTypeArgs TResult maybeWhen<TResult extends Object?>({ TResult Function(String imageUrl)? searchViaDirectUrl, TResult Function(Uint8List bytes)? searchViaFile, TResult Function()? openSearch, TResult Function(Future<Uint8List?>? mediaBytes, Future<String?>? text)? pastedContent, required TResult orElse(), }) { if (searchViaFile != null) { return searchViaFile(bytes); } return orElse(); } @override @optionalTypeArgs TResult map<TResult extends Object?>({ required TResult Function(_SearchViaDirectUrlSearchEvent value) searchViaDirectUrl, required TResult Function(_SearchViaFileSearchEvent value) searchViaFile, required TResult Function(_OpenSearchSearchEvent value) openSearch, required TResult Function(_PastedContentSearchEvent value) pastedContent, }) { return searchViaFile(this); } @override @optionalTypeArgs TResult? mapOrNull<TResult extends Object?>({ TResult Function(_SearchViaDirectUrlSearchEvent value)? searchViaDirectUrl, TResult Function(_SearchViaFileSearchEvent value)? searchViaFile, TResult Function(_OpenSearchSearchEvent value)? openSearch, TResult Function(_PastedContentSearchEvent value)? pastedContent, }) { return searchViaFile?.call(this); } @override @optionalTypeArgs TResult maybeMap<TResult extends Object?>({ TResult Function(_SearchViaDirectUrlSearchEvent value)? searchViaDirectUrl, TResult Function(_SearchViaFileSearchEvent value)? searchViaFile, TResult Function(_OpenSearchSearchEvent value)? openSearch, TResult Function(_PastedContentSearchEvent value)? pastedContent, required TResult orElse(), }) { if (searchViaFile != null) { return searchViaFile(this); } return orElse(); } } abstract class _SearchViaFileSearchEvent extends SearchEvent { const factory _SearchViaFileSearchEvent(final Uint8List bytes) = _$_SearchViaFileSearchEvent; const _SearchViaFileSearchEvent._() : super._(); Uint8List get bytes; @JsonKey(ignore: true) _$$_SearchViaFileSearchEventCopyWith<_$_SearchViaFileSearchEvent> get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class _$$_OpenSearchSearchEventCopyWith<$Res> { factory _$$_OpenSearchSearchEventCopyWith(_$_OpenSearchSearchEvent value, $Res Function(_$_OpenSearchSearchEvent) then) = __$$_OpenSearchSearchEventCopyWithImpl<$Res>; } /// @nodoc class __$$_OpenSearchSearchEventCopyWithImpl<$Res> extends _$SearchEventCopyWithImpl<$Res> implements _$$_OpenSearchSearchEventCopyWith<$Res> { __$$_OpenSearchSearchEventCopyWithImpl(_$_OpenSearchSearchEvent _value, $Res Function(_$_OpenSearchSearchEvent) _then) : super(_value, (v) => _then(v as _$_OpenSearchSearchEvent)); @override _$_OpenSearchSearchEvent get _value => super._value as _$_OpenSearchSearchEvent; } /// @nodoc class _$_OpenSearchSearchEvent extends _OpenSearchSearchEvent { const _$_OpenSearchSearchEvent() : super._(); @override String toString() { return 'SearchEvent.openSearch()'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_OpenSearchSearchEvent); } @override int get hashCode => runtimeType.hashCode; @override @optionalTypeArgs TResult when<TResult extends Object?>({ required TResult Function(String imageUrl) searchViaDirectUrl, required TResult Function(Uint8List bytes) searchViaFile, required TResult Function() openSearch, required TResult Function( Future<Uint8List?>? mediaBytes, Future<String?>? text) pastedContent, }) { return openSearch(); } @override @optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({ TResult Function(String imageUrl)? searchViaDirectUrl, TResult Function(Uint8List bytes)? searchViaFile, TResult Function()? openSearch, TResult Function(Future<Uint8List?>? mediaBytes, Future<String?>? text)? pastedContent, }) { return openSearch?.call(); } @override @optionalTypeArgs TResult maybeWhen<TResult extends Object?>({ TResult Function(String imageUrl)? searchViaDirectUrl, TResult Function(Uint8List bytes)? searchViaFile, TResult Function()? openSearch, TResult Function(Future<Uint8List?>? mediaBytes, Future<String?>? text)? pastedContent, required TResult orElse(), }) { if (openSearch != null) { return openSearch(); } return orElse(); } @override @optionalTypeArgs TResult map<TResult extends Object?>({ required TResult Function(_SearchViaDirectUrlSearchEvent value) searchViaDirectUrl, required TResult Function(_SearchViaFileSearchEvent value) searchViaFile, required TResult Function(_OpenSearchSearchEvent value) openSearch, required TResult Function(_PastedContentSearchEvent value) pastedContent, }) { return openSearch(this); } @override @optionalTypeArgs TResult? mapOrNull<TResult extends Object?>({ TResult Function(_SearchViaDirectUrlSearchEvent value)? searchViaDirectUrl, TResult Function(_SearchViaFileSearchEvent value)? searchViaFile, TResult Function(_OpenSearchSearchEvent value)? openSearch, TResult Function(_PastedContentSearchEvent value)? pastedContent, }) { return openSearch?.call(this); } @override @optionalTypeArgs TResult maybeMap<TResult extends Object?>({ TResult Function(_SearchViaDirectUrlSearchEvent value)? searchViaDirectUrl, TResult Function(_SearchViaFileSearchEvent value)? searchViaFile, TResult Function(_OpenSearchSearchEvent value)? openSearch, TResult Function(_PastedContentSearchEvent value)? pastedContent, required TResult orElse(), }) { if (openSearch != null) { return openSearch(this); } return orElse(); } } abstract class _OpenSearchSearchEvent extends SearchEvent { const factory _OpenSearchSearchEvent() = _$_OpenSearchSearchEvent; const _OpenSearchSearchEvent._() : super._(); } /// @nodoc abstract class _$$_PastedContentSearchEventCopyWith<$Res> { factory _$$_PastedContentSearchEventCopyWith( _$_PastedContentSearchEvent value, $Res Function(_$_PastedContentSearchEvent) then) = __$$_PastedContentSearchEventCopyWithImpl<$Res>; $Res call({Future<Uint8List?>? mediaBytes, Future<String?>? text}); } /// @nodoc class __$$_PastedContentSearchEventCopyWithImpl<$Res> extends _$SearchEventCopyWithImpl<$Res> implements _$$_PastedContentSearchEventCopyWith<$Res> { __$$_PastedContentSearchEventCopyWithImpl(_$_PastedContentSearchEvent _value, $Res Function(_$_PastedContentSearchEvent) _then) : super(_value, (v) => _then(v as _$_PastedContentSearchEvent)); @override _$_PastedContentSearchEvent get _value => super._value as _$_PastedContentSearchEvent; @override $Res call({ Object? mediaBytes = freezed, Object? text = freezed, }) { return _then(_$_PastedContentSearchEvent( mediaBytes == freezed ? _value.mediaBytes : mediaBytes // ignore: cast_nullable_to_non_nullable as Future<Uint8List?>?, text == freezed ? _value.text : text // ignore: cast_nullable_to_non_nullable as Future<String?>?, )); } } /// @nodoc class _$_PastedContentSearchEvent extends _PastedContentSearchEvent { const _$_PastedContentSearchEvent(this.mediaBytes, this.text) : super._(); @override final Future<Uint8List?>? mediaBytes; @override final Future<String?>? text; @override String toString() { return 'SearchEvent.pastedContent(mediaBytes: $mediaBytes, text: $text)'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_PastedContentSearchEvent && const DeepCollectionEquality() .equals(other.mediaBytes, mediaBytes) && const DeepCollectionEquality().equals(other.text, text)); } @override int get hashCode => Object.hash( runtimeType, const DeepCollectionEquality().hash(mediaBytes), const DeepCollectionEquality().hash(text)); @JsonKey(ignore: true) @override _$$_PastedContentSearchEventCopyWith<_$_PastedContentSearchEvent> get copyWith => __$$_PastedContentSearchEventCopyWithImpl< _$_PastedContentSearchEvent>(this, _$identity); @override @optionalTypeArgs TResult when<TResult extends Object?>({ required TResult Function(String imageUrl) searchViaDirectUrl, required TResult Function(Uint8List bytes) searchViaFile, required TResult Function() openSearch, required TResult Function( Future<Uint8List?>? mediaBytes, Future<String?>? text) pastedContent, }) { return pastedContent(mediaBytes, text); } @override @optionalTypeArgs TResult? whenOrNull<TResult extends Object?>({ TResult Function(String imageUrl)? searchViaDirectUrl, TResult Function(Uint8List bytes)? searchViaFile, TResult Function()? openSearch, TResult Function(Future<Uint8List?>? mediaBytes, Future<String?>? text)? pastedContent, }) { return pastedContent?.call(mediaBytes, text); } @override @optionalTypeArgs TResult maybeWhen<TResult extends Object?>({ TResult Function(String imageUrl)? searchViaDirectUrl, TResult Function(Uint8List bytes)? searchViaFile, TResult Function()? openSearch, TResult Function(Future<Uint8List?>? mediaBytes, Future<String?>? text)? pastedContent, required TResult orElse(), }) { if (pastedContent != null) { return pastedContent(mediaBytes, text); } return orElse(); } @override @optionalTypeArgs TResult map<TResult extends Object?>({ required TResult Function(_SearchViaDirectUrlSearchEvent value) searchViaDirectUrl, required TResult Function(_SearchViaFileSearchEvent value) searchViaFile, required TResult Function(_OpenSearchSearchEvent value) openSearch, required TResult Function(_PastedContentSearchEvent value) pastedContent, }) { return pastedContent(this); } @override @optionalTypeArgs TResult? mapOrNull<TResult extends Object?>({ TResult Function(_SearchViaDirectUrlSearchEvent value)? searchViaDirectUrl, TResult Function(_SearchViaFileSearchEvent value)? searchViaFile, TResult Function(_OpenSearchSearchEvent value)? openSearch, TResult Function(_PastedContentSearchEvent value)? pastedContent, }) { return pastedContent?.call(this); } @override @optionalTypeArgs TResult maybeMap<TResult extends Object?>({ TResult Function(_SearchViaDirectUrlSearchEvent value)? searchViaDirectUrl, TResult Function(_SearchViaFileSearchEvent value)? searchViaFile, TResult Function(_OpenSearchSearchEvent value)? openSearch, TResult Function(_PastedContentSearchEvent value)? pastedContent, required TResult orElse(), }) { if (pastedContent != null) { return pastedContent(this); } return orElse(); } } abstract class _PastedContentSearchEvent extends SearchEvent { const factory _PastedContentSearchEvent( final Future<Uint8List?>? mediaBytes, final Future<String?>? text) = _$_PastedContentSearchEvent; const _PastedContentSearchEvent._() : super._(); Future<Uint8List?>? get mediaBytes; Future<String?>? get text; @JsonKey(ignore: true) _$$_PastedContentSearchEventCopyWith<_$_PastedContentSearchEvent> get copyWith => throw _privateConstructorUsedError; }
0
mirrored_repositories/find_anime/lib/src/feature/search
mirrored_repositories/find_anime/lib/src/feature/search/util/paste_media_intent.dart
import 'dart:typed_data'; import 'package:flutter/material.dart'; class PasteMediaIntent extends Intent { const PasteMediaIntent({required this.mediaBytes, this.text}); final Future<Uint8List?> mediaBytes; final Future<String?>? text; }
0
mirrored_repositories/find_anime
mirrored_repositories/find_anime/test/widget_test.dart
import 'package:bloc_test/bloc_test.dart'; import 'package:find_anime/app/cubit/language_cubit.dart'; import 'package:find_anime/app/cubit/theme_cubit.dart'; import 'package:find_anime/common/widget/app.dart'; import 'package:find_anime/generated/l10n.dart'; import 'package:find_anime/search/search.dart'; import 'package:find_anime/search/view/search_view.dart'; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:tracemoe_repository/tracemoe_repository.dart'; class MockTraceMoeRepository extends Mock implements TraceMoeRepository {} class MockThemeCubit extends MockCubit<ThemeState> implements ThemeCubit { @override ThemeMode get appTheme => ThemeMode.light; } class MockLanguageCubit extends MockCubit<LanguageState> implements LanguageCubit { @override Locale get getLocale => const Locale('en'); } class MockSearchCubit extends MockCubit<SearchState> implements SearchCubit { @override TextEditingController get textController => TextEditingController(); } void main() { group('FindAnimeApp', () { late TraceMoeRepository traceMoeRepository; late SearchCubit searchCubit; late ThemeCubit themeCubit; late LanguageCubit languageCubit; setUpAll(() { registerFallbackValue(MockSearchCubit()); }); setUp(() { traceMoeRepository = TraceMoeRepository(); searchCubit = MockSearchCubit(); themeCubit = MockThemeCubit(); languageCubit = MockLanguageCubit(); }); testWidgets('Theme - system matching', (tester) async { await tester.pumpWidget(const FindAnimeApp()); // capture BuildContext for theme testing final BuildContext context = tester.element(find.byType(FindAnimeApp)); expect(context, isNotNull); final Brightness systemBrightness = SchedulerBinding.instance.window.platformBrightness; expect(Theme.of(context).brightness, systemBrightness); }); testWidgets('SearchView rendering from app starting', (tester) async { await tester.pumpWidget(const FindAnimeApp()); await tester.pump(); expect(find.byType(SearchView), findsOneWidget); }); testWidgets( 'renders InitialSearchView for SearchState.initial', (tester) async { when(() => searchCubit.state).thenReturn(const SearchState()); await tester.pumpWidget( MaterialApp( localizationsDelegates: const [AppLocalizationDelegate()], home: BlocProvider( create: (_) => searchCubit, child: const SearchView(), ), ), ); await tester.pump(const Duration(seconds: 1)); expect(find.byType(InitialSearchView), findsOneWidget); }, ); testWidgets( 'renders BuildLoadingIndicator for SearchState.loading', (tester) async { when(() => searchCubit.state) .thenReturn(const SearchState(status: SearchStatus.loading)); await tester.pumpWidget( MaterialApp( localizationsDelegates: const [AppLocalizationDelegate()], home: BlocProvider( create: (_) => searchCubit, child: const SearchView(), ), ), ); await tester.pump(const Duration(seconds: 1)); expect(find.byType(BuildLoadingIndicator), findsOneWidget); }, ); testWidgets( 'renders BuildError for SearchState.failure', (tester) async { when(() => searchCubit.state).thenReturn(SearchState( status: SearchStatus.failure, errorText: S().errorUnknown, )); await tester.pumpWidget( MaterialApp( localizationsDelegates: const [AppLocalizationDelegate()], home: BlocProvider( create: (_) => searchCubit, child: const SearchView(), ), ), ); await tester.pump(const Duration(seconds: 1)); expect(find.byType(BuildError), findsOneWidget); }, ); testWidgets( 'renders ResultList for SearchState.success', (tester) async { when(() => searchCubit.state).thenReturn( const SearchState(status: SearchStatus.success, result: []), ); await tester.pumpWidget( MaterialApp( localizationsDelegates: const [AppLocalizationDelegate()], home: BlocProvider( create: (_) => searchCubit, child: const SearchView(), ), ), ); await tester.pump(const Duration(seconds: 1)); expect(find.byType(ResultList), findsOneWidget); }, ); testWidgets( 'Change app theme on button tap', (tester) async { when(() => searchCubit.state).thenReturn(const SearchState()); await tester.pumpWidget(FindAnimeApp( _theme: themeCubit, )); await tester.pump(); expect(find.byType(InitialSearchView), findsOneWidget); await tester.tap(find.byIcon(Icons.brightness_6_outlined)); await tester.pumpAndSettle(); verify(() => themeCubit.changeAppTheme()).called(1); }, ); testWidgets( 'Change app language on button tap', (tester) async { when(() => searchCubit.state).thenReturn(const SearchState()); await tester.pumpWidget(FindAnimeApp( _languageCubit: languageCubit, )); await tester.pump(); expect(find.byType(InitialSearchView), findsOneWidget); await tester.tap(find.byIcon(Icons.language_outlined)); await tester.pumpAndSettle(); verify(() => languageCubit.toggleAppLanguage()).called(1); }, ); }); }
0
mirrored_repositories/find_anime/packages/tracemoe_api
mirrored_repositories/find_anime/packages/tracemoe_api/lib/tracemoe_api.dart
library tracemoe_api; export 'src/tracemoe_api_client.dart'; export 'src/models/search_result.dart';
0
mirrored_repositories/find_anime/packages/tracemoe_api/lib
mirrored_repositories/find_anime/packages/tracemoe_api/lib/src/tracemoe_api_client.dart
import 'dart:convert'; import 'dart:typed_data'; import 'package:http/http.dart' as http; import 'models/search_result.dart'; /// error 500 class SearchInternalErrorFailure implements Exception {} /// error 503 class SearchQueueIsFullFailure implements Exception {} /// error 504 class SearchServerOverloadFailure implements Exception {} /// error 405 class MethodIsNotAllowedFailure implements Exception {} /// error 403 class InvalidApiKeyFailure implements Exception {} /// error 402 class SearchQuotaDepletedFailure implements Exception {} /// error 400 class InvalidImageUrlFailure implements Exception {} class TraceMoeApiClient { TraceMoeApiClient({http.Client? httpClient}) : _httpClient = httpClient ?? http.Client(); final http.Client _httpClient; static const _baseUrl = 'https://api.trace.moe/search?anilistInfo'; /// Send GET method to get result from TraceMoe with given image [url]. /// /// Will throw exceptions according to the API documentation: /// https://soruly.github.io/trace.moe-api/#/docs?id=error-codes Future<SearchResultModel> getResultByImageUrl(String url) async { final response = await _httpClient.get(Uri.parse('$_baseUrl&url=$url')); return _getSearchModel(response); } /// Send POST method to get result from TraceMoe with given media, coded in [bytes]. /// You need to specify [mimeType] of file coded in [bytes]. /// /// Media can be an **image/\***, **video/\*** or **gif**. /// If a different file type is sent, [InvalidImageUrlFailure] will be thrown. /// /// Will throw exceptions according to the API documentation: /// https://soruly.github.io/trace.moe-api/#/docs?id=error-codes Future<SearchResultModel> getResultByFile( Uint8List bytes, { required String mimeType, }) async { final response = await _httpClient.post( Uri.parse(_baseUrl), headers: { 'Content-Type': mimeType, }, body: bytes, ); return _getSearchModel(response); } /// Processes the response and returns [SearchResultModel]. /// /// If response is not successful, will throw exception. /// /// https://soruly.github.io/trace.moe-api/#/docs?id=error-codes SearchResultModel _getSearchModel(http.Response response) { switch (response.statusCode) { case 200: return SearchResultModel.fromJson(jsonDecode(response.body)); case 400: throw InvalidImageUrlFailure(); case 402: throw SearchQuotaDepletedFailure(); case 403: throw InvalidApiKeyFailure(); case 405: throw MethodIsNotAllowedFailure(); case 500: throw SearchInternalErrorFailure(); case 503: throw SearchQueueIsFullFailure(); case 504: throw SearchServerOverloadFailure(); default: // unknown error occurred throw Exception(); } } }
0
mirrored_repositories/find_anime/packages/tracemoe_api/lib/src
mirrored_repositories/find_anime/packages/tracemoe_api/lib/src/models/search_result.dart
import 'package:freezed_annotation/freezed_annotation.dart'; part 'search_result.freezed.dart'; part 'search_result.g.dart'; @freezed class SearchResultModel with _$SearchResultModel { const factory SearchResultModel({ int? frameCount, String? error, List<ResultModel>? result, }) = _SearchResultModel; factory SearchResultModel.fromJson(Map<String, dynamic> json) => _$SearchResultModelFromJson(json); } @freezed class ResultModel with _$ResultModel { const factory ResultModel({ AnilistModel? anilist, String? filename, num? episode, num? from, num? to, num? similarity, String? video, String? image, }) = _ResultModel; factory ResultModel.fromJson(Map<String, dynamic> json) => _$ResultModelFromJson(json); } @freezed class AnilistModel with _$AnilistModel { const factory AnilistModel({ int? id, int? idMal, TitleModel? title, List<String>? synonyms, bool? isAdult, }) = _AnilistModel; factory AnilistModel.fromJson(Map<String, dynamic> json) => _$AnilistModelFromJson(json); } @freezed class TitleModel with _$TitleModel { const factory TitleModel({ String? native, String? romaji, String? english, }) = _TitleModel; factory TitleModel.fromJson(Map<String, dynamic> json) => _$TitleModelFromJson(json); }
0
mirrored_repositories/find_anime/packages/tracemoe_api/lib/src
mirrored_repositories/find_anime/packages/tracemoe_api/lib/src/models/search_result.freezed.dart
// coverage:ignore-file // GENERATED CODE - DO NOT MODIFY BY HAND // ignore_for_file: type=lint // ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target part of 'search_result.dart'; // ************************************************************************** // FreezedGenerator // ************************************************************************** T _$identity<T>(T value) => value; final _privateConstructorUsedError = UnsupportedError( 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#custom-getters-and-methods'); SearchResultModel _$SearchResultModelFromJson(Map<String, dynamic> json) { return _SearchResultModel.fromJson(json); } /// @nodoc mixin _$SearchResultModel { int? get frameCount => throw _privateConstructorUsedError; String? get error => throw _privateConstructorUsedError; List<ResultModel>? get result => throw _privateConstructorUsedError; Map<String, dynamic> toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) $SearchResultModelCopyWith<SearchResultModel> get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $SearchResultModelCopyWith<$Res> { factory $SearchResultModelCopyWith( SearchResultModel value, $Res Function(SearchResultModel) then) = _$SearchResultModelCopyWithImpl<$Res>; $Res call({int? frameCount, String? error, List<ResultModel>? result}); } /// @nodoc class _$SearchResultModelCopyWithImpl<$Res> implements $SearchResultModelCopyWith<$Res> { _$SearchResultModelCopyWithImpl(this._value, this._then); final SearchResultModel _value; // ignore: unused_field final $Res Function(SearchResultModel) _then; @override $Res call({ Object? frameCount = freezed, Object? error = freezed, Object? result = freezed, }) { return _then(_value.copyWith( frameCount: frameCount == freezed ? _value.frameCount : frameCount // ignore: cast_nullable_to_non_nullable as int?, error: error == freezed ? _value.error : error // ignore: cast_nullable_to_non_nullable as String?, result: result == freezed ? _value.result : result // ignore: cast_nullable_to_non_nullable as List<ResultModel>?, )); } } /// @nodoc abstract class _$$_SearchResultModelCopyWith<$Res> implements $SearchResultModelCopyWith<$Res> { factory _$$_SearchResultModelCopyWith(_$_SearchResultModel value, $Res Function(_$_SearchResultModel) then) = __$$_SearchResultModelCopyWithImpl<$Res>; @override $Res call({int? frameCount, String? error, List<ResultModel>? result}); } /// @nodoc class __$$_SearchResultModelCopyWithImpl<$Res> extends _$SearchResultModelCopyWithImpl<$Res> implements _$$_SearchResultModelCopyWith<$Res> { __$$_SearchResultModelCopyWithImpl( _$_SearchResultModel _value, $Res Function(_$_SearchResultModel) _then) : super(_value, (v) => _then(v as _$_SearchResultModel)); @override _$_SearchResultModel get _value => super._value as _$_SearchResultModel; @override $Res call({ Object? frameCount = freezed, Object? error = freezed, Object? result = freezed, }) { return _then(_$_SearchResultModel( frameCount: frameCount == freezed ? _value.frameCount : frameCount // ignore: cast_nullable_to_non_nullable as int?, error: error == freezed ? _value.error : error // ignore: cast_nullable_to_non_nullable as String?, result: result == freezed ? _value._result : result // ignore: cast_nullable_to_non_nullable as List<ResultModel>?, )); } } /// @nodoc @JsonSerializable() class _$_SearchResultModel implements _SearchResultModel { const _$_SearchResultModel( {this.frameCount, this.error, final List<ResultModel>? result}) : _result = result; factory _$_SearchResultModel.fromJson(Map<String, dynamic> json) => _$$_SearchResultModelFromJson(json); @override final int? frameCount; @override final String? error; final List<ResultModel>? _result; @override List<ResultModel>? get result { final value = _result; if (value == null) return null; // ignore: implicit_dynamic_type return EqualUnmodifiableListView(value); } @override String toString() { return 'SearchResultModel(frameCount: $frameCount, error: $error, result: $result)'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_SearchResultModel && const DeepCollectionEquality() .equals(other.frameCount, frameCount) && const DeepCollectionEquality().equals(other.error, error) && const DeepCollectionEquality().equals(other._result, _result)); } @JsonKey(ignore: true) @override int get hashCode => Object.hash( runtimeType, const DeepCollectionEquality().hash(frameCount), const DeepCollectionEquality().hash(error), const DeepCollectionEquality().hash(_result)); @JsonKey(ignore: true) @override _$$_SearchResultModelCopyWith<_$_SearchResultModel> get copyWith => __$$_SearchResultModelCopyWithImpl<_$_SearchResultModel>( this, _$identity); @override Map<String, dynamic> toJson() { return _$$_SearchResultModelToJson( this, ); } } abstract class _SearchResultModel implements SearchResultModel { const factory _SearchResultModel( {final int? frameCount, final String? error, final List<ResultModel>? result}) = _$_SearchResultModel; factory _SearchResultModel.fromJson(Map<String, dynamic> json) = _$_SearchResultModel.fromJson; @override int? get frameCount; @override String? get error; @override List<ResultModel>? get result; @override @JsonKey(ignore: true) _$$_SearchResultModelCopyWith<_$_SearchResultModel> get copyWith => throw _privateConstructorUsedError; } ResultModel _$ResultModelFromJson(Map<String, dynamic> json) { return _ResultModel.fromJson(json); } /// @nodoc mixin _$ResultModel { AnilistModel? get anilist => throw _privateConstructorUsedError; String? get filename => throw _privateConstructorUsedError; num? get episode => throw _privateConstructorUsedError; num? get from => throw _privateConstructorUsedError; num? get to => throw _privateConstructorUsedError; num? get similarity => throw _privateConstructorUsedError; String? get video => throw _privateConstructorUsedError; String? get image => throw _privateConstructorUsedError; Map<String, dynamic> toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) $ResultModelCopyWith<ResultModel> get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $ResultModelCopyWith<$Res> { factory $ResultModelCopyWith( ResultModel value, $Res Function(ResultModel) then) = _$ResultModelCopyWithImpl<$Res>; $Res call( {AnilistModel? anilist, String? filename, num? episode, num? from, num? to, num? similarity, String? video, String? image}); $AnilistModelCopyWith<$Res>? get anilist; } /// @nodoc class _$ResultModelCopyWithImpl<$Res> implements $ResultModelCopyWith<$Res> { _$ResultModelCopyWithImpl(this._value, this._then); final ResultModel _value; // ignore: unused_field final $Res Function(ResultModel) _then; @override $Res call({ Object? anilist = freezed, Object? filename = freezed, Object? episode = freezed, Object? from = freezed, Object? to = freezed, Object? similarity = freezed, Object? video = freezed, Object? image = freezed, }) { return _then(_value.copyWith( anilist: anilist == freezed ? _value.anilist : anilist // ignore: cast_nullable_to_non_nullable as AnilistModel?, filename: filename == freezed ? _value.filename : filename // ignore: cast_nullable_to_non_nullable as String?, episode: episode == freezed ? _value.episode : episode // ignore: cast_nullable_to_non_nullable as num?, from: from == freezed ? _value.from : from // ignore: cast_nullable_to_non_nullable as num?, to: to == freezed ? _value.to : to // ignore: cast_nullable_to_non_nullable as num?, similarity: similarity == freezed ? _value.similarity : similarity // ignore: cast_nullable_to_non_nullable as num?, video: video == freezed ? _value.video : video // ignore: cast_nullable_to_non_nullable as String?, image: image == freezed ? _value.image : image // ignore: cast_nullable_to_non_nullable as String?, )); } @override $AnilistModelCopyWith<$Res>? get anilist { if (_value.anilist == null) { return null; } return $AnilistModelCopyWith<$Res>(_value.anilist!, (value) { return _then(_value.copyWith(anilist: value)); }); } } /// @nodoc abstract class _$$_ResultModelCopyWith<$Res> implements $ResultModelCopyWith<$Res> { factory _$$_ResultModelCopyWith( _$_ResultModel value, $Res Function(_$_ResultModel) then) = __$$_ResultModelCopyWithImpl<$Res>; @override $Res call( {AnilistModel? anilist, String? filename, num? episode, num? from, num? to, num? similarity, String? video, String? image}); @override $AnilistModelCopyWith<$Res>? get anilist; } /// @nodoc class __$$_ResultModelCopyWithImpl<$Res> extends _$ResultModelCopyWithImpl<$Res> implements _$$_ResultModelCopyWith<$Res> { __$$_ResultModelCopyWithImpl( _$_ResultModel _value, $Res Function(_$_ResultModel) _then) : super(_value, (v) => _then(v as _$_ResultModel)); @override _$_ResultModel get _value => super._value as _$_ResultModel; @override $Res call({ Object? anilist = freezed, Object? filename = freezed, Object? episode = freezed, Object? from = freezed, Object? to = freezed, Object? similarity = freezed, Object? video = freezed, Object? image = freezed, }) { return _then(_$_ResultModel( anilist: anilist == freezed ? _value.anilist : anilist // ignore: cast_nullable_to_non_nullable as AnilistModel?, filename: filename == freezed ? _value.filename : filename // ignore: cast_nullable_to_non_nullable as String?, episode: episode == freezed ? _value.episode : episode // ignore: cast_nullable_to_non_nullable as num?, from: from == freezed ? _value.from : from // ignore: cast_nullable_to_non_nullable as num?, to: to == freezed ? _value.to : to // ignore: cast_nullable_to_non_nullable as num?, similarity: similarity == freezed ? _value.similarity : similarity // ignore: cast_nullable_to_non_nullable as num?, video: video == freezed ? _value.video : video // ignore: cast_nullable_to_non_nullable as String?, image: image == freezed ? _value.image : image // ignore: cast_nullable_to_non_nullable as String?, )); } } /// @nodoc @JsonSerializable() class _$_ResultModel implements _ResultModel { const _$_ResultModel( {this.anilist, this.filename, this.episode, this.from, this.to, this.similarity, this.video, this.image}); factory _$_ResultModel.fromJson(Map<String, dynamic> json) => _$$_ResultModelFromJson(json); @override final AnilistModel? anilist; @override final String? filename; @override final num? episode; @override final num? from; @override final num? to; @override final num? similarity; @override final String? video; @override final String? image; @override String toString() { return 'ResultModel(anilist: $anilist, filename: $filename, episode: $episode, from: $from, to: $to, similarity: $similarity, video: $video, image: $image)'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_ResultModel && const DeepCollectionEquality().equals(other.anilist, anilist) && const DeepCollectionEquality().equals(other.filename, filename) && const DeepCollectionEquality().equals(other.episode, episode) && const DeepCollectionEquality().equals(other.from, from) && const DeepCollectionEquality().equals(other.to, to) && const DeepCollectionEquality() .equals(other.similarity, similarity) && const DeepCollectionEquality().equals(other.video, video) && const DeepCollectionEquality().equals(other.image, image)); } @JsonKey(ignore: true) @override int get hashCode => Object.hash( runtimeType, const DeepCollectionEquality().hash(anilist), const DeepCollectionEquality().hash(filename), const DeepCollectionEquality().hash(episode), const DeepCollectionEquality().hash(from), const DeepCollectionEquality().hash(to), const DeepCollectionEquality().hash(similarity), const DeepCollectionEquality().hash(video), const DeepCollectionEquality().hash(image)); @JsonKey(ignore: true) @override _$$_ResultModelCopyWith<_$_ResultModel> get copyWith => __$$_ResultModelCopyWithImpl<_$_ResultModel>(this, _$identity); @override Map<String, dynamic> toJson() { return _$$_ResultModelToJson( this, ); } } abstract class _ResultModel implements ResultModel { const factory _ResultModel( {final AnilistModel? anilist, final String? filename, final num? episode, final num? from, final num? to, final num? similarity, final String? video, final String? image}) = _$_ResultModel; factory _ResultModel.fromJson(Map<String, dynamic> json) = _$_ResultModel.fromJson; @override AnilistModel? get anilist; @override String? get filename; @override num? get episode; @override num? get from; @override num? get to; @override num? get similarity; @override String? get video; @override String? get image; @override @JsonKey(ignore: true) _$$_ResultModelCopyWith<_$_ResultModel> get copyWith => throw _privateConstructorUsedError; } AnilistModel _$AnilistModelFromJson(Map<String, dynamic> json) { return _AnilistModel.fromJson(json); } /// @nodoc mixin _$AnilistModel { int? get id => throw _privateConstructorUsedError; int? get idMal => throw _privateConstructorUsedError; TitleModel? get title => throw _privateConstructorUsedError; List<String>? get synonyms => throw _privateConstructorUsedError; bool? get isAdult => throw _privateConstructorUsedError; Map<String, dynamic> toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) $AnilistModelCopyWith<AnilistModel> get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $AnilistModelCopyWith<$Res> { factory $AnilistModelCopyWith( AnilistModel value, $Res Function(AnilistModel) then) = _$AnilistModelCopyWithImpl<$Res>; $Res call( {int? id, int? idMal, TitleModel? title, List<String>? synonyms, bool? isAdult}); $TitleModelCopyWith<$Res>? get title; } /// @nodoc class _$AnilistModelCopyWithImpl<$Res> implements $AnilistModelCopyWith<$Res> { _$AnilistModelCopyWithImpl(this._value, this._then); final AnilistModel _value; // ignore: unused_field final $Res Function(AnilistModel) _then; @override $Res call({ Object? id = freezed, Object? idMal = freezed, Object? title = freezed, Object? synonyms = freezed, Object? isAdult = freezed, }) { return _then(_value.copyWith( id: id == freezed ? _value.id : id // ignore: cast_nullable_to_non_nullable as int?, idMal: idMal == freezed ? _value.idMal : idMal // ignore: cast_nullable_to_non_nullable as int?, title: title == freezed ? _value.title : title // ignore: cast_nullable_to_non_nullable as TitleModel?, synonyms: synonyms == freezed ? _value.synonyms : synonyms // ignore: cast_nullable_to_non_nullable as List<String>?, isAdult: isAdult == freezed ? _value.isAdult : isAdult // ignore: cast_nullable_to_non_nullable as bool?, )); } @override $TitleModelCopyWith<$Res>? get title { if (_value.title == null) { return null; } return $TitleModelCopyWith<$Res>(_value.title!, (value) { return _then(_value.copyWith(title: value)); }); } } /// @nodoc abstract class _$$_AnilistModelCopyWith<$Res> implements $AnilistModelCopyWith<$Res> { factory _$$_AnilistModelCopyWith( _$_AnilistModel value, $Res Function(_$_AnilistModel) then) = __$$_AnilistModelCopyWithImpl<$Res>; @override $Res call( {int? id, int? idMal, TitleModel? title, List<String>? synonyms, bool? isAdult}); @override $TitleModelCopyWith<$Res>? get title; } /// @nodoc class __$$_AnilistModelCopyWithImpl<$Res> extends _$AnilistModelCopyWithImpl<$Res> implements _$$_AnilistModelCopyWith<$Res> { __$$_AnilistModelCopyWithImpl( _$_AnilistModel _value, $Res Function(_$_AnilistModel) _then) : super(_value, (v) => _then(v as _$_AnilistModel)); @override _$_AnilistModel get _value => super._value as _$_AnilistModel; @override $Res call({ Object? id = freezed, Object? idMal = freezed, Object? title = freezed, Object? synonyms = freezed, Object? isAdult = freezed, }) { return _then(_$_AnilistModel( id: id == freezed ? _value.id : id // ignore: cast_nullable_to_non_nullable as int?, idMal: idMal == freezed ? _value.idMal : idMal // ignore: cast_nullable_to_non_nullable as int?, title: title == freezed ? _value.title : title // ignore: cast_nullable_to_non_nullable as TitleModel?, synonyms: synonyms == freezed ? _value._synonyms : synonyms // ignore: cast_nullable_to_non_nullable as List<String>?, isAdult: isAdult == freezed ? _value.isAdult : isAdult // ignore: cast_nullable_to_non_nullable as bool?, )); } } /// @nodoc @JsonSerializable() class _$_AnilistModel implements _AnilistModel { const _$_AnilistModel( {this.id, this.idMal, this.title, final List<String>? synonyms, this.isAdult}) : _synonyms = synonyms; factory _$_AnilistModel.fromJson(Map<String, dynamic> json) => _$$_AnilistModelFromJson(json); @override final int? id; @override final int? idMal; @override final TitleModel? title; final List<String>? _synonyms; @override List<String>? get synonyms { final value = _synonyms; if (value == null) return null; // ignore: implicit_dynamic_type return EqualUnmodifiableListView(value); } @override final bool? isAdult; @override String toString() { return 'AnilistModel(id: $id, idMal: $idMal, title: $title, synonyms: $synonyms, isAdult: $isAdult)'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_AnilistModel && const DeepCollectionEquality().equals(other.id, id) && const DeepCollectionEquality().equals(other.idMal, idMal) && const DeepCollectionEquality().equals(other.title, title) && const DeepCollectionEquality().equals(other._synonyms, _synonyms) && const DeepCollectionEquality().equals(other.isAdult, isAdult)); } @JsonKey(ignore: true) @override int get hashCode => Object.hash( runtimeType, const DeepCollectionEquality().hash(id), const DeepCollectionEquality().hash(idMal), const DeepCollectionEquality().hash(title), const DeepCollectionEquality().hash(_synonyms), const DeepCollectionEquality().hash(isAdult)); @JsonKey(ignore: true) @override _$$_AnilistModelCopyWith<_$_AnilistModel> get copyWith => __$$_AnilistModelCopyWithImpl<_$_AnilistModel>(this, _$identity); @override Map<String, dynamic> toJson() { return _$$_AnilistModelToJson( this, ); } } abstract class _AnilistModel implements AnilistModel { const factory _AnilistModel( {final int? id, final int? idMal, final TitleModel? title, final List<String>? synonyms, final bool? isAdult}) = _$_AnilistModel; factory _AnilistModel.fromJson(Map<String, dynamic> json) = _$_AnilistModel.fromJson; @override int? get id; @override int? get idMal; @override TitleModel? get title; @override List<String>? get synonyms; @override bool? get isAdult; @override @JsonKey(ignore: true) _$$_AnilistModelCopyWith<_$_AnilistModel> get copyWith => throw _privateConstructorUsedError; } TitleModel _$TitleModelFromJson(Map<String, dynamic> json) { return _TitleModel.fromJson(json); } /// @nodoc mixin _$TitleModel { String? get native => throw _privateConstructorUsedError; String? get romaji => throw _privateConstructorUsedError; String? get english => throw _privateConstructorUsedError; Map<String, dynamic> toJson() => throw _privateConstructorUsedError; @JsonKey(ignore: true) $TitleModelCopyWith<TitleModel> get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $TitleModelCopyWith<$Res> { factory $TitleModelCopyWith( TitleModel value, $Res Function(TitleModel) then) = _$TitleModelCopyWithImpl<$Res>; $Res call({String? native, String? romaji, String? english}); } /// @nodoc class _$TitleModelCopyWithImpl<$Res> implements $TitleModelCopyWith<$Res> { _$TitleModelCopyWithImpl(this._value, this._then); final TitleModel _value; // ignore: unused_field final $Res Function(TitleModel) _then; @override $Res call({ Object? native = freezed, Object? romaji = freezed, Object? english = freezed, }) { return _then(_value.copyWith( native: native == freezed ? _value.native : native // ignore: cast_nullable_to_non_nullable as String?, romaji: romaji == freezed ? _value.romaji : romaji // ignore: cast_nullable_to_non_nullable as String?, english: english == freezed ? _value.english : english // ignore: cast_nullable_to_non_nullable as String?, )); } } /// @nodoc abstract class _$$_TitleModelCopyWith<$Res> implements $TitleModelCopyWith<$Res> { factory _$$_TitleModelCopyWith( _$_TitleModel value, $Res Function(_$_TitleModel) then) = __$$_TitleModelCopyWithImpl<$Res>; @override $Res call({String? native, String? romaji, String? english}); } /// @nodoc class __$$_TitleModelCopyWithImpl<$Res> extends _$TitleModelCopyWithImpl<$Res> implements _$$_TitleModelCopyWith<$Res> { __$$_TitleModelCopyWithImpl( _$_TitleModel _value, $Res Function(_$_TitleModel) _then) : super(_value, (v) => _then(v as _$_TitleModel)); @override _$_TitleModel get _value => super._value as _$_TitleModel; @override $Res call({ Object? native = freezed, Object? romaji = freezed, Object? english = freezed, }) { return _then(_$_TitleModel( native: native == freezed ? _value.native : native // ignore: cast_nullable_to_non_nullable as String?, romaji: romaji == freezed ? _value.romaji : romaji // ignore: cast_nullable_to_non_nullable as String?, english: english == freezed ? _value.english : english // ignore: cast_nullable_to_non_nullable as String?, )); } } /// @nodoc @JsonSerializable() class _$_TitleModel implements _TitleModel { const _$_TitleModel({this.native, this.romaji, this.english}); factory _$_TitleModel.fromJson(Map<String, dynamic> json) => _$$_TitleModelFromJson(json); @override final String? native; @override final String? romaji; @override final String? english; @override String toString() { return 'TitleModel(native: $native, romaji: $romaji, english: $english)'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_TitleModel && const DeepCollectionEquality().equals(other.native, native) && const DeepCollectionEquality().equals(other.romaji, romaji) && const DeepCollectionEquality().equals(other.english, english)); } @JsonKey(ignore: true) @override int get hashCode => Object.hash( runtimeType, const DeepCollectionEquality().hash(native), const DeepCollectionEquality().hash(romaji), const DeepCollectionEquality().hash(english)); @JsonKey(ignore: true) @override _$$_TitleModelCopyWith<_$_TitleModel> get copyWith => __$$_TitleModelCopyWithImpl<_$_TitleModel>(this, _$identity); @override Map<String, dynamic> toJson() { return _$$_TitleModelToJson( this, ); } } abstract class _TitleModel implements TitleModel { const factory _TitleModel( {final String? native, final String? romaji, final String? english}) = _$_TitleModel; factory _TitleModel.fromJson(Map<String, dynamic> json) = _$_TitleModel.fromJson; @override String? get native; @override String? get romaji; @override String? get english; @override @JsonKey(ignore: true) _$$_TitleModelCopyWith<_$_TitleModel> get copyWith => throw _privateConstructorUsedError; }
0
mirrored_repositories/find_anime/packages/tracemoe_api/lib/src
mirrored_repositories/find_anime/packages/tracemoe_api/lib/src/models/search_result.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'search_result.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** _$_SearchResultModel _$$_SearchResultModelFromJson(Map<String, dynamic> json) => _$_SearchResultModel( frameCount: json['frameCount'] as int?, error: json['error'] as String?, result: (json['result'] as List<dynamic>?) ?.map((e) => ResultModel.fromJson(e as Map<String, dynamic>)) .toList(), ); Map<String, dynamic> _$$_SearchResultModelToJson( _$_SearchResultModel instance) => <String, dynamic>{ 'frameCount': instance.frameCount, 'error': instance.error, 'result': instance.result, }; _$_ResultModel _$$_ResultModelFromJson(Map<String, dynamic> json) => _$_ResultModel( anilist: json['anilist'] == null ? null : AnilistModel.fromJson(json['anilist'] as Map<String, dynamic>), filename: json['filename'] as String?, episode: json['episode'] as num?, from: json['from'] as num?, to: json['to'] as num?, similarity: json['similarity'] as num?, video: json['video'] as String?, image: json['image'] as String?, ); Map<String, dynamic> _$$_ResultModelToJson(_$_ResultModel instance) => <String, dynamic>{ 'anilist': instance.anilist, 'filename': instance.filename, 'episode': instance.episode, 'from': instance.from, 'to': instance.to, 'similarity': instance.similarity, 'video': instance.video, 'image': instance.image, }; _$_AnilistModel _$$_AnilistModelFromJson(Map<String, dynamic> json) => _$_AnilistModel( id: json['id'] as int?, idMal: json['idMal'] as int?, title: json['title'] == null ? null : TitleModel.fromJson(json['title'] as Map<String, dynamic>), synonyms: (json['synonyms'] as List<dynamic>?) ?.map((e) => e as String) .toList(), isAdult: json['isAdult'] as bool?, ); Map<String, dynamic> _$$_AnilistModelToJson(_$_AnilistModel instance) => <String, dynamic>{ 'id': instance.id, 'idMal': instance.idMal, 'title': instance.title, 'synonyms': instance.synonyms, 'isAdult': instance.isAdult, }; _$_TitleModel _$$_TitleModelFromJson(Map<String, dynamic> json) => _$_TitleModel( native: json['native'] as String?, romaji: json['romaji'] as String?, english: json['english'] as String?, ); Map<String, dynamic> _$$_TitleModelToJson(_$_TitleModel instance) => <String, dynamic>{ 'native': instance.native, 'romaji': instance.romaji, 'english': instance.english, };
0
mirrored_repositories/find_anime/packages/tracemoe_api
mirrored_repositories/find_anime/packages/tracemoe_api/test/tracemoe_api_client_test.dart
import 'dart:typed_data'; import 'package:flutter_test/flutter_test.dart'; import 'package:http/http.dart' as http; import 'package:mocktail/mocktail.dart'; import 'package:tracemoe_api/tracemoe_api.dart'; class MockHttpClient extends Mock implements http.Client {} class MockResponse extends Mock implements http.Response {} class FakeUri extends Fake implements Uri {} void main() { group('TraceMoeApiClient', () { late http.Client httpClient; late TraceMoeApiClient traceMoeApiClient; String jsonBody = '''{ "frameCount": 26914796, "error": "", "result": [ { "anilist": { "id": 577, "idMal": 577, "title": { "native": "鍵姫物語 永久アリス輪舞曲", "romaji": "Kagihime Monogatari: Eikyuu Alice Rinbukyoku", "english": "Key Princess Story Eternal Alice Rondo" }, "synonyms": [ "Kagihime", "Kagihime Monogatari Eikyuu Alice Rondo", "Kagihime Monogatari - Eikyuu Alice Rondo" ], "isAdult": false }, "filename": "Kagihime Monogatari - 01 A Rabbit Hole.mp4", "episode": 1, "from": 522.25, "to": 527.25, "similarity": 0.8873692863583079, "video": "https://media.trace.moe/video/577/Kagihime%20Monogatari%20-%2001%20A%20Rabbit%20Hole.mp4?t=524.75&now=1659085200&token=j2kR4rEooHoNpEug5bCSNgRXg", "image": "https://media.trace.moe/image/577/Kagihime%20Monogatari%20-%2001%20A%20Rabbit%20Hole.mp4.jpg?t=524.75&now=1659085200&token=yMsMX11FeIoNHYgtZHlKw9zTdUk" } ] }'''; setUpAll(() { registerFallbackValue(FakeUri()); }); setUp(() { httpClient = MockHttpClient(); traceMoeApiClient = TraceMoeApiClient(httpClient: httpClient); }); group('constructor', () { test('does not require am httpClient', () { expect(TraceMoeApiClient(), isNotNull); }); }); group('search via image url', () { const searchQuery = 'mock-search'; const baseUrl = 'https://api.trace.moe/search?anilistInfo'; test('check get request with 200 postcode', () async { final response = MockResponse(); when(() => response.statusCode).thenReturn(200); when(() => response.body).thenReturn('{}'); when(() => httpClient.get(any())).thenAnswer((_) async => response); try { await traceMoeApiClient.getResultByImageUrl(searchQuery); } catch (_) {} verify( () => httpClient.get( Uri.parse('$baseUrl&url=$searchQuery'), ), ).called(1); }); test('make get result with 500 postcode', () { final response = MockResponse(); when(() => response.statusCode).thenReturn(500); when(() => response.body).thenReturn('{}'); when(() => httpClient.get(any())).thenAnswer((_) async => response); expect( () async => await traceMoeApiClient.getResultByImageUrl(searchQuery), throwsA(isA<SearchInternalErrorFailure>())); }); test('make get result with 503 postcode', () { final response = MockResponse(); when(() => response.statusCode).thenReturn(503); when(() => response.body).thenReturn('{}'); when(() => httpClient.get(any())).thenAnswer((_) async => response); expect( () async => await traceMoeApiClient.getResultByImageUrl(searchQuery), throwsA(isA<SearchQueueIsFullFailure>())); }); test('make get result with 504 postcode', () { final response = MockResponse(); when(() => response.statusCode).thenReturn(504); when(() => response.body).thenReturn('{}'); when(() => httpClient.get(any())).thenAnswer((_) async => response); expect( () async => await traceMoeApiClient.getResultByImageUrl(searchQuery), throwsA(isA<SearchServerOverloadFailure>())); }); test('make get result with 405 postcode', () { final response = MockResponse(); when(() => response.statusCode).thenReturn(405); when(() => response.body).thenReturn('{}'); when(() => httpClient.get(any())).thenAnswer((_) async => response); expect( () async => await traceMoeApiClient.getResultByImageUrl(searchQuery), throwsA(isA<MethodIsNotAllowedFailure>())); }); test('make get result with 403 postcode', () { final response = MockResponse(); when(() => response.statusCode).thenReturn(403); when(() => response.body).thenReturn('{}'); when(() => httpClient.get(any())).thenAnswer((_) async => response); expect( () async => await traceMoeApiClient.getResultByImageUrl(searchQuery), throwsA(isA<InvalidApiKeyFailure>())); }); test('make get result with 402 postcode', () { final response = MockResponse(); when(() => response.statusCode).thenReturn(402); when(() => response.body).thenReturn('{}'); when(() => httpClient.get(any())).thenAnswer((_) async => response); expect( () async => await traceMoeApiClient.getResultByImageUrl(searchQuery), throwsA(isA<SearchQuotaDepletedFailure>())); }); test('make get result with 400 postcode', () { final response = MockResponse(); when(() => response.statusCode).thenReturn(400); when(() => response.body).thenReturn('{}'); when(() => httpClient.get(any())).thenAnswer((_) async => response); expect( () async => await traceMoeApiClient.getResultByImageUrl(searchQuery), throwsA(isA<InvalidImageUrlFailure>())); }); test('make get result with any other postcode', () { final response = MockResponse(); when(() => response.statusCode).thenReturn(404); when(() => response.body).thenReturn('{}'); when(() => httpClient.get(any())).thenAnswer((_) async => response); expect( () async => await traceMoeApiClient.getResultByImageUrl(searchQuery), throwsA(isA<Exception>())); }); test('make get result with valid response', () async { final response = MockResponse(); when(() => response.statusCode).thenReturn(200); when(() => response.body).thenReturn(jsonBody); when(() => httpClient.get(any())).thenAnswer((_) async => response); final result = await traceMoeApiClient.getResultByImageUrl(searchQuery); expect( result, isA<SearchResultModel>() .having((p0) => p0.result!.length, 'length of list<Anilist>', 1) .having((p0) => p0.frameCount, 'type check', isA<int?>()) .having((p0) => p0.result!.first.anilist!.isAdult, 'type check isAdult', allOf(isA<bool>(), false)), ); }); }); group('search via file', () { Uint8List fileBytes = Uint8List(10); const mimeType = 'image/png'; const baseUrl = 'https://api.trace.moe/search?anilistInfo'; test('check post request with 200 postcode', () async { final response = MockResponse(); when(() => response.statusCode).thenReturn(200); when(() => response.body).thenReturn('{}'); when(() => httpClient.post(any())).thenAnswer((_) async => response); try { await traceMoeApiClient.getResultByFile(fileBytes, mimeType: mimeType); } catch (_) {} verify( () => httpClient.post( Uri.parse(baseUrl), headers: { 'Content-Type': mimeType, }, body: fileBytes, ), ).called(1); }); test('make post request with 200 postcode', () async { final response = MockResponse(); when(() => response.statusCode).thenReturn(200); when(() => response.body).thenReturn(jsonBody); when( () => httpClient.post( any(), body: any(named: 'body'), headers: any(named: 'headers'), ), ).thenAnswer((_) async => response); final result = await traceMoeApiClient.getResultByFile(fileBytes, mimeType: mimeType); expect( result, isA<SearchResultModel>() .having((p0) => p0.result!.length, 'length of list<Anilist>', 1) .having((p0) => p0.frameCount, 'type check', isA<int?>()) .having((p0) => p0.result!.first.anilist!.isAdult, 'type check isAdult', allOf(isA<bool>(), false)), ); }); test('make post request with non-200 postcode', () async { final response = MockResponse(); when(() => response.statusCode).thenReturn(402); when(() => response.body).thenReturn(jsonBody); when( () => httpClient.post( any(), body: any(named: 'body'), headers: any(named: 'headers'), ), ).thenAnswer((_) async => response); expect( () async => await traceMoeApiClient.getResultByFile(fileBytes, mimeType: mimeType), throwsA(isA<SearchQuotaDepletedFailure>())); }); }); }); }
0
mirrored_repositories/find_anime/packages/tracemoe_api
mirrored_repositories/find_anime/packages/tracemoe_api/test/tracemoe_api_test.dart
import 'package:flutter_test/flutter_test.dart'; import 'package:tracemoe_api/tracemoe_api.dart'; void main() { group('SearchResultModel', () { group('fromJson', () { test( 'throws TypeError when result is unknown', () => { expect( () => SearchResultModel.fromJson(<String, dynamic>{ 'frameCount': 1, 'error': '', 'result': '', }), throwsA(isA<TypeError>()), ) }); }); }); }
0
mirrored_repositories/find_anime/packages/tracemoe_repository
mirrored_repositories/find_anime/packages/tracemoe_repository/lib/tracemoe_repository.dart
library tracemoe_repository; export 'src/tracemoe_repository.dart'; export 'src/models/result.dart';
0
mirrored_repositories/find_anime/packages/tracemoe_repository/lib
mirrored_repositories/find_anime/packages/tracemoe_repository/lib/src/tracemoe_repository.dart
import 'dart:typed_data'; import 'package:tracemoe_api/tracemoe_api.dart'; import 'package:tracemoe_repository/src/models/result.dart'; class EmptyResultFailure implements Exception {} class TraceMoeRepository { TraceMoeRepository({TraceMoeApiClient? traceMoeApiClient}) : _apiClient = traceMoeApiClient ?? TraceMoeApiClient(); final TraceMoeApiClient _apiClient; /// Returns simplified processed API result of search via image in /// list of [Resul] models. /// /// /// Will throw exceptions according to the API documentation: /// https://soruly.github.io/trace.moe-api/#/docs?id=error-codes Future<List<Result>> getResultByImageUrl(String url) async { try { final response = await _apiClient.getResultByImageUrl(url); return _getResultList(response); } catch (e) { rethrow; } } /// Returns simplified processed API result of search via file in /// list of [Resul] models. /// /// Media can be an **image/\***, **video/\*** or **gif**. /// If a different file type is sent, [InvalidImageUrlFailure] will be thrown. /// /// Will throw exceptions according to the API documentation: /// https://soruly.github.io/trace.moe-api/#/docs?id=error-codes Future<List<Result>> getResultByFile( Uint8List bytes, { required String mimeType, }) async { try { final response = await _apiClient.getResultByFile( bytes, mimeType: mimeType, ); return _getResultList(response); } catch (e) { rethrow; } } /// Processes raw API result and returns list of [Result]. /// /// Will throw [EmptyResultFailure] if result was empty. List<Result> _getResultList(SearchResultModel model) { if (model.result != null && model.result!.isNotEmpty) { List<Result> resultList = []; for (ResultModel result in model.result!) { resultList.add( Result( similarity: result.similarity == null ? '' : (result.similarity! * 100).toStringAsFixed(1), episode: result.episode ?? 0, moment: result.from ?? 0, video: result.video!, idMal: result.anilist!.idMal!, adultOnly: result.anilist!.isAdult ?? false, romajiName: result.anilist!.title!.romaji, japaneseName: result.anilist!.title!.native, ), ); } return resultList; } else { throw EmptyResultFailure(); } } }
0
mirrored_repositories/find_anime/packages/tracemoe_repository/lib/src
mirrored_repositories/find_anime/packages/tracemoe_repository/lib/src/models/result.freezed.dart
// coverage:ignore-file // GENERATED CODE - DO NOT MODIFY BY HAND // ignore_for_file: type=lint // ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target part of 'result.dart'; // ************************************************************************** // FreezedGenerator // ************************************************************************** T _$identity<T>(T value) => value; final _privateConstructorUsedError = UnsupportedError( 'It seems like you constructed your class using `MyClass._()`. This constructor is only meant to be used by freezed and you are not supposed to need it nor use it.\nPlease check the documentation here for more information: https://github.com/rrousselGit/freezed#custom-getters-and-methods'); /// @nodoc mixin _$Result { num get episode => throw _privateConstructorUsedError; String get similarity => throw _privateConstructorUsedError; num get moment => throw _privateConstructorUsedError; String get video => throw _privateConstructorUsedError; int get idMal => throw _privateConstructorUsedError; bool get adultOnly => throw _privateConstructorUsedError; String? get romajiName => throw _privateConstructorUsedError; String? get japaneseName => throw _privateConstructorUsedError; @JsonKey(ignore: true) $ResultCopyWith<Result> get copyWith => throw _privateConstructorUsedError; } /// @nodoc abstract class $ResultCopyWith<$Res> { factory $ResultCopyWith(Result value, $Res Function(Result) then) = _$ResultCopyWithImpl<$Res>; $Res call( {num episode, String similarity, num moment, String video, int idMal, bool adultOnly, String? romajiName, String? japaneseName}); } /// @nodoc class _$ResultCopyWithImpl<$Res> implements $ResultCopyWith<$Res> { _$ResultCopyWithImpl(this._value, this._then); final Result _value; // ignore: unused_field final $Res Function(Result) _then; @override $Res call({ Object? episode = freezed, Object? similarity = freezed, Object? moment = freezed, Object? video = freezed, Object? idMal = freezed, Object? adultOnly = freezed, Object? romajiName = freezed, Object? japaneseName = freezed, }) { return _then(_value.copyWith( episode: episode == freezed ? _value.episode : episode // ignore: cast_nullable_to_non_nullable as num, similarity: similarity == freezed ? _value.similarity : similarity // ignore: cast_nullable_to_non_nullable as String, moment: moment == freezed ? _value.moment : moment // ignore: cast_nullable_to_non_nullable as num, video: video == freezed ? _value.video : video // ignore: cast_nullable_to_non_nullable as String, idMal: idMal == freezed ? _value.idMal : idMal // ignore: cast_nullable_to_non_nullable as int, adultOnly: adultOnly == freezed ? _value.adultOnly : adultOnly // ignore: cast_nullable_to_non_nullable as bool, romajiName: romajiName == freezed ? _value.romajiName : romajiName // ignore: cast_nullable_to_non_nullable as String?, japaneseName: japaneseName == freezed ? _value.japaneseName : japaneseName // ignore: cast_nullable_to_non_nullable as String?, )); } } /// @nodoc abstract class _$$_ResultCopyWith<$Res> implements $ResultCopyWith<$Res> { factory _$$_ResultCopyWith(_$_Result value, $Res Function(_$_Result) then) = __$$_ResultCopyWithImpl<$Res>; @override $Res call( {num episode, String similarity, num moment, String video, int idMal, bool adultOnly, String? romajiName, String? japaneseName}); } /// @nodoc class __$$_ResultCopyWithImpl<$Res> extends _$ResultCopyWithImpl<$Res> implements _$$_ResultCopyWith<$Res> { __$$_ResultCopyWithImpl(_$_Result _value, $Res Function(_$_Result) _then) : super(_value, (v) => _then(v as _$_Result)); @override _$_Result get _value => super._value as _$_Result; @override $Res call({ Object? episode = freezed, Object? similarity = freezed, Object? moment = freezed, Object? video = freezed, Object? idMal = freezed, Object? adultOnly = freezed, Object? romajiName = freezed, Object? japaneseName = freezed, }) { return _then(_$_Result( episode: episode == freezed ? _value.episode : episode // ignore: cast_nullable_to_non_nullable as num, similarity: similarity == freezed ? _value.similarity : similarity // ignore: cast_nullable_to_non_nullable as String, moment: moment == freezed ? _value.moment : moment // ignore: cast_nullable_to_non_nullable as num, video: video == freezed ? _value.video : video // ignore: cast_nullable_to_non_nullable as String, idMal: idMal == freezed ? _value.idMal : idMal // ignore: cast_nullable_to_non_nullable as int, adultOnly: adultOnly == freezed ? _value.adultOnly : adultOnly // ignore: cast_nullable_to_non_nullable as bool, romajiName: romajiName == freezed ? _value.romajiName : romajiName // ignore: cast_nullable_to_non_nullable as String?, japaneseName: japaneseName == freezed ? _value.japaneseName : japaneseName // ignore: cast_nullable_to_non_nullable as String?, )); } } /// @nodoc class _$_Result implements _Result { const _$_Result( {required this.episode, required this.similarity, required this.moment, required this.video, required this.idMal, required this.adultOnly, required this.romajiName, required this.japaneseName}); @override final num episode; @override final String similarity; @override final num moment; @override final String video; @override final int idMal; @override final bool adultOnly; @override final String? romajiName; @override final String? japaneseName; @override String toString() { return 'Result(episode: $episode, similarity: $similarity, moment: $moment, video: $video, idMal: $idMal, adultOnly: $adultOnly, romajiName: $romajiName, japaneseName: $japaneseName)'; } @override bool operator ==(dynamic other) { return identical(this, other) || (other.runtimeType == runtimeType && other is _$_Result && const DeepCollectionEquality().equals(other.episode, episode) && const DeepCollectionEquality() .equals(other.similarity, similarity) && const DeepCollectionEquality().equals(other.moment, moment) && const DeepCollectionEquality().equals(other.video, video) && const DeepCollectionEquality().equals(other.idMal, idMal) && const DeepCollectionEquality().equals(other.adultOnly, adultOnly) && const DeepCollectionEquality() .equals(other.romajiName, romajiName) && const DeepCollectionEquality() .equals(other.japaneseName, japaneseName)); } @override int get hashCode => Object.hash( runtimeType, const DeepCollectionEquality().hash(episode), const DeepCollectionEquality().hash(similarity), const DeepCollectionEquality().hash(moment), const DeepCollectionEquality().hash(video), const DeepCollectionEquality().hash(idMal), const DeepCollectionEquality().hash(adultOnly), const DeepCollectionEquality().hash(romajiName), const DeepCollectionEquality().hash(japaneseName)); @JsonKey(ignore: true) @override _$$_ResultCopyWith<_$_Result> get copyWith => __$$_ResultCopyWithImpl<_$_Result>(this, _$identity); } abstract class _Result implements Result { const factory _Result( {required final num episode, required final String similarity, required final num moment, required final String video, required final int idMal, required final bool adultOnly, required final String? romajiName, required final String? japaneseName}) = _$_Result; @override num get episode; @override String get similarity; @override num get moment; @override String get video; @override int get idMal; @override bool get adultOnly; @override String? get romajiName; @override String? get japaneseName; @override @JsonKey(ignore: true) _$$_ResultCopyWith<_$_Result> get copyWith => throw _privateConstructorUsedError; }
0
mirrored_repositories/find_anime/packages/tracemoe_repository/lib/src
mirrored_repositories/find_anime/packages/tracemoe_repository/lib/src/models/result.dart
import 'package:freezed_annotation/freezed_annotation.dart'; part 'result.freezed.dart'; @freezed class Result with _$Result { const factory Result({ required num episode, required String similarity, required num moment, required String video, required int idMal, required bool adultOnly, required String? romajiName, required String? japaneseName, }) = _Result; }
0
mirrored_repositories/find_anime/packages/tracemoe_repository
mirrored_repositories/find_anime/packages/tracemoe_repository/test/tracemoe_repository_test.dart
import 'dart:typed_data'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:tracemoe_api/tracemoe_api.dart'; import 'package:tracemoe_repository/tracemoe_repository.dart'; class MockTraceMoeApiClient extends Mock implements TraceMoeApiClient {} class MockSearchResultModel extends Mock implements SearchResultModel {} void main() { group('TraceMoeRepository', () { late TraceMoeApiClient traceMoeApiClient; late TraceMoeRepository traceMoeRepository; setUpAll(() { registerFallbackValue(Uint8List(1)); }); setUp(() { traceMoeApiClient = MockTraceMoeApiClient(); traceMoeRepository = TraceMoeRepository(traceMoeApiClient: traceMoeApiClient); }); group('constructor', () { test('instantiates internal TraceMoeApiClient when not injected ', () { expect(TraceMoeRepository(), isNotNull); }); }); group('get result', () { const imageUrl = 'https://sample.com'; final imageBytes = Uint8List(1); const String mimeType = 'image/png'; test('get result via image url', () async { try { await traceMoeRepository.getResultByImageUrl(imageUrl); } catch (_) {} verify(() => traceMoeApiClient.getResultByImageUrl(imageUrl)).called(1); }); test('throws an exception when search via url fails', () async { when(() => traceMoeApiClient.getResultByImageUrl(any())) .thenThrow(SearchInternalErrorFailure()); expect( () async => await traceMoeRepository.getResultByImageUrl(imageUrl), throwsA(isA<SearchInternalErrorFailure>()), ); }); test('get result via file search', () async { try { await traceMoeRepository.getResultByFile( imageBytes, mimeType: mimeType, ); } catch (_) {} verify( () => traceMoeApiClient.getResultByFile( imageBytes, mimeType: mimeType, ), ).called(1); }); test('throws an exception when search via file fails', () { when( () => traceMoeApiClient.getResultByFile( any(), mimeType: any(named: 'mimeType'), ), ).thenThrow(InvalidImageUrlFailure()); expect( () async => await traceMoeRepository.getResultByFile( imageBytes, mimeType: mimeType, ), throwsA(isA<InvalidImageUrlFailure>()), ); }); test('throw EmptyResultException when search', () { final Future<SearchResultModel> future = Future<SearchResultModel>.delayed( Duration.zero, () => const SearchResultModel( frameCount: 0, error: '', result: [], ), ); when( () => traceMoeApiClient.getResultByImageUrl( any(), ), ).thenAnswer( (_) => future, ); when( () => traceMoeApiClient.getResultByFile( any(), mimeType: any(named: 'mimeType'), ), ).thenAnswer( (_) => future, ); expect( () => traceMoeRepository.getResultByImageUrl(imageUrl), throwsA( isA<EmptyResultFailure>(), ), ); expect( () => traceMoeRepository.getResultByFile( imageBytes, mimeType: mimeType, ), throwsA( isA<EmptyResultFailure>(), ), ); }); }); }); }
0
mirrored_repositories/Flutter-Http-Request-App
mirrored_repositories/Flutter-Http-Request-App/lib/main.dart
import 'package:flutter/material.dart'; import 'package:http_app/screens/home_page.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: HomePage(), ); } }
0
mirrored_repositories/Flutter-Http-Request-App/lib
mirrored_repositories/Flutter-Http-Request-App/lib/screens/home_page.dart
import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'dart:convert'; import 'dart:async'; class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { final String url = "https://swapi.co/api/people"; List data; @override void initState() { super.initState(); this.getJsonData(); } Future<String> getJsonData() async { var response = await http.get( // Encode the URL Uri.encodeFull(url), // only JSON response headers: {"Accept": "application/json"}); print(response.body); setState(() { var convertDataToJson = json.decode(response.body); data = convertDataToJson['results']; }); return "Success"; } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('HTTP App'), ), body: ListView.builder( itemCount: data == null ? 0 : data.length, itemBuilder: (BuildContext context, int index) { return Container( child: Center( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ Card( child: Container( child: Text(data[index]['name']), padding: EdgeInsets.all(20.0), ), ), ], ), ), ); }, ), ); } }
0
mirrored_repositories/Flutter-Http-Request-App
mirrored_repositories/Flutter-Http-Request-App/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:http_app/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/MoviesFlutter
mirrored_repositories/MoviesFlutter/lib/main.dart
import 'package:movies/src/pages/home_page.dart'; import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Movies', initialRoute: '/', routes: { '/' : (BuildContext context) => HomePage() } ); } }
0
mirrored_repositories/MoviesFlutter/lib/src
mirrored_repositories/MoviesFlutter/lib/src/widgets/card_swiper_widget.dart
import 'package:flutter/material.dart'; import 'package:flutter_swiper/flutter_swiper.dart'; import 'package:movies/src/models/movie_model.dart'; class CardSwiperWidget extends StatelessWidget { final List<Movie> movies; const CardSwiperWidget({@required this.movies}); @override Widget build(BuildContext context) { final _screenSize = MediaQuery.of(context).size; return Container( padding: EdgeInsets.only(top: 10.0), child: Swiper( layout: SwiperLayout.STACK, itemWidth: _screenSize.width * 0.7, itemHeight: _screenSize.height * 0.5, itemBuilder: (BuildContext context, int index) { return ClipRRect( borderRadius: BorderRadius.circular(20.0), child: FadeInImage( image: NetworkImage(movies[index].getPosterImg()), placeholder: AssetImage('assets/img/no-image.jpg'), fit: BoxFit.fill ), ); }, itemCount: movies.length, //pagination: new SwiperPagination(), //control: new SwiperControl(), ), ); } }
0
mirrored_repositories/MoviesFlutter/lib/src
mirrored_repositories/MoviesFlutter/lib/src/widgets/movie_horizontal.dart
import 'package:flutter/material.dart'; import 'package:movies/src/models/movie_model.dart'; class MovieHorizontal extends StatelessWidget { final List<Movie> movies; final Function nextPage; MovieHorizontal({ @required this.movies, @required this.nextPage }); final _pageController = PageController( initialPage: 1, viewportFraction: 0.3 ); @override Widget build(BuildContext context) { final _screenSize = MediaQuery.of(context).size; _pageController.addListener(() { if (_pageController.position.pixels >= _pageController.position.maxScrollExtent - 200) nextPage(); }); return Container( height: _screenSize.height * 0.28, child: PageView( controller: _pageController, pageSnapping: false, children: _cards(context), ), ); } List<Widget> _cards(BuildContext context) { return movies.map((movie) { return Container( margin: EdgeInsets.only(right: 15.0), child: Column( children: <Widget>[ ClipRRect( borderRadius: BorderRadius.circular(20.0), child: FadeInImage( image: NetworkImage(movie.getPosterImg()), placeholder: AssetImage('assets/img/no-image.jpg'), fit: BoxFit.cover, height: 160.0, ), ), SizedBox(height: 5.0), Text(movie.title, overflow: TextOverflow.ellipsis, style: Theme.of(context).textTheme.caption,) ], ), ); }).toList(); } }
0
mirrored_repositories/MoviesFlutter/lib/src
mirrored_repositories/MoviesFlutter/lib/src/pages/home_page.dart
import 'package:flutter/material.dart'; import 'package:movies/src/models/movie_model.dart'; import 'package:movies/src/providers/movies_provider.dart'; import 'package:movies/src/widgets/card_swiper_widget.dart'; import 'package:movies/src/widgets/movie_horizontal.dart'; class HomePage extends StatelessWidget { //const HomePage({Key key}) : super(key: key); final moviesProvider = MoviesProvider(); @override Widget build(BuildContext context) { moviesProvider.getPopular(); return Scaffold( appBar: AppBar( centerTitle: false, title: Text('Movies in theaters'), backgroundColor: Colors.indigoAccent, actions: <Widget>[ IconButton( icon: Icon(Icons.search), onPressed: () {}, ) ], ), body: Container( child: Column( children: <Widget>[ _swiperCards(), _footer(context) ], ))); } Widget _swiperCards() { return FutureBuilder( future: moviesProvider.getOnTheaters(), builder: (BuildContext context, AsyncSnapshot<List> snapshot) { if (snapshot.hasData) return CardSwiperWidget(movies: snapshot.data); else return Container( height: 400.0, child: Center( child: CircularProgressIndicator() ) ); }, ); //moviesProvider.getOnTheaters(); //return CardSwiperWidget( // movies: [1,2,3,4,5], //); } Widget _footer(BuildContext context) { return Container( width: double.infinity, child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ Container(padding: EdgeInsets.only(left: 20.0), child: Text('Popular', style: Theme.of(context).textTheme.subhead)), SizedBox(height: 5.0), StreamBuilder( stream: moviesProvider.popularStream, builder: (BuildContext context, AsyncSnapshot<List> snapshot) { snapshot.data?.forEach((p) => print(p.title)); // ? do the for each if exists data if (snapshot.hasData) return MovieHorizontal(movies: snapshot.data, nextPage: moviesProvider.getPopular); else return Center(child: CircularProgressIndicator()); }, ), ], ), ); } List<Text> _moviesTitles(List<Movie> data) { List<Text> moviesList = List<Text>(); data.forEach((movie) => moviesList.add(Text(movie.title))); moviesList.removeRange(0, 10); return moviesList; } }
0
mirrored_repositories/MoviesFlutter/lib/src
mirrored_repositories/MoviesFlutter/lib/src/models/movie_model.dart
class Movies { List<Movie> items = List(); Movies(); Movies.fromJsonList(List<dynamic> jsonList) { if (jsonList == null) return; for (var item in jsonList) { final movie = Movie.fromJsonMap(item); items.add(movie); } } } class Movie { int voteCount; int id; bool video; double voteAverage; String title; double popularity; String posterPath; String originalLanguage; String originalTitle; List<int> genreIds; String backdropPath; bool adult; String overview; String releaseDate; Movie({ this.voteCount, this.id, this.video, this.voteAverage, this.title, this.popularity, this.posterPath, this.originalLanguage, this.originalTitle, this.genreIds, this.backdropPath, this.adult, this.overview, this.releaseDate, }); Movie.fromJsonMap(Map<String, dynamic> movieJson) { voteCount = movieJson['vote_count']; id = movieJson['id']; video = movieJson['video']; voteAverage = movieJson['vote_average'] / 1; title = movieJson['title']; popularity = movieJson['popularity'] / 1; posterPath = movieJson['poster_path']; originalLanguage = movieJson['original_language']; originalTitle = movieJson['original_title']; genreIds = movieJson['genre_ids'].cast<int>(); backdropPath = movieJson['backdrop_path']; adult = movieJson['adult']; overview = movieJson['overview']; releaseDate = movieJson['release_date']; } getPosterImg() { if (posterPath == null) return 'https://www.heres.ee/pub/media/catalog/product/placeholder/default/white-image_1.png'; else return Uri.https('image.tmdb.org', 't/p/w500/$posterPath').toString();//image.tmdb.org/t/p/w500/$posterPath'; } }
0
mirrored_repositories/MoviesFlutter/lib/src
mirrored_repositories/MoviesFlutter/lib/src/providers/movies_provider.dart
import 'dart:async'; import 'dart:convert'; import 'package:http/http.dart' as http; import 'package:movies/src/models/movie_model.dart'; class MoviesProvider { String _apiKey = '4727032e58435cbe848ee26283a0e50b'; String _url = 'api.themoviedb.org'; String _language = 'es-GT'; int _popularPage = 0; List<Movie> _popular = List(); final _popularStreamController = StreamController<List<Movie>>.broadcast(); Function(List<Movie>) get popularSink => _popularStreamController.sink.add; Stream<List<Movie>> get popularStream => _popularStreamController.stream; void disposeStreams() { _popularStreamController?.close(); } Future<List<Movie>> getOnTheaters() async { final url = _buildUrl('3/movie/now_playing'); return await _processResponse(url); } Future<List<Movie>> getPopular() async { _popularPage++; final url = _buildUrl('3/movie/popular'); final response = await _processResponse(url); _popular.addAll(response); popularSink(_popular); return response; } Future<List<Movie>> _processResponse(Uri url) async { final response = await http.get(url); final decodedData = json.decode(response.body); final movies = Movies.fromJsonList(decodedData['results']); return movies.items; } Uri _buildUrl(String endPoint) { return Uri.https(_url, endPoint, { 'api_key' : _apiKey, 'language' : _language, 'page' : _popularPage == 0 ? '1' : _popularPage.toString() }); } }
0
mirrored_repositories/flutter-sliding-clipped-nav-bar-example/flutter_sliding_clipped_nav_bar_example
mirrored_repositories/flutter-sliding-clipped-nav-bar-example/flutter_sliding_clipped_nav_bar_example/lib/main.dart
import 'package:flutter/material.dart'; import 'package:sliding_clipped_nav_bar/sliding_clipped_nav_bar.dart'; import 'package:google_fonts/google_fonts.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return const MaterialApp( title: 'Flutter Sliding Clipped Nav Bar Package Example', debugShowCheckedModeBanner: false, home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({Key? key}) : super(key: key); @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { ///////////////////////////////////// //@CodeWithFlexz on Instagram // //AmirBayat0 on Github //Programming with Flexz on Youtube ///////////////////////////////////// late PageController _pageController; int selectedIndex = 0; bool _colorful = false; /// @override void initState() { super.initState(); _pageController = PageController(initialPage: selectedIndex); } /// METHOD FOR CHANGING APPBAR BACKGROUND COLOR Color appBarColor() { switch (selectedIndex) { case (0): return Colors.amber; case (1): return Colors.red; case (2): return Colors.deepPurpleAccent; case (3): return Colors.pinkAccent; default: return Colors.transparent; } } /// void onButtonPressed(int index) { setState(() { selectedIndex = index; }); _pageController.animateToPage(selectedIndex, duration: const Duration(milliseconds: 400), curve: Curves.easeOutQuad); } @override Widget build(BuildContext context) { return Scaffold( body: SafeArea( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ /// Custom AppBar AnimatedContainer( duration: const Duration(milliseconds: 300), color: appBarColor(), child: SwitchListTile( activeColor: Colors.white, title: Text( 'Colorful Navbar', style: GoogleFonts.oxygen(color: Colors.white), ), value: _colorful, onChanged: (bool value) { setState(() { _colorful = !_colorful; }); }, ), ), /// Main Body Expanded( child: PageView( physics: const NeverScrollableScrollPhysics(), controller: _pageController, children: _listOfWidget, ), ), ], ), ), /// Bottom Navigation Bar bottomNavigationBar: _colorful ? SlidingClippedNavBar.colorful( backgroundColor: Colors.white, onButtonPressed: onButtonPressed, iconSize: 30, selectedIndex: selectedIndex, barItems: <BarItem>[ BarItem( icon: Icons.home, title: 'Home', activeColor: Colors.amber, inactiveColor: Colors.red, ), BarItem( icon: Icons.search_rounded, title: 'Search', activeColor: Colors.red, inactiveColor: Colors.deepPurpleAccent, ), BarItem( icon: Icons.bolt_rounded, title: 'Energy', activeColor: Colors.deepPurpleAccent, inactiveColor: Colors.pinkAccent, ), BarItem( icon: Icons.tune_rounded, title: 'Settings', activeColor: Colors.pinkAccent, inactiveColor: Colors.amber, ), ], ) : SlidingClippedNavBar( backgroundColor: Colors.white, onButtonPressed: onButtonPressed, iconSize: 30, activeColor: const Color(0xFF01579B), selectedIndex: selectedIndex, barItems: <BarItem>[ BarItem( icon: Icons.home, title: 'Home', ), BarItem( icon: Icons.search_rounded, title: 'Search', ), BarItem( icon: Icons.bolt_rounded, title: 'Energy', ), BarItem( icon: Icons.tune_rounded, title: 'Settings', ), ], ), ); } } /// TextStyle fontstyle = GoogleFonts.oxygen( fontSize: 20, fontWeight: FontWeight.w400, color: Colors.white); double iconSize = 200; /// LIST OF SCREENS List<Widget> _listOfWidget = <Widget>[ /// EVENT Container( color: Colors.amber, alignment: Alignment.center, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon( Icons.home, size: iconSize, color: Colors.white, ), Text( "@CodeWithFlexz", style: fontstyle, ), ], ), ), /// SERACH Container( alignment: Alignment.center, color: Colors.red, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon( Icons.search, size: iconSize, color: Colors.white, ), Text("Search", style: fontstyle), ], ), ), /// ENERGY Container( color: Colors.deepPurpleAccent, alignment: Alignment.center, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon( Icons.bolt, size: iconSize, color: Colors.white, ), Text("Energy", style: fontstyle), ], ), ), /// SETTINGS Container( alignment: Alignment.center, color: Colors.pinkAccent, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon( Icons.tune_rounded, size: iconSize, color: Colors.white, ), Text("Settings", style: fontstyle), ], ), ), ];
0
mirrored_repositories/flutter_voice_recording_to_text
mirrored_repositories/flutter_voice_recording_to_text/lib/home_page_screen.dart
import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter_tts/flutter_tts.dart'; import 'package:speech_to_text/speech_recognition_error.dart'; import 'package:speech_to_text/speech_recognition_result.dart'; import 'package:speech_to_text/speech_to_text.dart'; enum TtsState { playing, stopped } /* Title:HomePageScreen Purpose:HomePageScreen Created By:Kalpesh Khandla */ class HomePageScreen extends StatefulWidget { HomePageScreen({Key key}) : super(key: key); @override _HomePageScreenState createState() => _HomePageScreenState(); } class _HomePageScreenState extends State<HomePageScreen> with SingleTickerProviderStateMixin, WidgetsBindingObserver { final SpeechToText speech = SpeechToText(); bool _hasSpeech = false; bool speechTest = false; bool _isAnimating = false; bool isMatchFound = false; String lastError = ""; String lastStatus = ""; String lastWords = ""; PersistentBottomSheetController _controller; AnimationController _animationController; GlobalKey<ScaffoldState> _key = GlobalKey(); dynamic languages; FlutterTts flutterTts; TtsState ttsState = TtsState.stopped; double volume = 0.5; double rate = 0.5; double pitch = 1.0; @override void initState() { // TODO: implement initState super.initState(); initSpeechState(); _animationController = AnimationController( vsync: this, lowerBound: 0.5, duration: Duration(seconds: 3), )..repeat(); initTts(); } initTts() { flutterTts = FlutterTts(); _getLanguages(); flutterTts.setStartHandler(() { setState(() { ttsState = TtsState.playing; }); }); flutterTts.setCompletionHandler(() { setState(() { ttsState = TtsState.stopped; }); }); flutterTts.setErrorHandler((msg) { setState(() { ttsState = TtsState.stopped; }); }); } Future _getLanguages() async { languages = await flutterTts.getLanguages; if (languages != null) setState(() => languages); } Future<void> initSpeechState() async { bool hasSpeech = await speech.initialize( onError: errorListener, onStatus: statusListener, debugLogging: false, ); if (!mounted) return; setState(() { _hasSpeech = hasSpeech; }); } void errorListener(SpeechRecognitionError error) { setState(() { lastError = "${error.errorMsg} - ${error.permanent}"; }); } void statusListener(String status) { if (status == "listening") { } else if (status == "notListening") { _animationController.reset(); _isAnimating = false; } } void resultListenerCheck(SpeechRecognitionResult result) { if (!speech.isListening) { resultListener(result); } } void resultListener(SpeechRecognitionResult result) { _animationController.reset(); _isAnimating = false; _controller.setState(() { //lastWords = "${result.recognizedWords} - ${result.finalResult}"; lastWords = "${result.recognizedWords}"; }); if (speech.isListening) { return; } else { lastWords != null && lastWords.length > 0 && !speech.isListening && !isMatchFound; ///lastWords="Sorry No Match Founds"; isMatchFound = true; // _speak("sorry we can not found any match! please try again"); } } @override Widget build(BuildContext context) { return Scaffold( key: _key, resizeToAvoidBottomInset: false, body: Padding( padding: const EdgeInsets.only( left: 15, right: 15, top: 30, ), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ GestureDetector( onTap: () { getBottomSheet(context); startListening(); }, child: Image.asset( 'assets/images/mike.png', height: 120, width: 200, ), ), Text( "Tap on Mike to Convert Your Speech to Text", textAlign: TextAlign.center, style: Theme.of(context).textTheme.caption.copyWith( fontSize: 18, color: Colors.black, fontWeight: FontWeight.w700, ), ) ], ), ), ); } void startListening() { _animationController.addListener(() { setState(() {}); }); //_animationController.forward(); _animationController.repeat(period: Duration(seconds: 2)); _isAnimating = true; lastWords = ""; lastError = ""; isMatchFound = false; int listenForSeconds = 10; if (Platform.isIOS) { listenForSeconds = 5; } Duration listenFor = Duration(seconds: listenForSeconds); speech.listen(onResult: resultListenerCheck, listenFor: listenFor); setState(() { speechTest = true; }); } Future _speak(String message) async { if (Platform.isIOS) { volume = 0.7; } else { volume = 0.5; } await flutterTts.setVolume(volume); await flutterTts.setSpeechRate(rate); await flutterTts.setPitch(pitch); if (message != null) { if (message.isNotEmpty) { var result = await flutterTts.speak(message); if (result == 1) setState(() => ttsState = TtsState.playing); } } } Future<void> getBottomSheet(BuildContext context) async { _controller = _key.currentState.showBottomSheet( (_) { return Align( alignment: Alignment.bottomCenter, child: Container( decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.all( Radius.circular( 20, ), ), shape: BoxShape.rectangle, border: Border.all( width: 5, color: Colors.grey, ), ), height: 250, width: 500, child: Column( children: <Widget>[ Container( padding: EdgeInsets.fromLTRB(20, 0, 0, 0), child: Row( children: <Widget>[ Expanded( child: Text( lastWords, style: Theme.of(context) .textTheme .title .copyWith(fontFamily: 'ManropSemiBold') .copyWith( color: Color(0xffE15B4F), ), ), ), IconButton( icon: Icon(Icons.close), onPressed: () { // Navigator.of(context).pop(); _controller.close(); }, ), ], ), ), _hasSpeech ? Expanded( child: AnimatedBuilder( animation: CurvedAnimation( parent: _animationController, curve: Curves.fastOutSlowIn), builder: (context, child) { return Stack( alignment: Alignment.center, children: <Widget>[ _buildContainer( 150 * _animationController.value), _buildContainer( 200 * _animationController.value), GestureDetector( onTap: () { _controller.setState(() { lastWords = ""; }); startListening(); }, child: Center( child: Image.asset( 'assets/images/mike.png', height: 120, width: 200, ), ), ), //Text(lastWords) ], ); }, ), ) : Container( height: 0, width: 0, ), ], ), ), ); }, ); } Widget _buildContainer(double radius) { radius = !speechTest || !_isAnimating ? 0 : radius; return Container( width: radius, height: radius, decoration: BoxDecoration( shape: BoxShape.circle, color: Color(0xffF7CCC9).withOpacity(1 - _animationController.value), ), ); } }
0
mirrored_repositories/flutter_voice_recording_to_text
mirrored_repositories/flutter_voice_recording_to_text/lib/main.dart
import 'package:flutter/material.dart'; import 'package:flutter_voice_recording_to_text_convert/home_page_screen.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: HomePageScreen(), ); } }
0
mirrored_repositories/flutter_voice_recording_to_text
mirrored_repositories/flutter_voice_recording_to_text/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_voice_recording_to_text_convert/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/expense_tracker
mirrored_repositories/expense_tracker/lib/transaction.dart
class Transaction { final int id; final String title; final double amount; final DateTime date; Transaction( {required this.id, required this.title, required this.amount, required this.date}); }
0
mirrored_repositories/expense_tracker
mirrored_repositories/expense_tracker/lib/main.dart
import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import './transaction.dart'; void main() { runApp(MyHomePage()); } class MyHomePage extends StatelessWidget { MyHomePage({super.key}); final List<Transaction> transactions = [ Transaction( id: 0001, title: 'Shoes', amount: 59.99, date: DateTime.now(), ), Transaction( id: 0002, title: 'Sunglasses', amount: 12.99, date: DateTime.now(), ) ]; @override Widget build(BuildContext context) { return MaterialApp( title: 'Welcome to Flutter', home: Scaffold( appBar: AppBar( title: Text('Welcome to Flutter'), ), body: Column( // mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ Card( color: Colors.blue, elevation: 5, child: SizedBox( child: Text('CHART!'), ), ), Card( child: Container( padding: EdgeInsets.all(10), child: Column( children: <Widget>[ TextField( decoration: InputDecoration(labelText: 'Title'), ), TextField( decoration: InputDecoration(labelText: 'Amount'), ), ElevatedButton( style: ElevatedButton.styleFrom( primary: Colors.blue, onPrimary: Colors.white, ), onPressed: () {}, child: Text('Add Transaction'), ) ], ), ), ), Column( children: transactions.map( (transaction) { return Card( child: Row( children: <Widget>[ Container( margin: EdgeInsets.symmetric( vertical: 15, horizontal: 20, ), decoration: BoxDecoration( border: Border.all( color: Colors.blue, width: 2, ), ), padding: EdgeInsets.all(10), child: Text( '\$ ${transaction.amount}', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 20, color: Colors.blue, ), ), //.toString converts it to a string ), Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Column( children: [ Text( transaction.title, style: TextStyle( fontWeight: FontWeight.bold, fontSize: 18, ), ), ], ), Text( DateFormat.yMMMd().format(transaction.date), style: TextStyle( color: Colors.grey, ), ), ], ), ], ), ); }, ).toList(), ) ], ), ), ); } }
0
mirrored_repositories/expense_tracker
mirrored_repositories/expense_tracker/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:expense_tracker/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(MyHomePage()); // 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/heramigo/docs/assets/assets
mirrored_repositories/heramigo/docs/assets/assets/data/list_cities.dart
final List<String> cities = [ "Lahore", "Multan", "Faisalabad", "Rawalpindi", "Islamabad", "Bhawalpur", "Rahim Yar Khan", "Sargodha", "Gujrat", "Sialkot", "Gujranwala", "Sahiwal", "Dera Ghazi Khan", "Lodhran", "Sheikhupura", "Wah", "Khariyan", "Taxila", "Narowal" "Karachi", "Larkana", "Jamshoroo", "Lyari", "Sukkur", "Gambat", "Hyderabad", "Mirpur Khas", "Tando Muhammad Khan" "Peshawar", "Abbottabad", "Dera Ismail Khan", "Swat", "Mardan", "Kohat", "Bannu", "Nowshera", "Swabi", "Quetta", "Kharian", ];
0
mirrored_repositories/heramigo/docs/assets/assets
mirrored_repositories/heramigo/docs/assets/assets/data/list_institutes.dart
final List<String> insititute = [ "King Edward Medical University", "Allama Iqbal Medical College", "Services Institute of Medical Sciences", "Fatima Jinnah Medical University", "Sheikh Khalifa Bin Zayed Al Nahyan Medical College", "Ameer Ud Din Medical College", "Nishter Medical Univerity", "Punjab Medical University", "Rawalpindi Medical Univerity", "Army Medical College", "Federal Medical And Dental College", "Quaid e Azam Medical College", "Sheikh Zayed Medical College", "Sargodha Medical College", "Nawaz Shareef Medical College", "Khawaja Muhammad Safdar Medical College", "Gujranwala Medical College", "Sahiwal Medical College", "D.G Khan medical college", "FMH College of Medicine and Dentistry", "Shalimar Medical College LMDC", "Lahore Medical And Dental College", "CMH Lahore Medical College", "Rahbar Medical College", "Al-Aleem Medical College", "Akhtar Saeed Medical And Dental College", "Avicenna Medical College", "Azra Naheed Medical College", "Amna Inayat Medical College", "University College of Medicine & Dentistry", "Gulab Devi Medical College", "Central Park Medical College", "Continental Medical College", "Pak Red Cresent Medical And Dental college", "Multan Medical and dental college", "Bakhtawar Amin Medical College", "Independent Medical College", "CMH Bhawalpur Medical College", "Combined Institute of Medical Sciences", "Shahida Islam Medical College", "slam Medical College", "Wah Medical College, Wah", "Shifa College of Medicine", "Yusra Medical And Dental College", "University Medical And Dental College", "Islamic International Medical College", "Al Nafees Medical College", "Fazaia Medical College", "Rawal Institute of Health Sciences", "Rai Medical College", "Niazi Medical College", "HBS Medical And Dental College", "Islamabad Medical And Dental College", "CMH Kharian Medical College", "Abwa Medical College, Faisalabad", "Aziz Fatima Medical And Dental College", "Sahara Medical College", "HITEC Institute of Medical Sciences", "M.Islam Medical College", "Dow Medical University", "Jinnah Sindh Medical University", "Karachi Medical & Dental College", "Chandka Medical College", "Liaquat University of Medical and Health Sciences (LUMHS) ", "Peoples University Medical & Health Sciences", "Dow International Medical College", "Shaheed Benazir Bhutto Medical College", "Ghulam Muhammad Mehar Medical college", "Bilawal Medical College", "Gambat Medical College", "The Agha Khan Medical University Medical College", "Baqai Medical College", "Isra University Medical College, Hyderabad", "Hamdard Medical College & Dentistry", "Jinnah Medical and Dental College", "United Medical and Dental College", "Sir Syed Medical College for Girls", "Zia ud Din Medical College", "Liaquat National Medical College", "Liaquat College of Medicine and Dentistry", "Al Tibri Medical College", "Muhammad Medical College", "Bahria Medical and Dental College", "Indus Medical Colleges", "Karachi Institute of Medical Sciences" "Khyber Medical University", "Khyber Girls Medical College", "Ayub Medical College", "Saidu Medical College", "Gomal Medical College", "KUST Institute of Medical Sciences", "Bacha Khan Medical College", "Banu Medical College", "Nowshera Medical College", "Gajju Khan Medical College", "Peshawar Medical College", "Pak International Medical College", "Kabir Medical College", "Jinnah Medical College", "Rehman Medical College", "Al Razi Medical College", "North West Medical School", "Frontier Medical College", "Abbottabad International Medical College", "Women Medical College" "Bolan Medical University", "Quetta Institute of Medical Sciences" ];
0
mirrored_repositories/heramigo/docs/assets/assets
mirrored_repositories/heramigo/docs/assets/assets/data/list_provinces.dart
final List<String> province = [ "Punjab", "Sindh", "Khyber Pakhtunkhwa", "Balochistan", "Gilgit Baltistan" ];
0
mirrored_repositories/yanews_app
mirrored_repositories/yanews_app/lib/main_app.dart
import 'package:flutter/material.dart'; import 'pages/main_page.dart'; class MainApp extends StatefulWidget { MainApp({Key key}) : super(key: key); @override _MainAppState createState() => _MainAppState(); } class _MainAppState extends State<MainApp> { @override Widget build(BuildContext context) { return MaterialApp( title: 'Yet Another News App', debugShowCheckedModeBanner: false, theme: ThemeData( primarySwatch: Colors.blueGrey, visualDensity: VisualDensity.adaptivePlatformDensity, ), home: MainPage(title: 'Yet Another News App'), ); } // TODO: introduce Auth and AuthBloc, implement MainApp and related pages }
0
mirrored_repositories/yanews_app
mirrored_repositories/yanews_app/lib/main.dart
import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_crashlytics/firebase_crashlytics.dart'; import 'package:firebase_remote_config/firebase_remote_config.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:hive/hive.dart'; import 'package:hive_flutter/hive_flutter.dart'; import 'blocs/app_navigator/app_navigator_bloc.dart'; import 'blocs/simple_bloc_observer.dart'; import 'main_app.dart'; import 'models/main_repository.dart'; import 'shared/common_utils.dart'; Future<void> main() async { WidgetsFlutterBinding.ensureInitialized(); Bloc.observer = SimpleBlocObserver(); await Firebase.initializeApp(); await Hive.initFlutter(); Box _hiveBox = await Hive.openBox("appBox"); // we get APIKEY and similar details from remoteconfig, safe and and reliable final RemoteConfig _remoteConfig = await RemoteConfig.instance; await _remoteConfig.fetch(expiration: const Duration(hours: 12)); await _remoteConfig.activateFetched(); // Enable developer mode to relax fetch throttling //_remoteConfig.setConfigSettings(RemoteConfigSettings(debugMode: !isPhysicalDevice)); // optional: set defaults as backup option Map<String, dynamic> remoteConfigDefaults = await CommonUtils.parseJsonFromAssets('assets/config/remoteconfig_defaults.json'); _remoteConfig.setDefaults(remoteConfigDefaults); final MainRepository _mainRepository = MainRepository(hiveBox: _hiveBox, remoteConfig: _remoteConfig); final String devicePlatform = await CommonUtils.getDevicePlatform(); final bool isPhysicalDevice = await CommonUtils.isPhysicalDevice(devicePlatform: devicePlatform); _mainRepository.hiveStore.save("DEVICEPLATFORM", devicePlatform); _mainRepository.hiveStore.save("IS_PHYSICAL_DEVICE", isPhysicalDevice); FirebaseCrashlytics.instance.setCrashlyticsCollectionEnabled(isPhysicalDevice); // Pass all uncaught errors to Crashlytics. FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterError; FlutterError.onError = (FlutterErrorDetails errorDetails) { // dumps errors to console FlutterError.dumpErrorToConsole(errorDetails); }; runApp(MultiBlocProvider(providers: [ BlocProvider<AppNavigatorBloc>( lazy: false, create: (context) => AppNavigatorBloc(mainRepository: _mainRepository)), ], child: MainApp())); }
0
mirrored_repositories/yanews_app/lib
mirrored_repositories/yanews_app/lib/shared/screen_size_config.dart
import 'package:flutter/widgets.dart'; class ScreenSizeConfig { MediaQueryData _mediaQueryData; double screenWidth; double screenHeight; double shortestSide; double blockSizeHorizontal; double blockSizeVertical; double _safeAreaHorizontal; double _safeAreaVertical; double safeBlockHorizontal; double safeBlockVertical; bool isInit() { return _mediaQueryData != null; } bool isNotInit() { return !isInit(); } void init(BuildContext context) { if (_mediaQueryData != null) { // ensure init is done only once return; } _mediaQueryData = MediaQuery.of(context); screenWidth = _mediaQueryData.size.width; screenHeight = _mediaQueryData.size.height; shortestSide = _mediaQueryData.size.shortestSide; blockSizeHorizontal = screenWidth / 100; blockSizeVertical = screenHeight / 100; _safeAreaHorizontal = _mediaQueryData.padding.left + _mediaQueryData.padding.right; _safeAreaVertical = _mediaQueryData.padding.top + _mediaQueryData.padding.bottom; safeBlockHorizontal = (screenWidth - _safeAreaHorizontal) / 100; safeBlockVertical = (screenHeight - _safeAreaVertical) / 100; } bool isMobile() { return shortestSide != null && shortestSide < 600; } Map<String, dynamic> toMap() { return { '_mediaQueryData': this._mediaQueryData, 'screenWidth': this.screenWidth, 'screenHeight': this.screenHeight, 'shortestSize': this.shortestSide, 'blockSizeHorizontal': this.blockSizeHorizontal, 'blockSizeVertical': this.blockSizeVertical, '_safeAreaHorizontal': this._safeAreaHorizontal, '_safeAreaVertical': this._safeAreaVertical, 'safeBlockHorizontal': this.safeBlockHorizontal, 'safeBlockVertical': this.safeBlockVertical, }; } }
0
mirrored_repositories/yanews_app/lib
mirrored_repositories/yanews_app/lib/shared/common_utils.dart
import 'dart:convert'; import 'package:device_info/device_info.dart'; import 'package:flutter/services.dart'; import 'package:intl/intl.dart'; import 'package:jiffy/jiffy.dart'; import 'package:logger/logger.dart'; import 'package:url_launcher/url_launcher.dart'; import 'package:uuid/uuid.dart'; class CommonUtils { // FIXME: isDebug is a manual switch, but it must come from isPhysicalDevice static final isDebug = true; static final Logger logger = Logger( level: isDebug ? Level.debug : Level.warning, printer: PrettyPrinter( methodCount: 2, // number of method calls to be displayed errorMethodCount: 8, // number of method calls if stacktrace is provided lineLength: 120, // width of the output colors: true, // Colorful log messages printEmojis: false, // Print an emoji for each log message printTime: true // Should each log print contain a timestamp ), ); static String nullSafe(String source) { return (source == null || source.isEmpty || source == "null") ? "" : source; } static String nullSafeSnap(dynamic source) { return source != null ? nullSafe(source as String) : ""; } static String generateUuid() { var uuid = Uuid(); return uuid.v5(Uuid.NAMESPACE_URL, 'beerstorm.net'); } static String getFormattedDate({DateTime date}) { return DateFormat("yyyy-MM-dd HH:mm:ss").format(date ?? DateTime.now()); } static humanizeDateText(String dateAt) { Jiffy jiffy = Jiffy(dateAt); if (jiffy.diff(DateTime.now(), Units.DAY) > -7) { return jiffy.fromNow(); } else { return jiffy.format("EEEE, dd MMMM yyyy"); // man, 22 mar 2020 } } static launchURL(url) async { if (await canLaunch(url)) { await launch( url, forceSafariVC: true, forceWebView: true, enableJavaScript: true, enableDomStorage: true, //headers: <String, String>{'source': 'beerstorm.net'} ); } else { throw 'Could not launch $url'; } } static Future<Map<String, dynamic>> parseJsonFromAssets(String filePath) async { return rootBundle.loadString(filePath).then((jsonStr) => jsonDecode(jsonStr)); } static String appendParamToUrl(String reqUrl, String paramKey, String paramVal) { if (nullSafe(paramKey).isNotEmpty && nullSafe(paramVal).isNotEmpty) { reqUrl += (reqUrl.contains("?") ? "&" : "?") + paramKey.trim() + "=" + paramVal.trim(); } return reqUrl; } static final DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin(); static Future<bool> isPhysicalDevice({String devicePlatform}) async { if (nullSafe(devicePlatform).isEmpty) { devicePlatform = await getDevicePlatform(); } if (devicePlatform?.toLowerCase() == "ios") { IosDeviceInfo iosDeviceInfo = await deviceInfoPlugin.iosInfo; return iosDeviceInfo.isPhysicalDevice; } else { AndroidDeviceInfo androidDeviceInfo = await deviceInfoPlugin.androidInfo; return androidDeviceInfo.isPhysicalDevice; } } static Future<String> getDevicePlatform() async { try { IosDeviceInfo iosDeviceInfo = await deviceInfoPlugin.iosInfo; if (iosDeviceInfo != null) { CommonUtils.logger.d('iOS device!'); return "ios"; } } catch (_) { CommonUtils.logger.d('ANDROID device!'); return "android"; } return "android"; // default } }
0
mirrored_repositories/yanews_app/lib
mirrored_repositories/yanews_app/lib/shared/hive_store.dart
import 'dart:convert'; import 'package:hive/hive.dart'; class HiveStore { String _boxName; Box _hiveBox; //static initHiveBox(boxName) => await Hive.openBox(boxName); HiveStore({boxName = "appBox", Box hiveBox}) : _boxName = boxName, _hiveBox = hiveBox; //initHiveBox(boxName); String get boxName => _boxName; Box get hiveBox => _hiveBox; read(String key) { if (!contains(key)) { return null; } String value = _hiveBox.get(key) as String; if (value.contains("{")) { return json.decode(value); } else { return value; } } save(String key, dynamic value) { if (value is String && !value.contains("{")) { _hiveBox.put(key, value); } else { _hiveBox.put(key, json.encode(value)); } } contains(String key) { return _hiveBox.containsKey(key); } remove(String key) { _hiveBox.delete(key); } clear() { _hiveBox.clear(); } // --- reusable methods for ease of access --- bool isIOSPlatform() { return _hiveBox.get("DEVICEPLATFORM") == "ios"; } bool isAndroidPlatform() { return _hiveBox.get("DEVICEPLATFORM") == "android"; } /* // for later use, together with Auth flow AppUser readAppUser() { String dataStr = _hiveBox.get("APP_USER"); return CommonUtils.nullSafe(dataStr).isNotEmpty ? AppUser.fromJson(json.decode(dataStr)) : null; }*/ }
0
mirrored_repositories/yanews_app/lib
mirrored_repositories/yanews_app/lib/shared/app_defaults.dart
// used for AppNavigatorBloc import 'package:flutter/material.dart'; class AppNavigatorPage { String id; Widget icon; Widget activeIcon; String label; Widget widgetContainer; // container to display AppNavigatorPage( {this.id, this.icon, this.label, this.activeIcon, this.widgetContainer}); } final List<AppNavigatorPage> appNavigatorPages = List() ..add(AppNavigatorPage( id: "HOME", icon: Icon( Icons.home, size: 28, ), label: "HOME", )) ..add(AppNavigatorPage( id: "TRADING", icon: Icon( Icons.monetization_on, size: 28, ), label: "TRADING", )); // to be used for AuthBloc enum ORIGIN { LOGIN, LOGOUT, RELOAD, REFRESH_TOKEN, }
0
mirrored_repositories/yanews_app/lib
mirrored_repositories/yanews_app/lib/widgets/common_dialogs.dart
import 'package:awesome_dialog/awesome_dialog.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_spinkit/flutter_spinkit.dart'; import 'package:progress_dialog/progress_dialog.dart'; import '../shared/common_utils.dart'; theSnackBar(context, String message) { return SnackBar( duration: Duration(seconds: 2), content: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, //crossAxisAlignment: CrossAxisAlignment.end, children: [ SizedBox( width: 260.0, child: Text( //AppLocalizations.of(context).translate('soon') + ' ' + message, message, overflow: TextOverflow.fade, softWrap: false, ), ), Icon(Icons.error), ], ), backgroundColor: Colors.orangeAccent, ); } // show alert as a dialog AwesomeDialog _awesomeDialog; showAlertDialog(context, String message, {String type = "INFO", Duration autoHide = const Duration(seconds: 2)}) { DialogType dialogType = DialogType.INFO; Color textColor = Colors.blueGrey; if (type.toUpperCase() == "SUCCESS") { dialogType = DialogType.SUCCES; textColor = Colors.green; } else if (type.toUpperCase() == "WARNING") { dialogType = DialogType.WARNING; textColor = Colors.deepOrange; } else if (type.toUpperCase() == "ERROR") { dialogType = DialogType.ERROR; textColor = Colors.red; } _awesomeDialog = AwesomeDialog( context: context, animType: AnimType.LEFTSLIDE, dismissOnTouchOutside: true, dismissOnBackKeyPress: true, headerAnimationLoop: true, dialogType: dialogType, btnOk: null, btnCancel: null, autoHide: autoHide, body: Container( padding: EdgeInsets.all(4.0), alignment: Alignment.center, child: Center( child: Text( message, textAlign: TextAlign.center, style: TextStyle( fontSize: 20, fontWeight: FontWeight.bold, color: textColor, ), overflow: TextOverflow.fade, maxLines: 12, softWrap: true, ), ), ), ); _awesomeDialog.show(); } buildProgressDialog(context, String message, {bool isDismissible = false, bool showLogs, Duration autoHide}) { ProgressDialog _progressDialog = ProgressDialog( context, type: ProgressDialogType.Normal, isDismissible: isDismissible, autoHide: autoHide ?? Duration(seconds: 2), showLogs: showLogs ?? CommonUtils.isDebug, ); _progressDialog.style( message: message.isNotEmpty ? message : '...', messageTextStyle: TextStyle( color: Colors.blueGrey, fontSize: 20.0, fontWeight: FontWeight.w600), progressWidget: SpinKitPouringHourglass( color: Colors.blueGrey, //size: 44, ), progressWidgetAlignment: Alignment.topLeft, dialogAlignment: Alignment.topCenter, //padding: EdgeInsets.only(top: 8.0), ); return _progressDialog; } class LoadingIndicator extends StatelessWidget { @override Widget build(BuildContext context) { return Center( child: CircularProgressIndicator( strokeWidth: 8.0, ), ); } }
0
mirrored_repositories/yanews_app/lib
mirrored_repositories/yanews_app/lib/blocs/simple_bloc_observer.dart
import 'package:bloc/bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import '../shared/common_utils.dart'; class SimpleBlocObserver extends BlocObserver { @override void onEvent(Bloc bloc, Object event) { CommonUtils.logger.d('onEvent: $event'); super.onEvent(bloc, event); } @override void onTransition(Bloc bloc, Transition transition) { CommonUtils.logger.d('onTransition: $transition'); super.onTransition(bloc, transition); } @override void onError(Cubit cubit, Object error, StackTrace stacktrace) { CommonUtils.logger.d('onError: $error, $stacktrace'); super.onError(cubit, error, stacktrace); } @override void onChange(Cubit cubit, Change change) { CommonUtils.logger.d('onChange: $cubit, $change'); super.onChange(cubit, change); } }
0
mirrored_repositories/yanews_app/lib/blocs
mirrored_repositories/yanews_app/lib/blocs/app_navigator/app_navigator_state.dart
part of 'app_navigator_bloc.dart'; abstract class AppNavigatorState extends Equatable { const AppNavigatorState(); @override List<Object> get props => []; } class InitialAppNavigatorState extends AppNavigatorState {} class AppPageState extends AppNavigatorState { final AppNavigatorPage tab; const AppPageState({this.tab}); @override List<Object> get props => [tab]; @override String toString() => 'AppPageState {tab: $tab}'; } class WarnUserState extends AppNavigatorState { final List<String> actions; final String message; final Duration duration; const WarnUserState(this.actions, {this.message, this.duration = const Duration(seconds: 2)}); @override List<Object> get props => [actions, message, duration]; @override String toString() => 'WarnUserState { actions: $actions, message: $message, duration: $duration }'; } class ItemsLoaded extends AppNavigatorState { final List<NewsItem> items; const ItemsLoaded({this.items}); @override List<Object> get props => [items]; @override String toString() => 'ItemsLoaded {items: $items}'; }
0
mirrored_repositories/yanews_app/lib/blocs
mirrored_repositories/yanews_app/lib/blocs/app_navigator/app_navigator_bloc.dart
import 'dart:async'; import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:meta/meta.dart'; import 'package:yanews_app/models/news_item.dart'; import '../../models/main_repository.dart'; import '../../models/news_item.dart'; import '../../shared/app_defaults.dart'; import '../../shared/common_utils.dart'; part 'app_navigator_event.dart'; part 'app_navigator_state.dart'; class AppNavigatorBloc extends Bloc<AppNavigatorEvent, AppNavigatorState> { MainRepository _mainRepository; AppNavigatorBloc({@required MainRepository mainRepository}) : assert(mainRepository != null), _mainRepository = mainRepository, super(InitialAppNavigatorState()); @override Stream<AppNavigatorState> mapEventToState(AppNavigatorEvent event) async* { if (event is AppPageEvent) { yield AppPageState(tab: event.tab); } else if (event is AnonymousSigninEvent) { yield* _signInAnonymously(event); } else if (event is WarnUserEvent) { // NB! implement this further if necessary yield WarnUserState(event.actions, message: event.message, duration: event.duration); } else if (event is LoadItemsEvent) { yield* _loadItems(event); } } Stream<ItemsLoaded> _loadItems(LoadItemsEvent event) async* { List<NewsItem> items = await _mainRepository.apiGetNews(event.reqParams); yield ItemsLoaded(items: items); } Stream<AppNavigatorState> _signInAnonymously(AnonymousSigninEvent event) async* { String userId = _mainRepository.hiveStore.read("USERID"); if (CommonUtils.nullSafe(userId).isEmpty || FirebaseAuth.instance.currentUser == null) { UserCredential userCredential = await FirebaseAuth.instance.signInAnonymously(); CommonUtils.logger.d("userCredential: $userCredential"); /* userCredential: UserCredential(additionalUserInfo: AdditionalUserInfo( isNewUser: true, profile: {}, providerId: null, username: null), credential: null, user: User(displayName: null, email: null, emailVerified: false, isAnonymous: true, metadata: UserMetadata(creationTime: 2020-11-17 21:58:34.418, lastSignInTime: 2020-11-17 21:58:34.418), phoneNumber: null, photoURL: null, providerData, [], refreshToken: , tenantId: null, uid: RsLrKJkEcyPY9Dpr8nAIjHynTLD2) ) */ userId = userCredential.user.uid; _mainRepository.hiveStore.save("USERID", userId); } /* // nb! this can be used later on add(WarnUserEvent(List<String>()..add("alert_message")..add("WARN"), message: "Welcome anonymous! $userId", duration: Duration(seconds: 3))); */ } }
0
mirrored_repositories/yanews_app/lib/blocs
mirrored_repositories/yanews_app/lib/blocs/app_navigator/app_navigator_event.dart
part of 'app_navigator_bloc.dart'; abstract class AppNavigatorEvent extends Equatable { const AppNavigatorEvent(); @override List<Object> get props => []; } class AnonymousSigninEvent extends AppNavigatorEvent {} class LoadItemsEvent extends AppNavigatorEvent { final Map<String, String> reqParams; const LoadItemsEvent({this.reqParams}); @override List<Object> get props => [reqParams]; @override String toString() => 'LoadItemsEvent {reqParams: $reqParams}'; } class AppPageEvent extends AppNavigatorEvent { final AppNavigatorPage tab; const AppPageEvent({this.tab}); @override List<Object> get props => [tab]; @override String toString() => 'AppPageEvent {tab: $tab}'; } class WarnUserEvent extends AppNavigatorEvent { final List<String> actions; final String message; final Duration duration; const WarnUserEvent(this.actions, {this.message, this.duration = const Duration(seconds: 2)}); @override List<Object> get props => [actions, message, duration]; @override String toString() => 'WarnUserEvent { actions: $actions, message: $message, duration: $duration }'; }
0
mirrored_repositories/yanews_app/lib
mirrored_repositories/yanews_app/lib/pages/home_page.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:pull_to_refresh/pull_to_refresh.dart'; import '../blocs/app_navigator/app_navigator_bloc.dart'; import '../models/main_repository.dart'; import '../models/news_item.dart'; import '../shared/common_utils.dart'; import '../shared/screen_size_config.dart'; class HomePage extends StatefulWidget { HomePage({Key key}) : super(key: key); @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { ScreenSizeConfig screenSizeConfig = ScreenSizeConfig(); MainRepository _mainRepository; List<NewsItem> _items = List(); String pageSizeDefault = "20"; String countryDefault = "no"; // set default params, and update per request! Map<String, String> _reqParams = Map() ..putIfAbsent("isHeadlines", () => "true") ..putIfAbsent("page", () => "0") ..putIfAbsent("pageSize", () => "20") ..putIfAbsent("country", () => "no") ..putIfAbsent("q", () => null); @override void initState() { super.initState(); } RefreshController _refreshController = RefreshController(initialRefresh: true); @override Widget build(BuildContext buildContext) { screenSizeConfig.init(buildContext); if (_mainRepository == null) { _mainRepository = RepositoryProvider.of<MainRepository>(context); CommonUtils.logger.d("repository isReady: ${_mainRepository != null}"); } return BlocListener<AppNavigatorBloc, AppNavigatorState>( listener: (context, state) { BlocProvider.of<AppNavigatorBloc>(context) .add(WarnUserEvent(List<String>()..add("progress_stop"))); if (state is ItemsLoaded) { setState(() { //_coins = state.coins; _items.addAll(state.items); _refreshController.refreshCompleted(); }); } }, child: Container( child: SmartRefresher( controller: _refreshController, enablePullDown: true, enablePullUp: true, header: WaterDropMaterialHeader(), onRefresh: () { BlocProvider.of<AppNavigatorBloc>(context).add( WarnUserEvent(List<String>()..add("progress_start"), message: "in progress..")); BlocProvider.of<AppNavigatorBloc>(context).add(LoadItemsEvent(reqParams: _reqParams)); }, onLoading: () { // infinite loading String page = _reqParams['page']; if (CommonUtils.nullSafe(page).isEmpty) { page = "0"; } String pageSize = _reqParams['pageSize']; if (CommonUtils.nullSafe(pageSize).isEmpty) { pageSize = pageSizeDefault; } if (_items.isNotEmpty && (_items.length == int.parse(pageSize))) { page = (int.parse(page) + int.parse(pageSize)).toString(); _reqParams['page'] = page; BlocProvider.of<AppNavigatorBloc>(context) .add(LoadItemsEvent(reqParams: _reqParams)); } }, child: ListView.builder( itemCount: _items.length, physics: ClampingScrollPhysics(), itemBuilder: (context, index) { final NewsItem _item = _items[index]; return _itemCard(_item); }, ), ), )); } _itemCard(NewsItem item) { return Card( elevation: 4.0, shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4.0))), margin: EdgeInsets.all(4.0), child: Container( height: screenSizeConfig.safeBlockVertical * 24, child: Column( children: [ ListTile( contentPadding: EdgeInsets.all(8.0), onTap: () => CommonUtils.launchURL(item.url), //isThreeLine: true, leading: _networkImage(item.urlToImage), title: Container( alignment: Alignment.center, child: Text( "${item.title}", maxLines: 2, softWrap: true, overflow: TextOverflow.clip, style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, ), ), ), subtitle: Text( "${item.description}", maxLines: 2, softWrap: true, overflow: TextOverflow.clip, style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, ), ), ), Container( //padding: EdgeInsets.only(bottom: 2), //alignment: Alignment.topCenter, child: Column( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Text("${CommonUtils.humanizeDateText(item.publishedAt)}", style: TextStyle(fontSize: 14, fontStyle: FontStyle.italic)), Text( "${item.author}", maxLines: 2, softWrap: true, overflow: TextOverflow.clip, style: TextStyle(fontSize: 12), ), Text( "${item.source?.name}", maxLines: 2, softWrap: true, overflow: TextOverflow.clip, style: TextStyle(fontSize: 12), ), ], ), ) ], ))); } _networkImage(String imageUrl) => CachedNetworkImage( imageUrl: imageUrl, placeholder: (context, url) => CircularProgressIndicator(), errorWidget: (context, url, error) => Icon(Icons.error), width: screenSizeConfig.safeBlockHorizontal * 22, height: screenSizeConfig.safeBlockVertical * 22, fit: BoxFit.fill, ); }
0
mirrored_repositories/yanews_app/lib
mirrored_repositories/yanews_app/lib/pages/main_page.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:progress_dialog/progress_dialog.dart'; import '../blocs/app_navigator/app_navigator_bloc.dart'; import '../models/main_repository.dart'; import '../pages/home_page.dart'; import '../shared/app_defaults.dart'; import '../widgets/common_dialogs.dart'; class MainPage extends StatefulWidget { MainPage({Key key, this.title = "MainPage"}) : super(key: key); final String title; @override _MainPageState createState() => _MainPageState(); } class _MainPageState extends State<MainPage> { AppNavigatorPage _currentPage; ProgressDialog _progressDialog; @override void initState() { _currentPage = appNavigatorPages.reversed.first; BlocProvider.of<AppNavigatorBloc>(context).add(AnonymousSigninEvent()); /*BlocProvider.of<AppNavigatorBloc>(context).add(WarnUserEvent( List<String>()..add("progress_start"), message: "in progress.."));*/ super.initState(); } @override void dispose() { super.dispose(); } @override Widget build(BuildContext buildContext) { if (_progressDialog == null) { _progressDialog = buildProgressDialog(buildContext, '...in progress...', isDismissible: true, autoHide: Duration(seconds: 3)); } return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: MultiBlocListener( listeners: [ BlocListener<AppNavigatorBloc, AppNavigatorState>( listener: (context, state) { if (state is AppPageState) { setState(() { _currentPage = state.tab; }); } else if (state is WarnUserState) { // progress dialog if (state.actions.contains("progress_start")) { _progressDialog.show(); } else if (state.actions.contains("progress_stop")) { _progressDialog.hide(); } else if (state.actions.contains("alert_message")) { String _alertType = "WARNING"; // default if (state.actions.contains("SUCCESS")) { _alertType = "SUCCESS"; } else if (state.actions.contains("INFO")) { _alertType = "INFO"; } else if (state.actions.contains("ERROR")) { _alertType = "ERROR"; } showAlertDialog(buildContext, state.message, type: _alertType, autoHide: state.duration); } } }, ), ], child: Center( child: _pageContainer(), ), ), ); } Widget _pageContainer() { // TODO: revisit and simplify browsing logic, avoid recreating components!!! /*Widget _widget; if (_currentPage.id == "TRADING") { _widget = TradingPage(); } else { _widget = HomePage(); }*/ Widget _widget = HomePage(); return RepositoryProvider( create: (context) => MainRepository(), child: _widget, ); } }
0
mirrored_repositories/yanews_app/lib
mirrored_repositories/yanews_app/lib/models/main_repository.dart
import 'dart:convert'; import 'package:firebase_remote_config/firebase_remote_config.dart'; import 'package:hive/hive.dart'; import 'package:http/http.dart' as http; import 'package:yanews_app/models/news_item.dart'; import '../shared/common_utils.dart'; import '../shared/hive_store.dart'; class MainRepository { final HiveStore _hiveStore; final RemoteConfig _remoteConfig; RemoteConfig get remoteConfig => _remoteConfig; HiveStore get hiveStore => _hiveStore; static initHiveStore(hiveBox) => HiveStore(hiveBox: hiveBox); MainRepository({Box hiveBox, RemoteConfig remoteConfig}) : _hiveStore = initHiveStore(hiveBox), _remoteConfig = remoteConfig; /// https://newsapi.org/docs/endpoints/everything /// https://newsapi.org/docs/endpoints/top-headlines Future<List<NewsItem>> apiGetNews(Map<String, String> reqParams) async { List<NewsItem> newsItems = List(); Map<String, String> reqHeaders = Map() ..putIfAbsent("X-Api-Key", () => _remoteConfig.getString("newsapi_key")); String reqUrl = _remoteConfig.getString("newsapi_url"); reqUrl += (reqParams.containsKey("isHeadlines") ? _remoteConfig.getString("newsapi_headlines") : _remoteConfig.getString("newsapi_all")); reqUrl = CommonUtils.appendParamToUrl(reqUrl, "page", reqParams['page']); reqUrl = CommonUtils.appendParamToUrl(reqUrl, "pageSize", reqParams['pageSize']); reqUrl = CommonUtils.appendParamToUrl(reqUrl, "country", reqParams['country']); reqUrl = CommonUtils.appendParamToUrl(reqUrl, "q", reqParams['q']); try { final response = await http.get(reqUrl, headers: reqHeaders); if (response.statusCode <= 201) { Map<String, dynamic> responseMap = json.decode(response.body); if (responseMap.containsKey("articles")) { List<dynamic> dataItems = responseMap["articles"] as List; dataItems.forEach((dataItem) { newsItems.add(NewsItem.fromJson(dataItem)); }); } } } catch (ex) { CommonUtils.logger.e(ex); } return newsItems; } }
0
mirrored_repositories/yanews_app/lib
mirrored_repositories/yanews_app/lib/models/news_item.dart
/// { // "source": { // "id": null, // "name": "CoinDesk" // }, // "author": "Tanzeel Akhtar", // "title": "Crypto Exchange Bittrex Lists Tokenized Apple, Amazon, Tesla Stocks for Trading", // "description": "Bittrex will list tokenized stocks such as Apple, Tesla and Amazon on its digital asset exchange.", // "url": "https://www.coindesk.com/index.php?p=551484", // "urlToImage": "https://static.coindesk.com/wp-content/uploads/2018/08/shutterstock_1015316194-1200x628.jpg", // "publishedAt": "2020-12-07T15:00:04Z", // "content": "Bittrex Global has launched trading in tokenized stocks such as Apple, Tesla and Amazon on its digital asset exchange.\r\n&lt;ul&gt;&lt;li&gt;The platform said traders and investors will have direct access to list… [+1663 chars]" // } class NewsItem { NewsSource _source; String _author; String _title; String _description; String _url; String _urlToImage; String _publishedAt; String _content; NewsSource get source => _source; String get author => _author; String get title => _title; String get description => _description; String get url => _url; String get urlToImage => _urlToImage; String get publishedAt => _publishedAt; String get content => _content; NewsItem( {NewsSource source, String author, String title, String description, String url, String urlToImage, String publishedAt, String content}) { _source = source; _author = author; _title = title; _description = description; _url = url; _urlToImage = urlToImage; _publishedAt = publishedAt; _content = content; } NewsItem.fromJson(dynamic json) { _source = json["source"] != null ? NewsSource.fromJson(json["source"]) : null; _author = json["author"]; _title = json["title"]; _description = json["description"]; _url = json["url"]; _urlToImage = json["urlToImage"]; _publishedAt = json["publishedAt"]; _content = json["content"]; } Map<String, dynamic> toJson() { var map = <String, dynamic>{}; if (_source != null) { map["source"] = _source.toJson(); } map["author"] = _author; map["title"] = _title; map["description"] = _description; map["url"] = _url; map["urlToImage"] = _urlToImage; map["publishedAt"] = _publishedAt; map["content"] = _content; return map; } } class NewsSource { dynamic _id; String _name; dynamic get id => _id; String get name => _name; NewsSource({dynamic id, String name}) { _id = id; _name = name; } NewsSource.fromJson(dynamic json) { _id = json["id"]; _name = json["name"]; } Map<String, dynamic> toJson() { var map = <String, dynamic>{}; map["id"] = _id; map["name"] = _name; return map; } }
0
mirrored_repositories/Expenses-Tracker
mirrored_repositories/Expenses-Tracker/lib/main.dart
import 'package:flutter/material.dart'; import 'package:expense_tracker/widgets/expenses.dart'; import 'package:flutter/services.dart'; var kColorScheme = ColorScheme.fromSeed(seedColor: const Color.fromRGBO(87, 8, 8, 1)); var kDarkColorScheme = ColorScheme.fromSeed( brightness: Brightness.dark, seedColor: const Color.fromARGB(255, 36, 208, 224), ); void main() { // Responsivenss // WidgetsFlutterBinding.ensureInitialized(); // SystemChrome.setPreferredOrientations([ // DeviceOrientation.portraitUp, // ]).then((fn) { // happens after locking in // move run app here runApp( MaterialApp( darkTheme: ThemeData.dark().copyWith( useMaterial3: true, colorScheme: kDarkColorScheme, cardTheme: const CardTheme().copyWith( color: kDarkColorScheme.secondaryContainer, margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), ), elevatedButtonTheme: ElevatedButtonThemeData( style: ElevatedButton.styleFrom( backgroundColor: kDarkColorScheme.primaryContainer, foregroundColor: kDarkColorScheme.onPrimaryContainer, ), ), ), theme: ThemeData().copyWith( useMaterial3: true, colorScheme: kColorScheme, appBarTheme: AppBarTheme().copyWith( backgroundColor: kColorScheme.onPrimaryContainer, foregroundColor: kColorScheme.primaryContainer, ), cardTheme: const CardTheme().copyWith( color: kColorScheme.secondaryContainer, margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), ), elevatedButtonTheme: ElevatedButtonThemeData( style: ElevatedButton.styleFrom( backgroundColor: kColorScheme.primaryContainer, ), ), textTheme: ThemeData().textTheme.copyWith( titleLarge: TextStyle( fontWeight: FontWeight.bold, color: kColorScheme.onSecondaryContainer, fontSize: 24), titleMedium: TextStyle( fontWeight: FontWeight.w700, color: kColorScheme.onSecondaryContainer, fontSize: 14), ), ), // themeMode: ThemeMode.system, home: const Expenses(), ), ); // }); }
0
mirrored_repositories/Expenses-Tracker/lib
mirrored_repositories/Expenses-Tracker/lib/widgets/new_expense.dart
import 'package:flutter/material.dart'; import 'package:expense_tracker/models/expense.dart'; class NewExpense extends StatefulWidget { const NewExpense({super.key, required this.onAddExpense}); final void Function(Expense expense) onAddExpense; @override State<NewExpense> createState() { return _NewExpenseState(); } } class _NewExpenseState extends State<NewExpense> { final _titleController = TextEditingController(); final _amountController = TextEditingController(); DateTime? _selectedDate; Category _selectedCategory = Category.leisure; void _submitExpenseData() { final eneteredAmount = double.tryParse(_amountController.text); final amountIsValid = (eneteredAmount == null || eneteredAmount <= 0); if (_titleController.text.trim().isEmpty || amountIsValid || _selectedDate == null) { showDialog( context: context, builder: (ctx) => AlertDialog( title: const Text('Invalid Input'), content: const Text( 'Please make sure a valid title, amount, date and category was entered.'), actions: [ TextButton( onPressed: () { Navigator.pop(ctx); }, child: const Text('Okay')), ], ), ); return; } widget.onAddExpense( Expense( title: _titleController.text, amount: eneteredAmount, date: _selectedDate!, category: _selectedCategory), ); Navigator.pop(context); } void _presentDatePicker() async { final now = DateTime.now(); final firstDate = DateTime(now.year - 1, now.month, now.day); final pickedDate = await showDatePicker( context: context, initialDate: now, firstDate: firstDate, lastDate: now); setState(() { _selectedDate = pickedDate; }); } @override void dispose() { _titleController.dispose(); _amountController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final keyboardSpace = MediaQuery.of(context).viewInsets.bottom; return LayoutBuilder(builder: (context, constraints) { final width = constraints.maxWidth; return SizedBox( height: double.infinity, child: SingleChildScrollView( child: Padding( padding: EdgeInsets.fromLTRB(16, 16, 16, 16 + keyboardSpace), child: Column( children: [ if (width >= 600) Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded( child: TextField( controller: _titleController, maxLength: 50, decoration: const InputDecoration( label: Text('Title'), ), ), ), const SizedBox( width: 24, ), Expanded( child: TextField( controller: _amountController, keyboardType: TextInputType.number, decoration: const InputDecoration( prefixText: '\$ ', label: Text('Amount'), ), ), ), ], ) else TextField( controller: _titleController, maxLength: 50, decoration: const InputDecoration( label: Text('Title'), ), ), if (width >= 600) Row( children: [ DropdownButton( value: _selectedCategory, items: Category.values .map((category) => DropdownMenuItem( value: category, child: Text( category.name.toUpperCase(), ), )) .toList(), onChanged: (value) { if (value == null) return; setState(() { _selectedCategory = value; }); }, ), const SizedBox( width: 24, ), Expanded( child: Row( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.center, children: [ Text( _selectedDate == null ? 'No date selected' : formatter.format(_selectedDate!), ), IconButton( onPressed: _presentDatePicker, icon: const Icon( Icons.calendar_month, )), ], )) ], ) else Row( children: [ Expanded( child: TextField( controller: _amountController, keyboardType: TextInputType.number, decoration: const InputDecoration( prefixText: '\$ ', label: Text('Amount'), ), ), ), const SizedBox(width: 16), Expanded( child: Row( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.center, children: [ Text( _selectedDate == null ? 'No date selected' : formatter.format(_selectedDate!), ), IconButton( onPressed: _presentDatePicker, icon: const Icon( Icons.calendar_month, )), ], )) ], ), const SizedBox(height: 16), if (width >= 600) Row( children: [ const Spacer(), TextButton( onPressed: () { Navigator.pop(context); }, child: const Text('Cancel')), ElevatedButton( onPressed: _submitExpenseData, child: const Text('Save Expense')), ], ) else Row( children: [ DropdownButton( value: _selectedCategory, items: Category.values .map((category) => DropdownMenuItem( value: category, child: Text( category.name.toUpperCase(), ), )) .toList(), onChanged: (value) { if (value == null) return; setState(() { _selectedCategory = value; }); }, ), const Spacer(), TextButton( onPressed: () { Navigator.pop(context); }, child: const Text('Cancel')), ElevatedButton( onPressed: _submitExpenseData, child: const Text('Save Expense')), ], ) ], ), ), ), ); }); } }
0
mirrored_repositories/Expenses-Tracker/lib
mirrored_repositories/Expenses-Tracker/lib/widgets/expenses.dart
import 'package:expense_tracker/widgets/chart/chart.dart'; import 'package:expense_tracker/widgets/expenses_list/expenses_list.dart'; import 'package:expense_tracker/widgets/new_expense.dart'; import 'package:flutter/material.dart'; import 'package:expense_tracker/models/expense.dart'; class Expenses extends StatefulWidget { const Expenses({super.key}); @override State<Expenses> createState() { return _ExpensesState(); } } class _ExpensesState extends State<Expenses> { final List<Expense> _registeredExpneses = [ Expense( title: 'Flutter Course', amount: 100.0, date: DateTime.now(), category: Category.work, ), Expense( title: 'Cinema', amount: 25.0, date: DateTime.now(), category: Category.leisure, ) ]; void _addExpense(Expense expense) { setState(() { _registeredExpneses.add(expense); }); } void _removeExpense(Expense expense) { final expenseIndex = _registeredExpneses.indexOf(expense); setState(() { _registeredExpneses.remove(expense); }); ScaffoldMessenger.of(context).clearSnackBars(); ScaffoldMessenger.of(context).showSnackBar(SnackBar( duration: const Duration(seconds: 3), content: const Text('Expense deleted.'), action: SnackBarAction( label: 'Undo', onPressed: () { setState(() { _registeredExpneses.insert(expenseIndex, expense); }); }), )); } void _openAddExpenseOverlay() { showModalBottomSheet( useSafeArea: true, isScrollControlled: true, context: context, builder: (ctx) => NewExpense(onAddExpense: _addExpense)); } @override Widget build(BuildContext context) { final width = MediaQuery.of(context).size.width; Widget mainContent = const Center( child: Text('No Expenses found currently. Start adding some!'), ); if (_registeredExpneses.isNotEmpty) { mainContent = ExpensesList( expenses: _registeredExpneses, onRemoveExpense: _removeExpense); } return Scaffold( appBar: AppBar(title: const Text('Flutter Expense Tracker'), actions: [ IconButton( onPressed: _openAddExpenseOverlay, icon: const Icon(Icons.add), ) ]), body: width < 600 ? Column( children: [ Chart(expenses: _registeredExpneses), Expanded( child: mainContent, ) ], ) : Row( children: [ // chart must be wrapped in expanded widget to work Expanded(child: Chart(expenses: _registeredExpneses)), Expanded( child: mainContent, ) ], ), ); } }
0
mirrored_repositories/Expenses-Tracker/lib/widgets
mirrored_repositories/Expenses-Tracker/lib/widgets/expenses_list/expense_item.dart
import 'package:expense_tracker/models/expense.dart'; import 'package:flutter/material.dart'; class ExpenseItem extends StatelessWidget { const ExpenseItem(this.expense, {super.key}); final Expense expense; @override Widget build(BuildContext context) { return Card( child: Padding( padding: const EdgeInsets.symmetric( horizontal: 20, vertical: 16, ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( expense.title, style: Theme.of(context).textTheme.titleMedium, ), const SizedBox(height: 4), Row( children: [ Text('\$${expense.amount.toStringAsFixed(2)}'), const Spacer(), Row( children: [ Icon(categoryIcons[expense.category]), const SizedBox(width: 8), Text(expense.formattedDate), ], ), ], ) ], ), ), ); } }
0
mirrored_repositories/Expenses-Tracker/lib/widgets
mirrored_repositories/Expenses-Tracker/lib/widgets/expenses_list/expenses_list.dart
import 'package:expense_tracker/widgets/expenses_list/expense_item.dart'; import 'package:flutter/material.dart'; import 'package:expense_tracker/models/expense.dart'; class ExpensesList extends StatelessWidget { const ExpensesList({ super.key, required this.expenses, required this.onRemoveExpense, }); final List<Expense> expenses; final void Function(Expense expense) onRemoveExpense; @override Widget build(BuildContext context) { return ListView.builder( itemCount: expenses.length, itemBuilder: (ctx, index) => Dismissible( background: Container( color: Theme.of(context).colorScheme.error, margin: EdgeInsets.symmetric( horizontal: Theme.of(context).cardTheme.margin!.horizontal, ), ), key: ValueKey(expenses[index]), onDismissed: (direstion) { onRemoveExpense(expenses[index]); }, child: ExpenseItem(expenses[index]), ), ); } }
0
mirrored_repositories/Expenses-Tracker/lib/widgets
mirrored_repositories/Expenses-Tracker/lib/widgets/chart/chart.dart
import 'package:flutter/material.dart'; import 'package:expense_tracker/widgets/chart/chart_bar.dart'; import 'package:expense_tracker/models/expense.dart'; class Chart extends StatelessWidget { const Chart({super.key, required this.expenses}); final List<Expense> expenses; List<ExpenseBucket> get buckets { return [ ExpenseBucket.forCategory(expenses, Category.food), ExpenseBucket.forCategory(expenses, Category.leisure), ExpenseBucket.forCategory(expenses, Category.travel), ExpenseBucket.forCategory(expenses, Category.work), ]; } double get maxTotalExpense { double maxTotalExpense = 0; for (final bucket in buckets) { if (bucket.totalExpenses > maxTotalExpense) { maxTotalExpense = bucket.totalExpenses; } } return maxTotalExpense; } @override Widget build(BuildContext context) { final isDarkMode = MediaQuery.of(context).platformBrightness == Brightness.dark; return Container( margin: const EdgeInsets.all(16), padding: const EdgeInsets.symmetric( vertical: 16, horizontal: 8, ), width: double.infinity, height: 180, decoration: BoxDecoration( borderRadius: BorderRadius.circular(8), gradient: LinearGradient( colors: [ Theme.of(context).colorScheme.primary.withOpacity(0.3), Theme.of(context).colorScheme.primary.withOpacity(0.0) ], begin: Alignment.bottomCenter, end: Alignment.topCenter, ), ), child: Column( children: [ Expanded( child: Row( crossAxisAlignment: CrossAxisAlignment.end, children: [ for (final bucket in buckets) // alternative to map() ChartBar( fill: bucket.totalExpenses == 0 ? 0 : bucket.totalExpenses / maxTotalExpense, ) ], ), ), const SizedBox(height: 12), Row( children: buckets .map( (bucket) => Expanded( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 4), child: Icon( categoryIcons[bucket.category], color: isDarkMode ? Theme.of(context).colorScheme.secondary : Theme.of(context) .colorScheme .primary .withOpacity(0.7), ), ), ), ) .toList(), ) ], ), ); } }
0
mirrored_repositories/Expenses-Tracker/lib/widgets
mirrored_repositories/Expenses-Tracker/lib/widgets/chart/chart_bar.dart
import 'package:flutter/material.dart'; class ChartBar extends StatelessWidget { const ChartBar({ super.key, required this.fill, }); final double fill; @override Widget build(BuildContext context) { final isDarkMode = MediaQuery.of(context).platformBrightness == Brightness.dark; return Expanded( child: Padding( padding: const EdgeInsets.symmetric(horizontal: 4), child: FractionallySizedBox( heightFactor: fill, child: DecoratedBox( decoration: BoxDecoration( shape: BoxShape.rectangle, borderRadius: const BorderRadius.vertical(top: Radius.circular(8)), color: isDarkMode ? Theme.of(context).colorScheme.secondary : Theme.of(context).colorScheme.primary.withOpacity(0.65), ), ), ), ), ); } }
0
mirrored_repositories/Expenses-Tracker/lib
mirrored_repositories/Expenses-Tracker/lib/models/expense.dart
import 'package:flutter/material.dart'; import 'package:uuid/uuid.dart'; import 'package:intl/intl.dart'; final formatter = DateFormat.yMd(); const uuid = Uuid(); enum Category { food, travel, leisure, work } const categoryIcons = { Category.food: Icons.lunch_dining, Category.travel: Icons.flight_takeoff, Category.leisure: Icons.movie, Category.work: Icons.work, }; class Expense { Expense({ required this.title, required this.amount, required this.date, required this.category, }) : id = uuid.v4(); final String id; final String title; final double amount; final DateTime date; final Category category; String get formattedDate { return formatter.format(date); } } class ExpenseBucket { const ExpenseBucket({ required this.category, required this.expenses, }); ExpenseBucket.forCategory(List<Expense> allExpenses, this.category) : expenses = allExpenses .where((expense) => expense.category == category) .toList(); final Category category; final List<Expense> expenses; double get totalExpenses { double sum = 0; for (final expense in expenses) { sum += expense.amount; } return sum; } }
0
mirrored_repositories/flutter-logs
mirrored_repositories/flutter-logs/lib/main.dart
import 'dart:developer' as developer; import 'package:flutter/material.dart'; void main() { runApp( const MyApp(), ); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'Logs in Flutter', theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({ Key? key, required this.title, }) : super(key: key); final String title; @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() async { final timelineTask = developer.TimelineTask(); timelineTask.start('_incrementCounter'); try { // developer.Timeline.startSync('_incrementCounter'); await Future.delayed( const Duration(seconds: 2), ); print('calling _incrementCounter'); // int.parse('abc'); developer.log( 'calling _incrementCounter', name: 'felipecastrosales', error: 'sending error', ); developer.inspect(_counter); developer.debugger(); developer.debugger(when: _counter > 2); setState(() { _counter++; }); developer.inspect(this); developer.inspect(_counter); } catch (e, s) { developer.log( 'error in _incrementCounter', name: 'felipecastrosales', error: e.toString(), stackTrace: s, ); } // developer.Timeline.finishSync(); timelineTask.finish(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ const Text( 'You have pushed the button this many times:', ), Text( '$_counter', style: Theme.of(context).textTheme.headline4, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: const Icon(Icons.add), ), ); } }
0
mirrored_repositories/flutter-logs
mirrored_repositories/flutter-logs/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_logs/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/flutter-basics/spanishaudionum
mirrored_repositories/flutter-basics/spanishaudionum/lib/NumberAudio.dart
import 'package:flutter/material.dart'; class NumberAudio { String audioUri; MaterialColor buttonColor; String buttonText; NumberAudio(String aU, MaterialColor bC, String bT) { this.audioUri = aU; this.buttonColor = bC; this.buttonText = bT; } }
0
mirrored_repositories/flutter-basics/spanishaudionum
mirrored_repositories/flutter-basics/spanishaudionum/lib/HomePage.dart
import 'package:flutter/material.dart'; import 'NumberAudio.dart'; import 'package:audioplayers/audio_cache.dart'; class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { AudioCache audioPlayer = AudioCache(); List<NumberAudio> numberList = [ NumberAudio("one.wav", Colors.red, "One"), NumberAudio("two.wav", Colors.brown, "Two"), NumberAudio("three.wav", Colors.purple, "Three"), NumberAudio("four.wav", Colors.orange, "Four"), NumberAudio("five.wav", Colors.blue, "Five"), NumberAudio("six.wav", Colors.grey, "Six"), NumberAudio("seven.wav", Colors.teal, "Seven"), NumberAudio("eight.wav", Colors.yellow, "Eight"), NumberAudio("nine.wav", Colors.pink, "Nine"), NumberAudio("ten.wav", Colors.green, "Ten"), ]; play(String uri) { audioPlayer.play(uri); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Spanish Numbers'), ), body: Container( child: Center( child: Column( children: <Widget>[ Image(image: AssetImage('assets/logo.png')), Expanded( child: GridView.builder( padding: EdgeInsets.all(10), gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, childAspectRatio: 2.0, crossAxisSpacing: 10, mainAxisSpacing: 10), itemCount: numberList.length, itemBuilder: (BuildContext context, int i) => SizedBox( height: 50, width: 100, child: RaisedButton( onPressed: () { play(numberList[i].audioUri); }, color: numberList[i].buttonColor, child: Text( numberList[i].buttonText, style: TextStyle(fontSize: 20, color: Colors.white), ), ), ), )) ], ), ), ), ); } }
0
mirrored_repositories/flutter-basics/spanishaudionum
mirrored_repositories/flutter-basics/spanishaudionum/lib/main.dart
import 'package:flutter/material.dart'; import 'HomePage.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Spanish Number Audio', debugShowCheckedModeBanner: false, theme: ThemeData(primarySwatch: Colors.blue), home: HomePage(), ); } }
0
mirrored_repositories/flutter-basics/spanishaudionum
mirrored_repositories/flutter-basics/spanishaudionum/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:spanishaudionum/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/flutter-basics/scratchandwin
mirrored_repositories/flutter-basics/scratchandwin/lib/HomePage.dart
import 'package:flutter/material.dart'; import 'dart:math'; class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { //TODO import images AssetImage circle = AssetImage('images/circle.png'); AssetImage lucky = AssetImage('images/rupee.png'); AssetImage unlucky = AssetImage('images/sadFace.png'); // TODO get an array List<String> itemArray; int luckyNumber; String message = ''; int chances = 3; //TODO init array with 25 element @override void initState() { super.initState(); itemArray = List<String>.generate(25, (index) => 'empty'); generateRandomNumber(); } generateRandomNumber() { int rnd = Random().nextInt(25); print(rnd); setState(() { luckyNumber = rnd; }); } // TODO define getimage method AssetImage getImage(int index) { String currentState = itemArray[index]; switch (currentState) { case 'lucky': return lucky; break; case 'unlucky': return unlucky; break; } return circle; } //TODO play game method playGame(int index) { if (chances > 0) { if (index == luckyNumber) { setState(() { itemArray[index] = 'lucky'; message = 'Congrates You won'; chances = -1; }); } else if (index != luckyNumber && chances > 0) { setState(() { itemArray[index] = 'unlucky'; message = 'You have ${chances - 1} left'; chances--; }); if (chances == 0) { setState(() { message = 'You loose'; }); } } } } //TODO Show all showAll() { setState(() { itemArray = List<String>.filled(25, 'unlucky'); itemArray[luckyNumber] = 'lucky'; chances = -1; }); } //TODO reset all resetGame() { setState(() { itemArray = List<String>.filled(25, 'empty'); }); message = ''; generateRandomNumber(); chances = 3; } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Scratch And Win'), ), body: Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ Expanded( child: GridView.builder( padding: EdgeInsets.all(20), gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 5, childAspectRatio: 1.0, crossAxisSpacing: 10, mainAxisSpacing: 10, ), itemCount: itemArray.length, itemBuilder: (BuildContext context, int i) => SizedBox( width: 50, height: 50, child: RaisedButton( onPressed: () { playGame(i); }, child: Image(image: getImage(i)), ), ), )), Container( margin: EdgeInsets.only(bottom: 50), padding: EdgeInsets.all(30), child: Text( message, style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold), ), ), Container( margin: EdgeInsets.all(15), child: ClipRRect( borderRadius: BorderRadius.circular(30), child: RaisedButton( onPressed: showAll, color: Colors.pink, padding: EdgeInsets.all(10), child: Text( 'Show All', style: TextStyle( color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold), ), ), ), ), Container( margin: EdgeInsets.all(15), child: ClipRRect( borderRadius: BorderRadius.circular(30), child: RaisedButton( onPressed: resetGame, color: Colors.pink, padding: EdgeInsets.all(10), child: Text( 'Reset Game', style: TextStyle( fontSize: 20, fontWeight: FontWeight.bold, color: Colors.white), ), ), ), ), ], ), ); } }
0
mirrored_repositories/flutter-basics/scratchandwin
mirrored_repositories/flutter-basics/scratchandwin/lib/main.dart
import 'package:flutter/material.dart'; import 'HomePage.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Scratch And Win', debugShowCheckedModeBanner: false, theme: ThemeData(primarySwatch: Colors.pink), home: HomePage(), ); } }
0
mirrored_repositories/flutter-basics/scratchandwin
mirrored_repositories/flutter-basics/scratchandwin/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:scratchandwin/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/flutter-basics/simpleCameraApp
mirrored_repositories/flutter-basics/simpleCameraApp/lib/HomePage.dart
import 'package:flutter/material.dart'; import 'package:image_picker/image_picker.dart'; import 'dart:io'; import 'dart:async'; class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { File _image; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Camera App'), ), body: Container( margin: EdgeInsets.all(30), child: Center( child: _image == null ? Text('NO Image') : Image.file(_image), ), ), floatingActionButton: FloatingActionButton( onPressed: _optionsDialogBox, child: Icon(Icons.add_a_photo), tooltip: 'Open Camera', ), ); } Future<void> _optionsDialogBox() { return showDialog( context: context, builder: (BuildContext context) { return AlertDialog( backgroundColor: Colors.blue, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), content: SingleChildScrollView( child: ListBody( children: <Widget>[ GestureDetector( onTap: openCamera, child: Text( 'Take a picture', style: TextStyle(color: Colors.white, fontSize: 20), ), ), Padding(padding: EdgeInsets.all(10)), GestureDetector( onTap: openGallery, child: Text( 'Open Gallery', style: TextStyle(color: Colors.white, fontSize: 20), ), ) ], ), ), ); }); } // Camera method Future openCamera() async { var image = await ImagePicker().getImage(source: ImageSource.camera); setState(() { _image = File(image.path); }); } //Gallery method Future openGallery() async { var picture = await ImagePicker().getImage(source: ImageSource.gallery); setState(() { _image = File(picture.path); }); } }
0
mirrored_repositories/flutter-basics/simpleCameraApp
mirrored_repositories/flutter-basics/simpleCameraApp/lib/main.dart
import 'package:flutter/material.dart'; import 'HomePage.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Camera App', debugShowCheckedModeBanner: false, color: Colors.blue, home: HomePage(), ); } }
0
mirrored_repositories/flutter-basics/simpleCameraApp
mirrored_repositories/flutter-basics/simpleCameraApp/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:simpleCameraApp/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/flutter-basics/tictactoe
mirrored_repositories/flutter-basics/tictactoe/lib/HomePage.dart
import 'package:flutter/material.dart'; import 'dart:async'; class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { //TODO: link up all images AssetImage circle = AssetImage('images/circle.png'); AssetImage cross = AssetImage('images/cross.png'); AssetImage edit = AssetImage('images/edit.png'); bool isCross = true; String message; List<String> gameState; //TODO: initialize state with empty box @override void initState() { super.initState(); setState(() { this.gameState = [ 'empty', 'empty', 'empty', 'empty', 'empty', 'empty', 'empty', 'empty', 'empty', ]; this.message = ''; }); } // TODO playGame method playGame(int index) { if (this.gameState[index] == 'empty') { setState(() { if (this.isCross) { this.gameState[index] = 'cross'; } else { this.gameState[index] = 'circle'; } this.isCross = !this.isCross; this.checkWin(); }); } } //TODO reset game method resetGame() { setState(() { this.gameState = [ 'empty', 'empty', 'empty', 'empty', 'empty', 'empty', 'empty', 'empty', 'empty', ]; this.message = ''; }); } // TODO getImages method AssetImage getImage(String value) { switch (value) { case ('empty'): return edit; break; case ('circle'): return circle; break; case ('cross'): return cross; break; } } //TODO reset game automatically when someone wins automaticReset() { Timer(Duration(seconds: 2), () { resetGame(); }); } //TODO Check winning logic checkWin() { if ((gameState[0] != 'empty') && (gameState[0] == gameState[1]) && (gameState[1] == gameState[2])) { setState(() { this.message = '${gameState[0]} Wins'; automaticReset(); }); } else if ((gameState[3] != 'empty') && (gameState[3] == gameState[4]) && (gameState[4] == gameState[5])) { setState(() { this.message = '${gameState[3]} Wins'; automaticReset(); }); } else if ((gameState[6] != 'empty') && (gameState[6] == gameState[7]) && (gameState[7] == gameState[8])) { setState(() { this.message = "${gameState[6]} Wins"; automaticReset(); }); } else if ((gameState[0] != 'empty') && (gameState[0] == gameState[3]) && (gameState[3] == gameState[6])) { setState(() { this.message = '${gameState[0]} Wins'; automaticReset(); }); } else if ((gameState[1] != 'empty') && (gameState[1] == gameState[4]) && (gameState[4] == gameState[7])) { setState(() { this.message = '${gameState[1]} Wins'; automaticReset(); }); } else if ((gameState[2] != 'empty') && (gameState[2] == gameState[5]) && (gameState[5] == gameState[8])) { setState(() { this.message = '${gameState[2]} Wins'; automaticReset(); }); } else if ((gameState[0] != 'empty') && (gameState[0] == gameState[4]) && (gameState[4] == gameState[8])) { setState(() { this.message = '${gameState[0]} Wins'; automaticReset(); }); } else if ((gameState[2] != 'empty') && (gameState[2] == gameState[4]) && (gameState[4]) == gameState[6]) { setState(() { this.message = '${gameState[2]} Wins'; automaticReset(); }); } else if (!gameState.contains('empty')) { setState(() { this.message = 'Game Draw'; automaticReset(); }); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Tic Tac Toe'), ), body: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ Expanded( child: GridView.builder( padding: EdgeInsets.all(20), gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 3, childAspectRatio: 1.0, crossAxisSpacing: 10, mainAxisSpacing: 10), itemCount: gameState.length, itemBuilder: (BuildContext context, i) => SizedBox( width: 100.0, height: 100.0, child: MaterialButton( onPressed: () { this.playGame(i); }, child: Image(image: this.getImage(this.gameState[i])), ), ))), Container( padding: EdgeInsets.all(30), child: Text( this.message, style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold), ), ), ClipRRect( borderRadius: BorderRadius.circular(20), child: MaterialButton( onPressed: resetGame, color: Colors.purple, minWidth: 300, height: 50, child: Text( 'Reset Game!', style: TextStyle(fontSize: 20, color: Colors.white), ), ), ), Container( padding: EdgeInsets.all(10), ) ], ), ); } }
0
mirrored_repositories/flutter-basics/tictactoe
mirrored_repositories/flutter-basics/tictactoe/lib/main.dart
import 'package:flutter/material.dart'; import 'HomePage.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Tic Tac Toe', debugShowCheckedModeBanner: false, theme: ThemeData(primarySwatch: Colors.purple), home: HomePage(), ); } }
0
mirrored_repositories/flutter-basics/tictactoe
mirrored_repositories/flutter-basics/tictactoe/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:tictactoe/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