repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/puzzles/lib
mirrored_repositories/puzzles/lib/puzzles/puzzle_types.dart
enum PUZZLETYPE { xoxo, letters, shapes, mixed }
0
mirrored_repositories/puzzles/lib
mirrored_repositories/puzzles/lib/puzzles/puzzles.dart
export 'puzzle_types.dart';
0
mirrored_repositories/puzzles/lib
mirrored_repositories/puzzles/lib/app/app.dart
export 'view/app.dart';
0
mirrored_repositories/puzzles/lib/app
mirrored_repositories/puzzles/lib/app/view/app.dart
import 'package:flutter/material.dart'; import 'package:puzzles/l10n/l10n.dart'; import 'package:puzzles/router/app_router.dart'; import 'package:puzzles/theme/theme.dart'; class App extends StatelessWidget { const App({super.key}); @override Widget build(BuildContext context) { final appRouter = AppRouter(); return MaterialApp.router( routerDelegate: appRouter.delegate(), routeInformationParser: appRouter.defaultRouteParser(), routeInformationProvider: appRouter.routeInfoProvider(), theme: PuzzlesTheme.light, darkTheme: PuzzlesTheme.dark, localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, ); } }
0
mirrored_repositories/puzzles/lib
mirrored_repositories/puzzles/lib/gen/assets.gen.dart
/// GENERATED CODE - DO NOT MODIFY BY HAND /// ***************************************************** /// FlutterGen /// ***************************************************** // coverage:ignore-file // ignore_for_file: type=lint // ignore_for_file: directives_ordering,unnecessary_import,implicit_dynamic_list_literal,deprecated_member_use import 'package:flutter/widgets.dart'; class $AssetsSvgsGen { const $AssetsSvgsGen(); /// File path: assets/svgs/letters.svg String get letters => 'assets/svgs/letters.svg'; /// File path: assets/svgs/mixed.svg String get mixed => 'assets/svgs/mixed.svg'; /// File path: assets/svgs/shapes.svg String get shapes => 'assets/svgs/shapes.svg'; /// File path: assets/svgs/xoxo.svg String get xoxo => 'assets/svgs/xoxo.svg'; /// List of all assets List<String> get values => [letters, mixed, shapes, xoxo]; } class Assets { Assets._(); static const $AssetsSvgsGen svgs = $AssetsSvgsGen(); } class AssetGenImage { const AssetGenImage(this._assetName); final String _assetName; Image image({ Key? key, AssetBundle? bundle, ImageFrameBuilder? frameBuilder, ImageErrorWidgetBuilder? errorBuilder, String? semanticLabel, bool excludeFromSemantics = false, double? scale, double? width, double? height, Color? color, Animation<double>? opacity, BlendMode? colorBlendMode, BoxFit? fit, AlignmentGeometry alignment = Alignment.center, ImageRepeat repeat = ImageRepeat.noRepeat, Rect? centerSlice, bool matchTextDirection = false, bool gaplessPlayback = false, bool isAntiAlias = false, String? package, FilterQuality filterQuality = FilterQuality.low, int? cacheWidth, int? cacheHeight, }) { return Image.asset( _assetName, key: key, bundle: bundle, frameBuilder: frameBuilder, errorBuilder: errorBuilder, semanticLabel: semanticLabel, excludeFromSemantics: excludeFromSemantics, scale: scale, width: width, height: height, color: color, opacity: opacity, colorBlendMode: colorBlendMode, fit: fit, alignment: alignment, repeat: repeat, centerSlice: centerSlice, matchTextDirection: matchTextDirection, gaplessPlayback: gaplessPlayback, isAntiAlias: isAntiAlias, package: package, filterQuality: filterQuality, cacheWidth: cacheWidth, cacheHeight: cacheHeight, ); } ImageProvider provider() => AssetImage(_assetName); String get path => _assetName; String get keyName => _assetName; }
0
mirrored_repositories/puzzles/lib
mirrored_repositories/puzzles/lib/router/app_router.gr.dart
// ************************************************************************** // AutoRouteGenerator // ************************************************************************** // GENERATED CODE - DO NOT MODIFY BY HAND // ************************************************************************** // AutoRouteGenerator // ************************************************************************** // // ignore_for_file: type=lint part of 'app_router.dart'; class _$AppRouter extends RootStackRouter { _$AppRouter([GlobalKey<NavigatorState>? navigatorKey]) : super(navigatorKey); @override final Map<String, PageFactory> pagesMap = { HomePageRoute.name: (routeData) { return AdaptivePage<dynamic>( routeData: routeData, child: const HomePage(), opaque: true, ); } }; @override List<RouteConfig> get routes => [ RouteConfig( HomePageRoute.name, path: '/', ) ]; } /// generated route for /// [HomePage] class HomePageRoute extends PageRouteInfo<void> { const HomePageRoute() : super( HomePageRoute.name, path: '/', ); static const String name = 'HomePageRoute'; }
0
mirrored_repositories/puzzles/lib
mirrored_repositories/puzzles/lib/router/app_router.dart
import 'package:auto_route/auto_route.dart'; import 'package:flutter/material.dart'; import 'package:puzzles/home/view/view.dart'; part 'app_router.gr.dart'; @MaterialAutoRouter( routes: <AdaptiveRoute>[ AdaptiveRoute<dynamic>(page: HomePage, initial: true), ], ) class AppRouter extends _$AppRouter {}
0
mirrored_repositories/puzzles/lib
mirrored_repositories/puzzles/lib/theme/theme.dart
import 'package:flutter/material.dart'; class PuzzlesTheme { static ThemeData get light { return ThemeData( appBarTheme: const AppBarTheme( color: Colors.greenAccent, ), colorScheme: ColorScheme.fromSwatch( accentColor: Colors.greenAccent, primarySwatch: Colors.green, ), snackBarTheme: const SnackBarThemeData( behavior: SnackBarBehavior.floating, ), ); } static ThemeData get dark { return ThemeData( appBarTheme: const AppBarTheme( color: Colors.greenAccent, ), colorScheme: ColorScheme.fromSwatch( brightness: Brightness.dark, accentColor: Colors.greenAccent, primarySwatch: Colors.green, ), snackBarTheme: const SnackBarThemeData( behavior: SnackBarBehavior.floating, ), ); } }
0
mirrored_repositories/puzzles/lib
mirrored_repositories/puzzles/lib/counter/counter.dart
export 'cubit/counter_cubit.dart'; export 'view/counter_page.dart';
0
mirrored_repositories/puzzles/lib/counter
mirrored_repositories/puzzles/lib/counter/view/counter_page.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:puzzles/counter/counter.dart'; import 'package:puzzles/l10n/l10n.dart'; class CounterPage extends StatelessWidget { const CounterPage({super.key}); @override Widget build(BuildContext context) { return BlocProvider( create: (_) => CounterCubit(), child: const CounterView(), ); } } class CounterView extends StatelessWidget { const CounterView({super.key}); @override Widget build(BuildContext context) { final l10n = context.l10n; return Scaffold( appBar: AppBar(title: Text(l10n.counterAppBarTitle)), body: const Center(child: CounterText()), floatingActionButton: Column( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.end, children: [ FloatingActionButton( onPressed: () => context.read<CounterCubit>().increment(), child: const Icon(Icons.add), ), const SizedBox(height: 8), FloatingActionButton( onPressed: () => context.read<CounterCubit>().decrement(), child: const Icon(Icons.remove), ), ], ), ); } } class CounterText extends StatelessWidget { const CounterText({super.key}); @override Widget build(BuildContext context) { final theme = Theme.of(context); final count = context.select((CounterCubit cubit) => cubit.state); return Text('$count', style: theme.textTheme.displayLarge); } }
0
mirrored_repositories/puzzles/lib/counter
mirrored_repositories/puzzles/lib/counter/cubit/counter_cubit.dart
import 'package:bloc/bloc.dart'; class CounterCubit extends Cubit<int> { CounterCubit() : super(0); void increment() => emit(state + 1); void decrement() => emit(state - 1); }
0
mirrored_repositories/puzzles/lib/home
mirrored_repositories/puzzles/lib/home/view/home_page.dart
import 'package:flutter/material.dart'; import 'package:puzzles/gen/assets.gen.dart'; import 'package:puzzles/home/view/widgets/home_widgets.dart'; import 'package:puzzles/l10n/l10n.dart'; import 'package:puzzles/puzzles/puzzles.dart'; class HomePage extends StatelessWidget { const HomePage({super.key}); @override Widget build(BuildContext context) { final l10n = context.l10n; return Scaffold( body: CustomScrollView( slivers: [ SliverAppBar( title: Text(l10n.puzzlesAppBarTitle), elevation: 0, ), SliverGrid.count( crossAxisCount: 2, childAspectRatio: 1.7, children: [ PuzzleTypeCard( asset: Assets.svgs.letters, title: l10n.lettersText, puzzletype: PUZZLETYPE.letters, ), PuzzleTypeCard( asset: Assets.svgs.xoxo, title: l10n.xoxoText, puzzletype: PUZZLETYPE.xoxo, ), PuzzleTypeCard( asset: Assets.svgs.shapes, title: l10n.shapesText, puzzletype: PUZZLETYPE.shapes, ), PuzzleTypeCard( asset: Assets.svgs.mixed, title: l10n.mixedPuzzlesText, puzzletype: PUZZLETYPE.mixed, ), ], ), const SliverToBoxAdapter( child: SizedBox(height: 120), ) ], ), ); } }
0
mirrored_repositories/puzzles/lib/home
mirrored_repositories/puzzles/lib/home/view/view.dart
export 'home_page.dart';
0
mirrored_repositories/puzzles/lib/home/view
mirrored_repositories/puzzles/lib/home/view/widgets/puzzle_tye_card.dart
import 'package:flutter/material.dart'; import 'package:flutter_svg/svg.dart'; import 'package:puzzles/l10n/l10n.dart'; import 'package:puzzles/puzzles/puzzles.dart'; /// {@template puzzles_type_card} /// Used to display what types of puzzles. /// /// [title] the title of the puzzle type eg xoxo /// /// [asset] an svg asset path else the title will be used /// /// [puzzletype] Used to identify type of puzzle when navigating /// {@endtemplate} class PuzzleTypeCard extends StatelessWidget { const PuzzleTypeCard({ super.key, required this.title, this.asset, required this.puzzletype, }); /// [asset] an svg asset path else the title will be used final String? asset; /// [title] the title of the puzzle type eg xoxo final String title; /// [puzzletype] Used to identify type of puzzle when navigating final PUZZLETYPE puzzletype; @override Widget build(BuildContext context) { final l10n = context.l10n; return Container( margin: const EdgeInsets.all(8), decoration: BoxDecoration( color: Theme.of(context).cardColor, borderRadius: BorderRadius.circular(12), border: Border.all(color: Theme.of(context).primaryColor), ), child: Padding( padding: const EdgeInsets.all(4), child: Column( children: [ const SizedBox( height: 4, ), if (asset?.isNotEmpty ?? false) SvgPicture.asset( asset!, height: kToolbarHeight, width: kToolbarHeight, colorFilter: ColorFilter.mode( Theme.of(context).indicatorColor, BlendMode.srcIn, ), ), if (asset?.isNotEmpty ?? false) const SizedBox( height: 8, ), Text( '$title ${l10n.puzzlesAppBarTitle}', style: const TextStyle(fontSize: 20), ), const SizedBox( height: 4, ), ], ), ), ); } }
0
mirrored_repositories/puzzles/lib/home/view
mirrored_repositories/puzzles/lib/home/view/widgets/home_widgets.dart
export 'puzzle_tye_card.dart';
0
mirrored_repositories/puzzles/lib
mirrored_repositories/puzzles/lib/l10n/l10n.dart
import 'package:flutter/widgets.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; export 'package:flutter_gen/gen_l10n/app_localizations.dart'; extension AppLocalizationsX on BuildContext { AppLocalizations get l10n => AppLocalizations.of(this); }
0
mirrored_repositories/puzzles/test/app
mirrored_repositories/puzzles/test/app/view/app_test.dart
import 'package:flutter_test/flutter_test.dart'; import 'package:puzzles/app/app.dart'; import 'package:puzzles/counter/counter.dart'; void main() { group('App', () { testWidgets('renders CounterPage', (tester) async { await tester.pumpWidget(const App()); expect(find.byType(CounterPage), findsOneWidget); }); }); }
0
mirrored_repositories/puzzles/test/counter
mirrored_repositories/puzzles/test/counter/view/counter_page_test.dart
import 'package:bloc_test/bloc_test.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:puzzles/counter/counter.dart'; import '../../helpers/helpers.dart'; class MockCounterCubit extends MockCubit<int> implements CounterCubit {} void main() { group('CounterPage', () { testWidgets('renders CounterView', (tester) async { await tester.pumpApp(const CounterPage()); expect(find.byType(CounterView), findsOneWidget); }); }); group('CounterView', () { late CounterCubit counterCubit; setUp(() { counterCubit = MockCounterCubit(); }); testWidgets('renders current count', (tester) async { const state = 42; when(() => counterCubit.state).thenReturn(state); await tester.pumpApp( BlocProvider.value( value: counterCubit, child: const CounterView(), ), ); expect(find.text('$state'), findsOneWidget); }); testWidgets('calls increment when increment button is tapped', (tester) async { when(() => counterCubit.state).thenReturn(0); when(() => counterCubit.increment()).thenReturn(null); await tester.pumpApp( BlocProvider.value( value: counterCubit, child: const CounterView(), ), ); await tester.tap(find.byIcon(Icons.add)); verify(() => counterCubit.increment()).called(1); }); testWidgets('calls decrement when decrement button is tapped', (tester) async { when(() => counterCubit.state).thenReturn(0); when(() => counterCubit.decrement()).thenReturn(null); await tester.pumpApp( BlocProvider.value( value: counterCubit, child: const CounterView(), ), ); await tester.tap(find.byIcon(Icons.remove)); verify(() => counterCubit.decrement()).called(1); }); }); }
0
mirrored_repositories/puzzles/test/counter
mirrored_repositories/puzzles/test/counter/cubit/counter_cubit_test.dart
import 'package:bloc_test/bloc_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:puzzles/counter/counter.dart'; void main() { group('CounterCubit', () { test('initial state is 0', () { expect(CounterCubit().state, equals(0)); }); blocTest<CounterCubit, int>( 'emits [1] when increment is called', build: CounterCubit.new, act: (cubit) => cubit.increment(), expect: () => [equals(1)], ); blocTest<CounterCubit, int>( 'emits [-1] when decrement is called', build: CounterCubit.new, act: (cubit) => cubit.decrement(), expect: () => [equals(-1)], ); }); }
0
mirrored_repositories/puzzles/test
mirrored_repositories/puzzles/test/helpers/helpers.dart
export 'pump_app.dart';
0
mirrored_repositories/puzzles/test
mirrored_repositories/puzzles/test/helpers/pump_app.dart
import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:puzzles/l10n/l10n.dart'; extension PumpApp on WidgetTester { Future<void> pumpApp(Widget widget) { return pumpWidget( MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, home: widget, ), ); } }
0
mirrored_repositories/puzzles/packages/xoxo_generator
mirrored_repositories/puzzles/packages/xoxo_generator/lib/xoxo_generator.dart
/// An API that handles xoxo generation related requests. library xoxo_generator; export 'src/xoxo_generator.dart';
0
mirrored_repositories/puzzles/packages/xoxo_generator/lib
mirrored_repositories/puzzles/packages/xoxo_generator/lib/src/xoxo_generator.dart
import 'dart:math'; /// {@template xoxo_generator} /// An API that handles xoxo generation related requests. /// {@endtemplate} class XoxoGenerator { /// {@macro xoxo_generator} const XoxoGenerator(); /// {@template xoxo_randomXOXOGenerator} /// [randomXOXOGenerator] generates random [String]s of xoxo /// Using [Random] if even make words similar else switcharoo one letter /// /// [length] is used to count no of characters with 4 being min /// {@endtemplate} Future<List<String>> randomXOXOGenerator(int? length) async { assert(length == null || length > 4, 'Length must be greater than 4'); final random = Random(); /// generate similar xoxo's if (random.nextInt(100).isEven) { final word1 = generateMixedXOXO(length); return [word1, word1]; } else { final word1 = generateMixedXOXO(length); final word2 = generateSimilarXOXO(word1); return [word1, word2]; } } /// Used to generate first Word /// if [length] generate up to 4 String generateMixedXOXO(int? length) { final random = Random(); var word = ''; for (var i = 0; i < (length ?? 4); i++) { final char = (random.nextInt(100).isEven) ? 'x' : 'o'; // ignore: use_string_buffers word += char; } return word; } /// Used to generate 2nd word from first word /// Its tweak a bit String generateSimilarXOXO(String originalWord) { final random = Random(); var word = originalWord; final index = random.nextInt(word.length - 2) + 1; final oldChar = word[index]; final newChar = (oldChar == 'x') ? 'o' : 'x'; // ignore: join_return_with_assignment word = word.substring(0, index) + newChar + word.substring(index + 1); return word; } }
0
mirrored_repositories/puzzles/packages/xoxo_generator/test
mirrored_repositories/puzzles/packages/xoxo_generator/test/src/xoxo_generator_test.dart
// ignore_for_file: prefer_const_constructors import 'package:test/test.dart'; import 'package:xoxo_generator/xoxo_generator.dart'; void main() { group('XoxoGenerator', () { test('can be instantiated', () { expect(XoxoGenerator(), isNotNull); }); test('Can generate random xoxo and match iven length', () async { final xoxoGenerator = XoxoGenerator(); // Test case 1: Generate word with length 7 final word1 = await xoxoGenerator.randomXOXOGenerator(7); expect(word1, isA<List<String>>()); expect(word1.first.length, 7); expect(word1[1].length, 7); }); test('xoxo Generated xoxo that match length', () async { final xoxoGenerator = XoxoGenerator(); // Test case 1: Generate word with length 7 final word1 = xoxoGenerator.generateMixedXOXO(7); expect(word1, isA<String>()); expect(word1.length, 7); // Test case 2: Generate word with length 7 final word2 = xoxoGenerator.generateSimilarXOXO(word1); expect(word2, isA<String>()); expect(word2.length, 7); }); }); }
0
mirrored_repositories/puzzles/packages/puzzles_repository
mirrored_repositories/puzzles/packages/puzzles_repository/lib/puzzles_repository.dart
/// A repository that handles puzzles related requests. library puzzles_repository; export 'src/puzzles_repository.dart';
0
mirrored_repositories/puzzles/packages/puzzles_repository/lib
mirrored_repositories/puzzles/packages/puzzles_repository/lib/src/puzzles_repository.dart
import 'package:local_storage_puzzles_api/local_storage_puzzles_api.dart'; import 'package:puzzles_api/puzzles_api.dart'; /// {@template puzzles_repository} /// A repository that handles puzzles related requests. /// {@endtemplate} class PuzzlesRepository { /// {@macro puzzles_repository} const PuzzlesRepository({ required LocalStoragePuzzlesApi localStoragePuzzlesApi, }) : _localStoragePuzzlesApi = localStoragePuzzlesApi; final LocalStoragePuzzlesApi _localStoragePuzzlesApi; /// Insert a puzzle Future<void> insertPuzzle(Puzzle puzzle) => _localStoragePuzzlesApi.insertPuzzle(puzzle); /// Update a puzzle Future<void> updatePuzzle(Puzzle puzzle) => _localStoragePuzzlesApi.updatePuzzle(puzzle); /// Delete a puzzle Future<void> deletePuzzle(Puzzle puzzle) => _localStoragePuzzlesApi.deletePuzzle(puzzle); /// Get all puzzles Future<List<Puzzle>?>? getAllPuzzles() => _localStoragePuzzlesApi.getAllPuzzles(); /// stream all puzzles Stream<List<Puzzle>?>? streamAllPuzzles() => _localStoragePuzzlesApi.streamAllPuzzles(); /// Get a puzzle by id Future<Puzzle?>? getPuzzleById(int id) => _localStoragePuzzlesApi.getPuzzleById(id); ///======== PUZZLEITEMS============= /// // /// Insert a puzzleItem Future<void> insertPuzzleItem(PuzzleItem puzzleItem) => _localStoragePuzzlesApi.insertPuzzleItem(puzzleItem); /// Update a puzzleItem Future<void> updatePuzzleItem(PuzzleItem puzzleItem) => _localStoragePuzzlesApi.updatePuzzleItem(puzzleItem); /// Delete a puzzleItem given [puzzleItem] Future<void> deletePuzzleItem(PuzzleItem puzzleItem) => _localStoragePuzzlesApi.deletePuzzleItem(puzzleItem); /// Get all puzzleItem given puzzle [id] Future<List<PuzzleItem>?>? getAllPuzzlesItems(int id) => _localStoragePuzzlesApi.getAllPuzzlesItems(id); /// stream all puzzleItems given puzzle[id] Stream<List<PuzzleItem>?>? streamAllPuzzlesItems(int id) => _localStoragePuzzlesApi.streamAllPuzzlesItems(id); /// Get a puzzleItem by id Future<PuzzleItem?>? getPuzzleItemById(int id) => _localStoragePuzzlesApi.getPuzzleItemById(id); }
0
mirrored_repositories/puzzles/packages/puzzles_repository/test
mirrored_repositories/puzzles/packages/puzzles_repository/test/src/puzzles_repository_test.dart
// ignore_for_file: flutter_style_todos import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:puzzles_api/puzzles_api.dart'; import 'package:puzzles_repository/puzzles_repository.dart'; final puzzleItems = [puzzleItem]; final puzzles = [puzzle]; final puzzle = Puzzle( id: 1, createdAt: DateTime.november.toString(), completedAt: DateTime.november.toString(), puzzleType: 'Type 1', ); final puzzleItem = PuzzleItem( id: 1, puzzleId: 1, puzzleType: 'Type 1', createdAt: DateTime.november.toString(), completedAt: DateTime.november.toString(), choices: const ['Item 1'], ); class MockPuzzlesRepository extends Mock implements PuzzlesRepository { @override Future<void> deletePuzzle(Puzzle puzzle) { return Future.value(); } @override Future<void> deletePuzzleItem(PuzzleItem puzzleItem) { return Future.value(); } @override Future<List<Puzzle>?>? getAllPuzzles() { return Future.value([puzzle]); } @override Future<List<PuzzleItem>?>? getAllPuzzlesItems(int id) { return Future.value([puzzleItem]); } @override Future<Puzzle?>? getPuzzleById(int id) { return Future.value(puzzle); } @override Future<PuzzleItem?>? getPuzzleItemById(int id) { return Future.value(puzzleItem); } @override Future<void> insertPuzzle(Puzzle puzzle) { return Future.value(); } @override Future<void> insertPuzzleItem(PuzzleItem puzzleItem) { return Future.value(); } @override Stream<List<Puzzle>?>? streamAllPuzzles() { return Stream.value([puzzle]); } @override Stream<List<PuzzleItem>?>? streamAllPuzzlesItems(int id) { return Stream.value([puzzleItem]); } @override Future<void> updatePuzzle(Puzzle puzzle) { return Future.value(); } @override Future<void> updatePuzzleItem(PuzzleItem puzzleItem) { return Future.value(); } } // ignore: todo // TODO(question): tests /// can Simply testing [can be instantiated] do as functions are tested? void main() { TestWidgetsFlutterBinding.ensureInitialized(); late MockPuzzlesRepository puzzlesRepository; setUp(() { puzzlesRepository = MockPuzzlesRepository(); }); group('PuzzlesRepository', () { test('can be instantiated', () { // Arrange // Set up any necessary data or dependencies for the test // Act final repository = MockPuzzlesRepository(); // Assert expect(repository, isA<MockPuzzlesRepository>()); }); test('getAllPuzzles returns a list of puzzles', () async { await puzzlesRepository.insertPuzzle(puzzle); // Act final puzzles = await puzzlesRepository.getAllPuzzles(); // Assert expect(puzzles, isA<List<Puzzle>>()); expect(puzzles?.length, 1); expect(puzzles?[0], equals(puzzle)); }); test('getAllPuzzlesItems returns a list of puzzle items', () async { // Insert await puzzlesRepository.insertPuzzleItem(puzzleItem); // Act final puzzleItems = await puzzlesRepository.getAllPuzzlesItems(1); // Assert expect(puzzleItems, isA<List<PuzzleItem>>()); expect(puzzleItems?.length, 1); expect(puzzleItems?[0], equals(puzzleItem)); }); test('Test updatePuzzle', () async { await puzzlesRepository.insertPuzzle(puzzle); await puzzlesRepository.updatePuzzle(puzzle.copyWith(createdAt: '11')); // ignore: inference_failure_on_instance_creation await Future.delayed(const Duration(seconds: 3)); // Verify that the updatePuzzle method is called with the correct // argument final result = await puzzlesRepository.getPuzzleById(1); expect(result, equals(puzzle.copyWith(createdAt: '11'))); }); test('Test deletePuzzle', () async { await puzzlesRepository.insertPuzzle(puzzle); await puzzlesRepository.deletePuzzle(puzzle); // ignore: todo // TODO(assert): assert on delete }); test('Test getAllPuzzles', () async { await puzzlesRepository.insertPuzzle(puzzle); final result = await puzzlesRepository.getAllPuzzles(); // Verify that the result matches the expected puzzles expect(result, puzzles); }); test('Test streamAllPuzzles', () async { await puzzlesRepository.insertPuzzle(puzzle); final result = puzzlesRepository.streamAllPuzzles(); // Verify that the streamAllPuzzles method is called with the correct // argument // Verify that the result matches the expected puzzles expect(result, emits(puzzles)); }); test('Test insertPuzzleItem', () async { await puzzlesRepository.insertPuzzleItem(puzzleItem); // ignore: inference_failure_on_instance_creation // Verify that the insertPuzzleItem method is called with the correct // argument final result = await puzzlesRepository.getPuzzleItemById(1); expect(puzzleItem, equals(result)); }); test('Test updatePuzzleItem', () async { await puzzlesRepository.insertPuzzleItem(puzzleItem); await puzzlesRepository .updatePuzzleItem(puzzleItem.copyWith(createdAt: '11')); // Verify that the updatePuzzleItem method is called with the correct // argument final result = await puzzlesRepository.getPuzzleItemById(1); expect(puzzleItem.copyWith(createdAt: '11'), equals(result)); }); // test('Test deletePuzzleItem', () async { // await puzzlesRepository.insertPuzzleItem(puzzleItem); // await puzzlesRepository.deletePuzzleItem(puzzleItem); // // Verify that the updatePuzzleItem method is called with the correct // // argument // final result = await puzzlesRepository.getPuzzleItemById(1); // // expect(result, null); // }); test('Test getAllPuzzlesItems', () async { const id = 1; await puzzlesRepository.insertPuzzleItem(puzzleItem); final result = await puzzlesRepository.getAllPuzzlesItems(id); // Verify that the result matches the expected puzzleItems expect(result, puzzleItems); }); test('Test streamAllPuzzlesItems', () async { const id = 1; await puzzlesRepository.insertPuzzleItem(puzzleItem); final result = puzzlesRepository.streamAllPuzzlesItems(id); // Verify that the streamAllPuzzlesItems method is called with the correct // argument // Verify that the result matches the expected puzzleItems expect(result, emits(puzzleItems)); }); }); }
0
mirrored_repositories/puzzles/packages/words_generator
mirrored_repositories/puzzles/packages/words_generator/lib/words_generator.dart
/// An API that handles words generation related requests. library words_generator; export 'src/words_generator.dart';
0
mirrored_repositories/puzzles/packages/words_generator/lib
mirrored_repositories/puzzles/packages/words_generator/lib/src/words_generator.dart
import 'dart:math'; /// {@template words_generator} /// An API that handles words generation related requests. /// {@endtemplate} class WordsGenerator { /// {@macro words_generator} const WordsGenerator(); /// [randomWordsGenerator] generates random [String]s of letters(words) /// Using [Random] if even make words similar else switcharoo one letter /// /// [length] is used to count no of characters with 4 being min Future<List<String>> randomWordsGenerator(int? length) async { assert(length == null || length > 4, 'Length must be greater than 4'); final random = Random(); if (random.nextInt(100).isEven) { final word1 = generateWord(length); return [word1, word1]; } else { final word1 = generateWord(length); final word2 = generateSimilarWord(word1); return [word1, word2]; } } /// Used to generate first Word /// if [length] generate upto 4 String generateWord(int? length) { final random = Random(); const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; var word = ''; for (var i = 0; i < (length ?? 4); i++) { final letter = alphabet[random.nextInt(alphabet.length)]; // ignore: use_string_buffers word += letter; } return word; } /// USed to generate 2nd word from first word String generateSimilarWord(String originalWord) { final random = Random(); const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; var word = originalWord; final index = random.nextInt(word.length - 2) + 1; final oldLetter = word[index]; var newLetter = oldLetter; while (newLetter == oldLetter) { newLetter = alphabet[random.nextInt(alphabet.length)]; } // ignore: join_return_with_assignment word = word.substring(0, index) + newLetter + word.substring(index + 1); return word; } }
0
mirrored_repositories/puzzles/packages/words_generator/test
mirrored_repositories/puzzles/packages/words_generator/test/src/words_generator_test.dart
// ignore_for_file: prefer_const_constructors import 'package:test/test.dart'; import 'package:words_generator/words_generator.dart'; void main() { // Test the generateWord method test('Test generateWord', () { final wordsGenerator = WordsGenerator(); // Test case 1: Generate word with length 7 final word1 = wordsGenerator.generateWord(7); expect(word1, isA<String>()); expect(word1.length, 7); // Test case 2: Generate word with length 7 final word2 = wordsGenerator.generateSimilarWord(word1); expect(word2, isA<String>()); expect(word2.length, 7); }); // Test the generateSimilarWord method test('Test randomWordsGenerator', () async { final wordsGenerator = WordsGenerator(); // Test case 1: Generate similar word for 'WORD' final words = await wordsGenerator.randomWordsGenerator(5); expect(words, isA<List<String>>()); // Test case 2: Check the words are of the given length expect(words[0].length, equals(words[1].length)); }); }
0
mirrored_repositories/puzzles/packages/puzzles_api
mirrored_repositories/puzzles/packages/puzzles_api/lib/puzzles_api.dart
/// The interface and models for an API providing access to puzzles and /// puzzle items. library puzzles_api; export 'src/models/models.dart'; export 'src/puzzles_api.dart';
0
mirrored_repositories/puzzles/packages/puzzles_api/lib
mirrored_repositories/puzzles/packages/puzzles_api/lib/src/puzzles_api.dart
import 'package:puzzles_api/src/models/models.dart'; /// {@template puzzles_api} /// The interface and models for an API providing access to puzzles and puzzle /// items. /// {@endtemplate} abstract class PuzzlesApi { /// {@macro puzzles_api} const PuzzlesApi(); /// Provides a [Stream] of all puzzles. Stream<List<Puzzle>>? streamPuzzles(); /// Provides a [Stream] of all puzzleItems. Stream<List<PuzzleItem>>? streamPuzzleItems(int puzzleId); /// Saves a [puzzle]. /// /// If a [puzzle] with the same id already exists, it will be replaced. Future<void> savePuzzle(Puzzle puzzle); /// Saves a [puzzleItem]. /// /// If a [puzzleItem] with the same id already exists, it will be replaced. Future<void> savePuzzleItem(PuzzleItem puzzleItem); /// Updates a [puzzle]. /// /// If a [puzzle] with the same id already exists, it will be replaced. Future<void> updatePuzzle(Puzzle puzzle); /// Updates a [puzzleItem]. /// /// If a [puzzleItem] with the same id already exists, it will be replaced. Future<void> updatePuzzleItem(PuzzleItem puzzleItem); /// Deletes the `puzzle` with the given id. /// /// Also deletes all related puzzle items /// /// If no `puzzle` with the given id exists, a [PuzzleNotFoundException] error /// isthrown. Future<void> deletePuzzle(int id); /// Deletes the `puzzleItem` with the given id. /// /// If no `puzzleItem` with the given id exists, a /// [PuzzleItemNotFoundException] error is /// thrown. Future<void> deletePuzzleItem(int id); /// Gets the `puzzle` with the given id. /// /// /// If no `puzzle` with the given id exists, a [PuzzleNotFoundException] error /// isthrown. Future<void> getPuzzleById(int id); /// Get the `puzzleItem` with the given id. /// /// If no `puzzleItem` with the given id exists, a /// [PuzzleItemNotFoundException] error is /// thrown. Future<void> getPPuzzleItemById(int id); } /// Error thrown when a [Puzzle] with a given id is not found. class PuzzleNotFoundException implements Exception {} /// Error thrown when a [PuzzleItem] with a given id is not found. class PuzzleItemNotFoundException implements Exception {}
0
mirrored_repositories/puzzles/packages/puzzles_api/lib/src
mirrored_repositories/puzzles/packages/puzzles_api/lib/src/models/json_map.dart
/// The type definition for a JSON-serializable [Map]. typedef JsonMap = Map<String, dynamic>;
0
mirrored_repositories/puzzles/packages/puzzles_api/lib/src
mirrored_repositories/puzzles/packages/puzzles_api/lib/src/models/models.dart
export 'puzzle/puzzle.dart'; export 'puzzle_items/puzzle_item.dart';
0
mirrored_repositories/puzzles/packages/puzzles_api/lib/src/models
mirrored_repositories/puzzles/packages/puzzles_api/lib/src/models/puzzle_items/puzzle_item.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'puzzle_item.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** PuzzleItem _$PuzzleItemFromJson(Map<String, dynamic> json) => PuzzleItem( id: json['id'] as int?, puzzleId: json['puzzle_id'] as int?, choices: (json['choices'] as List<dynamic>?)?.map((e) => e as String).toList(), puzzleType: json['puzzle_type'] as String?, createdAt: json['created_at'] as String?, completedAt: json['completed_at'] as String?, ); Map<String, dynamic> _$PuzzleItemToJson(PuzzleItem instance) => <String, dynamic>{ 'id': instance.id, 'puzzle_id': instance.puzzleId, 'choices': instance.choices, 'puzzle_type': instance.puzzleType, 'created_at': instance.createdAt, 'completed_at': instance.completedAt, };
0
mirrored_repositories/puzzles/packages/puzzles_api/lib/src/models
mirrored_repositories/puzzles/packages/puzzles_api/lib/src/models/puzzle_items/puzzle_item.dart
import 'package:equatable/equatable.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:puzzles_api/src/models/json_map.dart'; part 'puzzle_item.g.dart'; /// {@template puzzle_item} /// A single `puzzle_item` . /// /// Contains a [puzzleType], [createdAt],[puzzleId] ,[choices ]and [completedAt] /// /// If an [id] is provided, it cannot be empty. If no [id] is provided, one /// will be generated. /// /// [PuzzleItem]s are immutable and can be copied using [copyWith], in addition /// to /// being serialized and deserialized using [toJson] and [fromJson] /// respectively. /// {@endtemplate} /// @JsonSerializable() class PuzzleItem extends Equatable { /// {@macro puzzle_item} const PuzzleItem({ this.id, this.puzzleId, this.choices, this.puzzleType, this.createdAt, this.completedAt, }); /// puzzle_item primary key final int? id; /// related puzzle primary key @JsonKey(name: 'puzzle_id') final int? puzzleId; /// choices generated final List<String>? choices; /// Puzzle type can be xoxoxo,lts,etc @JsonKey(name: 'puzzle_type') final String? puzzleType; /// When the puzzle was created @JsonKey(name: 'created_at') final String? createdAt; /// when the puzzle was completed @JsonKey(name: 'completed_at') final String? completedAt; /// Deserializes the given [JsonMap] into a [PuzzleItem]. static PuzzleItem fromJson(JsonMap json) => _$PuzzleItemFromJson(json); /// Converts this [PuzzleItem] into a [JsonMap]. Map<String, dynamic> toJson() => _$PuzzleItemToJson(this); /// {@macro puzzle_item} PuzzleItem copyWith({ int? id, int? puzzleId, List<String>? choices, String? puzzleType, String? createdAt, String? completedAt, }) { return PuzzleItem( id: id ?? this.id, puzzleId: puzzleId ?? this.puzzleId, choices: choices ?? this.choices, puzzleType: puzzleType ?? this.puzzleType, createdAt: createdAt ?? this.createdAt, completedAt: completedAt ?? this.completedAt, ); } @override List<Object?> get props { return [ id, puzzleId, choices, puzzleType, createdAt, completedAt, ]; } }
0
mirrored_repositories/puzzles/packages/puzzles_api/lib/src/models
mirrored_repositories/puzzles/packages/puzzles_api/lib/src/models/puzzle/puzzle.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'puzzle.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** Puzzle _$PuzzleFromJson(Map<String, dynamic> json) => Puzzle( id: json['id'] as int?, puzzleType: json['puzzle_type'] as String?, createdAt: json['created_at'] as String?, completedAt: json['completed_at'] as String?, ); Map<String, dynamic> _$PuzzleToJson(Puzzle instance) => <String, dynamic>{ 'id': instance.id, 'puzzle_type': instance.puzzleType, 'created_at': instance.createdAt, 'completed_at': instance.completedAt, };
0
mirrored_repositories/puzzles/packages/puzzles_api/lib/src/models
mirrored_repositories/puzzles/packages/puzzles_api/lib/src/models/puzzle/puzzle.dart
import 'package:equatable/equatable.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:puzzles_api/src/models/json_map.dart'; part 'puzzle.g.dart'; /// {@template puzzle} /// A single `puzzle` . /// /// Contains a [puzzleType], [createdAt] and [completedAt] /// /// If an [id] is provided, it cannot be empty. If no [id] is provided, one /// will be generated. /// /// [Puzzle]s are immutable and can be copied using [copyWith], in addition to /// being serialized and deserialized using [toJson] and [fromJson] /// respectively. /// {@endtemplate} /// @JsonSerializable() class Puzzle extends Equatable { /// {@macro puzzle} const Puzzle({ this.id, this.puzzleType, this.createdAt, this.completedAt, }); /// puzzle primary key final int? id; /// Puzzle type can be xoxoxo,lts,etc @JsonKey(name: 'puzzle_type') final String? puzzleType; /// When the puzzle was created @JsonKey(name: 'created_at') final String? createdAt; /// when the puzzle was completed @JsonKey(name: 'completed_at') final String? completedAt; /// Deserializes the given [JsonMap] into a [Puzzle]. static Puzzle fromJson(JsonMap json) => _$PuzzleFromJson(json); /// Converts this [Puzzle] into a [JsonMap]. Map<String, dynamic> toJson() => _$PuzzleToJson(this); /// {@macro puzzle} Puzzle copyWith({ int? id, String? puzzleType, String? createdAt, String? completedAt, }) { return Puzzle( id: id ?? this.id, puzzleType: puzzleType ?? this.puzzleType, createdAt: createdAt ?? this.createdAt, completedAt: completedAt ?? this.completedAt, ); } // ignore: override_on_non_overriding_member, // ignore: public_member_api_docs @override List<Object?> get props => [id, puzzleType, createdAt, completedAt]; }
0
mirrored_repositories/puzzles/packages/puzzles_api/test
mirrored_repositories/puzzles/packages/puzzles_api/test/src/puzzles_api_test.dart
// ignore_for_file: prefer_const_constructors import 'package:puzzles_api/puzzles_api.dart'; import 'package:test/test.dart'; class TestTodosApi extends PuzzlesApi { TestTodosApi() : super(); @override dynamic noSuchMethod(Invocation invocation) { return super.noSuchMethod(invocation); } } void main() { group('PuzzlesApi', () { test('can be constructed', () { expect(TestTodosApi.new, returnsNormally); }); }); }
0
mirrored_repositories/puzzles/packages/puzzles_api/test/src
mirrored_repositories/puzzles/packages/puzzles_api/test/src/models/puzzle_items.dart
import 'package:puzzles_api/puzzles_api.dart'; import 'package:test/test.dart'; void main() { group('Puzzle Item', () { PuzzleItem createSubject({ int? id = 1, int? puzzleId = 1, List<String>? choices = const ['choices', 'choices'], String? puzzleType = 'xoxoxx', String? createdAt = '2023/04/07', String? completedAt = '2023/04/07', }) { return PuzzleItem( id: id, puzzleId: puzzleId, puzzleType: puzzleType, createdAt: createdAt, choices: choices, completedAt: completedAt, ); } group('constructor', () { test('works correctly', () { expect( createSubject, returnsNormally, ); }); }); test('supports value equality', () { expect( createSubject(), equals(createSubject()), ); }); test('props are correct', () { expect( createSubject().props, equals([ 1, // id 1, //puzzleId ['choices', 'choices'], //choices 'xoxoxx', // puzzle_type '2023/04/07', // created_at '2023/04/07', // completed_at ]), ); }); group('copyWith', () { test('returns the same object if not arguments are provided', () { expect( createSubject().copyWith(), equals(createSubject()), ); }); test('retains the old value for every parameter if null is provided', () { expect( createSubject().copyWith(), equals(createSubject()), ); }); test('replaces every non-null parameter', () { expect( createSubject().copyWith( id: 2, puzzleType: 'puzzleType', createdAt: 'createdAt', completedAt: 'completedAt', ), equals( createSubject( id: 2, puzzleType: 'puzzleType', createdAt: 'createdAt', completedAt: 'completedAt', ), ), ); }); group('fromJson', () { test('works correctly', () { expect( PuzzleItem.fromJson(<String, dynamic>{ 'id': 1, 'puzzle_type': 'xoxoxx', 'choices': ['choices', 'choices'], 'puzzle_id': 1, 'created_at': '2023/04/07', 'completed_at': '2023/04/07', }), equals(createSubject()), ); }); }); group('toJson', () { test('works correctly', () { expect( createSubject().toJson(), equals(<String, dynamic>{ 'id': 1, 'puzzle_type': 'xoxoxx', 'choices': ['choices', 'choices'], 'puzzle_id': 1, 'created_at': '2023/04/07', 'completed_at': '2023/04/07', }), ); }); }); }); }); }
0
mirrored_repositories/puzzles/packages/puzzles_api/test/src
mirrored_repositories/puzzles/packages/puzzles_api/test/src/models/puzzle.dart
import 'package:puzzles_api/puzzles_api.dart'; import 'package:test/test.dart'; void main() { group('Puzzle', () { Puzzle createSubject({ int? id = 1, String? puzzleType = 'xoxoxx', String? createdAt = '2023/04/07', String? completedAt = '2023/04/07', }) { return Puzzle( id: id, puzzleType: puzzleType, createdAt: createdAt, completedAt: completedAt, ); } group('constructor', () { test('works correctly', () { expect( createSubject, returnsNormally, ); }); // test('throws AssertionError when id is empty', () { // expect( // createSubject(id: null), // throwsA(isA<AssertionError>()), // ); // }); }); test('supports value equality', () { expect( createSubject(), equals(createSubject()), ); }); test('props are correct', () { expect( createSubject().props, equals([ 1, // id 'xoxoxx', // puzzle_type '2023/04/07', // created_at '2023/04/07', // completed_at ]), ); }); group('copyWith', () { test('returns the same object if not arguments are provided', () { expect( createSubject().copyWith(), equals(createSubject()), ); }); test('retains the old value for every parameter if null is provided', () { expect( createSubject().copyWith(), equals(createSubject()), ); }); test('replaces every non-null parameter', () { expect( createSubject().copyWith( id: 2, puzzleType: 'puzzleType', createdAt: 'createdAt', completedAt: 'completedAt', ), equals( createSubject( id: 2, puzzleType: 'puzzleType', createdAt: 'createdAt', completedAt: 'completedAt', ), ), ); }); group('fromJson', () { test('works correctly', () { expect( Puzzle.fromJson(<String, dynamic>{ 'id': 1, 'puzzle_type': 'xoxoxx', 'created_at': '2023/04/07', 'completed_at': '2023/04/07', }), equals(createSubject()), ); }); }); group('toJson', () { test('works correctly', () { expect( createSubject().toJson(), equals(<String, dynamic>{ 'id': 1, 'puzzle_type': 'xoxoxx', 'created_at': '2023/04/07', 'completed_at': '2023/04/07', }), ); }); }); }); }); }
0
mirrored_repositories/puzzles/packages/xoxo_repository
mirrored_repositories/puzzles/packages/xoxo_repository/lib/xoxo_repository.dart
/// A Repository that handles xoxo generation related functions. library xoxo_repository; export 'src/xoxo_repository.dart';
0
mirrored_repositories/puzzles/packages/xoxo_repository/lib
mirrored_repositories/puzzles/packages/xoxo_repository/lib/src/xoxo_repository.dart
import 'package:xoxo_generator/xoxo_generator.dart'; /// {@template xoxo_repository} /// A Repository that handles xoxo generation related functions. /// {@endtemplate} class XoxoRepository { /// {@macro xoxo_repository} const XoxoRepository({required XoxoGenerator xoxoGenerator}) : _xoxoGenerator = xoxoGenerator; final XoxoGenerator _xoxoGenerator; /// {@macro xoxo_randomXOXOGenerator} Future<List<String>> randomXOXOGenerator(int? length) => _xoxoGenerator.randomXOXOGenerator(length); }
0
mirrored_repositories/puzzles/packages/xoxo_repository/test
mirrored_repositories/puzzles/packages/xoxo_repository/test/src/xoxo_repository_test.dart
// ignore_for_file: prefer_const_constructors import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; import 'package:xoxo_generator/xoxo_generator.dart'; import 'package:xoxo_repository/xoxo_repository.dart'; void main() { group('XoxoRepository', () { final xoxoGenerator = MockXoxoGenerator(); test('can be instantiated', () { expect(XoxoRepository(xoxoGenerator: xoxoGenerator), isNotNull); }); test('Can generate random xoxo', () async { final xoxoRepository = XoxoRepository(xoxoGenerator: xoxoGenerator); final result = await xoxoRepository.randomXOXOGenerator(5); // Verify the result expect(result, isA<List<String>>()); expect(result.length, equals(2)); expect(result[0], equals('xoxox')); expect(result[1], equals('xoxox')); }); }); } class MockXoxoGenerator extends Mock implements XoxoGenerator { @override Future<List<String>> randomXOXOGenerator(int? length) { return Future.value(['xoxox', 'xoxox']); } }
0
mirrored_repositories/puzzles/packages/words_generator_repository
mirrored_repositories/puzzles/packages/words_generator_repository/lib/words_generator_repository.dart
/// A repository that handles words generation related requests. library words_generator_repository; export 'src/words_generator_repository.dart';
0
mirrored_repositories/puzzles/packages/words_generator_repository/lib
mirrored_repositories/puzzles/packages/words_generator_repository/lib/src/words_generator_repository.dart
import 'package:words_generator/words_generator.dart'; /// {@template words_generator_repository} /// A repository that handles words generation related requests. /// {@endtemplate} class WordsGeneratorRepository { /// {@macro words_generator_repository} const WordsGeneratorRepository({required WordsGenerator wordsGenerator}) : _wordsGenerator = wordsGenerator; final WordsGenerator _wordsGenerator; /// [randomWordsGenerator] generates random [String]s of letters(words) // ignore: comment_references /// Using [Random] if even make words similar else switcharoo one letter /// /// [length] is used to count no of characters with 4 being min Future<List<String>> randomWordsGenerator(int? length) => _wordsGenerator.randomWordsGenerator(length); }
0
mirrored_repositories/puzzles/packages/words_generator_repository/test
mirrored_repositories/puzzles/packages/words_generator_repository/test/src/words_generator_repository_test.dart
// ignore_for_file: prefer_const_constructors import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; import 'package:words_generator/words_generator.dart'; import 'package:words_generator_repository/words_generator_repository.dart'; void main() async { // Test the randomWordsGenerator method in WordsGeneratorRepository test('Test randomWordsGenerator in WordsGeneratorRepository', () async { // Create a mock instance of WordsGenerator final mockWordsGenerator = MockWordsGenerator(); final wordsGeneratorRepository = WordsGeneratorRepository(wordsGenerator: mockWordsGenerator); // Call the randomWordsGenerator method in WordsGeneratorRepository final result = await wordsGeneratorRepository.randomWordsGenerator(5); // Verify that the randomWordsGenerator method in WordsGeneratorRepository // called the same method in WordsGenerator // Verify the result expect(result, isA<List<String>>()); expect(result.length, equals(2)); expect(result[0], equals('word1')); expect(result[1], equals('word2')); }); } // Define a mock class for WordsGenerator class MockWordsGenerator extends Mock implements WordsGenerator { @override Future<List<String>> randomWordsGenerator(int? length) { return Future.value(['word1', 'word2']); } }
0
mirrored_repositories/puzzles/packages/local_storage_puzzles_api
mirrored_repositories/puzzles/packages/local_storage_puzzles_api/lib/local_storage_puzzles_api.dart
/// A Flutter implementation of the PuzzlesApi that uses local storage. library local_storage_puzzles_api; export 'src/database/db.dart' show openConnection; export 'src/local_storage_puzzles_api.dart';
0
mirrored_repositories/puzzles/packages/local_storage_puzzles_api/lib
mirrored_repositories/puzzles/packages/local_storage_puzzles_api/lib/src/local_storage_puzzles_api.dart
import 'package:local_storage_puzzles_api/src/database/daos/puzzle_items_dao.dart'; import 'package:local_storage_puzzles_api/src/database/daos/puzzles_dao.dart'; import 'package:puzzles_api/puzzles_api.dart'; /// {@template local_storage_puzzles_api} /// A Flutter implementation of the PuzzlesApi that uses local storage. /// {@endtemplate} class LocalStoragePuzzlesApi { /// {@macro local_storage_puzzles_api} const LocalStoragePuzzlesApi({ required PuzzlesDao puzzlesDao, required PuzzlesItemDao puzzlesItemDao, }) : _puzzlesDao = puzzlesDao, _puzzlesItemDao = puzzlesItemDao; final PuzzlesDao _puzzlesDao; final PuzzlesItemDao _puzzlesItemDao; /// Insert a puzzle Future<void> insertPuzzle(Puzzle puzzle) => _puzzlesDao.insertPuzzle(puzzle); /// Update a puzzle Future<void> updatePuzzle(Puzzle puzzle) => _puzzlesDao.updatePuzzle(puzzle); /// Delete a puzzle Future<void> deletePuzzle(Puzzle puzzle) => _puzzlesDao.deletePuzzle(puzzle); /// Get all puzzles Future<List<Puzzle>?>? getAllPuzzles() => _puzzlesDao.getAllPuzzles(); /// stream all puzzles Stream<List<Puzzle>?>? streamAllPuzzles() => _puzzlesDao.streamAllPuzzles(); /// Get a puzzle by id Future<Puzzle?>? getPuzzleById(int id) => _puzzlesDao.getPuzzleById(id); ///======== PUZZLEITEMS============= /// // /// Insert a puzzleItem Future<void> insertPuzzleItem(PuzzleItem puzzleItem) => _puzzlesItemDao.insertPuzzleItem(puzzleItem); /// Update a puzzleItem Future<void> updatePuzzleItem(PuzzleItem puzzleItem) => _puzzlesItemDao.updatePuzzleItem(puzzleItem); /// Delete a puzzleItem given [puzzleItem] Future<void> deletePuzzleItem(PuzzleItem puzzleItem) => _puzzlesItemDao.deletePuzzleItem(puzzleItem); /// Get all puzzleItem given puzzle [id] Future<List<PuzzleItem>?>? getAllPuzzlesItems(int id) => _puzzlesItemDao.getAllPuzzlesItems(id); /// stream all puzzleItems given puzzle[id] Stream<List<PuzzleItem>?>? streamAllPuzzlesItems(int id) => _puzzlesItemDao.streamAllPuzzlesItems(id); /// Get a puzzleItem by id Future<PuzzleItem?>? getPuzzleItemById(int id) => _puzzlesItemDao.getPuzzleItemById(id); }
0
mirrored_repositories/puzzles/packages/local_storage_puzzles_api/lib/src
mirrored_repositories/puzzles/packages/local_storage_puzzles_api/lib/src/database/db.dart
import 'dart:io'; import 'package:drift/drift.dart'; import 'package:drift/native.dart'; import 'package:local_storage_puzzles_api/src/database/daos/puzzle_items_dao.dart'; import 'package:local_storage_puzzles_api/src/database/daos/puzzles_dao.dart'; import 'package:local_storage_puzzles_api/src/database/model_converters.dart'; import 'package:local_storage_puzzles_api/src/database/tables.dart'; import 'package:path/path.dart' as p; import 'package:path_provider/path_provider.dart'; part 'db.g.dart'; /// Init db connection LazyDatabase openConnection() { // the LazyDatabase util lets us find the right location for the file async. return LazyDatabase(() async { // put the database file, called db.sqlite here, into the documents folder // for your app. final dbFolder = await getApplicationSupportDirectory(); final file = File(p.join(dbFolder.path, 'puzzles/db.sqlite')); return NativeDatabase(file); }); } @DriftDatabase( daos: [PuzzlesDao, PuzzlesItemDao], tables: [PuzzlesItemTable, PuzzlesTable], ) /// Our App database class MyDatabase extends _$MyDatabase { /// Our App database MyDatabase([QueryExecutor? queryExecutor]) : super(queryExecutor ?? openConnection()); @override int get schemaVersion => 2; @override MigrationStrategy get migration => MigrationStrategy( onCreate: (m) { return m.createAll(); }, onUpgrade: (Migrator m, int from, int to) async {}, ); }
0
mirrored_repositories/puzzles/packages/local_storage_puzzles_api/lib/src
mirrored_repositories/puzzles/packages/local_storage_puzzles_api/lib/src/database/tables.dart
// Puzzles Table // ignore_for_file: public_member_api_docs import 'package:drift/drift.dart'; import 'package:local_storage_puzzles_api/src/database/model_converters.dart'; /// {@macro puzzle} class PuzzlesTable extends Table { IntColumn get id => integer().nullable().autoIncrement()(); @JsonKey('created_at') TextColumn get createdAt => text().nullable()(); @JsonKey('completed_at') TextColumn get completedAt => text().nullable()(); @JsonKey('puzzle_type') TextColumn get puzzleType => text().nullable()(); } // PuzzlesItem Table /// {@macro puzzle_item} class PuzzlesItemTable extends Table { IntColumn get id => integer().nullable().autoIncrement()(); @JsonKey('created_at') TextColumn get createdAt => text().nullable()(); @JsonKey('completed_at') TextColumn get completedAt => text().nullable()(); @JsonKey('puzzle_type') TextColumn get puzzleType => text().nullable()(); TextColumn get choices => text().map(const ListStringConverter()).nullable()(); @JsonKey('puzzle_id') IntColumn get puzzleId => integer().nullable()(); }
0
mirrored_repositories/puzzles/packages/local_storage_puzzles_api/lib/src
mirrored_repositories/puzzles/packages/local_storage_puzzles_api/lib/src/database/db.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'db.dart'; // ignore_for_file: type=lint class $PuzzlesItemTableTable extends PuzzlesItemTable with TableInfo<$PuzzlesItemTableTable, PuzzlesItemTableData> { @override final GeneratedDatabase attachedDatabase; final String? _alias; $PuzzlesItemTableTable(this.attachedDatabase, [this._alias]); static const VerificationMeta _idMeta = const VerificationMeta('id'); @override late final GeneratedColumn<int> id = GeneratedColumn<int>( 'id', aliasedName, true, hasAutoIncrement: true, type: DriftSqlType.int, requiredDuringInsert: false, defaultConstraints: GeneratedColumn.constraintIsAlways('PRIMARY KEY AUTOINCREMENT')); static const VerificationMeta _createdAtMeta = const VerificationMeta('createdAt'); @override late final GeneratedColumn<String> createdAt = GeneratedColumn<String>( 'created_at', aliasedName, true, type: DriftSqlType.string, requiredDuringInsert: false); static const VerificationMeta _completedAtMeta = const VerificationMeta('completedAt'); @override late final GeneratedColumn<String> completedAt = GeneratedColumn<String>( 'completed_at', aliasedName, true, type: DriftSqlType.string, requiredDuringInsert: false); static const VerificationMeta _puzzleTypeMeta = const VerificationMeta('puzzleType'); @override late final GeneratedColumn<String> puzzleType = GeneratedColumn<String>( 'puzzle_type', aliasedName, true, type: DriftSqlType.string, requiredDuringInsert: false); static const VerificationMeta _choicesMeta = const VerificationMeta('choices'); @override late final GeneratedColumnWithTypeConverter<List<String>?, String> choices = GeneratedColumn<String>('choices', aliasedName, true, type: DriftSqlType.string, requiredDuringInsert: false) .withConverter<List<String>?>( $PuzzlesItemTableTable.$converterchoicesn); static const VerificationMeta _puzzleIdMeta = const VerificationMeta('puzzleId'); @override late final GeneratedColumn<int> puzzleId = GeneratedColumn<int>( 'puzzle_id', aliasedName, true, type: DriftSqlType.int, requiredDuringInsert: false); @override List<GeneratedColumn> get $columns => [id, createdAt, completedAt, puzzleType, choices, puzzleId]; @override String get aliasedName => _alias ?? 'puzzles_item_table'; @override String get actualTableName => 'puzzles_item_table'; @override VerificationContext validateIntegrity( Insertable<PuzzlesItemTableData> instance, {bool isInserting = false}) { final context = VerificationContext(); final data = instance.toColumns(true); if (data.containsKey('id')) { context.handle(_idMeta, id.isAcceptableOrUnknown(data['id']!, _idMeta)); } if (data.containsKey('created_at')) { context.handle(_createdAtMeta, createdAt.isAcceptableOrUnknown(data['created_at']!, _createdAtMeta)); } if (data.containsKey('completed_at')) { context.handle( _completedAtMeta, completedAt.isAcceptableOrUnknown( data['completed_at']!, _completedAtMeta)); } if (data.containsKey('puzzle_type')) { context.handle( _puzzleTypeMeta, puzzleType.isAcceptableOrUnknown( data['puzzle_type']!, _puzzleTypeMeta)); } context.handle(_choicesMeta, const VerificationResult.success()); if (data.containsKey('puzzle_id')) { context.handle(_puzzleIdMeta, puzzleId.isAcceptableOrUnknown(data['puzzle_id']!, _puzzleIdMeta)); } return context; } @override Set<GeneratedColumn> get $primaryKey => {id}; @override PuzzlesItemTableData map(Map<String, dynamic> data, {String? tablePrefix}) { final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; return PuzzlesItemTableData( id: attachedDatabase.typeMapping .read(DriftSqlType.int, data['${effectivePrefix}id']), createdAt: attachedDatabase.typeMapping .read(DriftSqlType.string, data['${effectivePrefix}created_at']), completedAt: attachedDatabase.typeMapping .read(DriftSqlType.string, data['${effectivePrefix}completed_at']), puzzleType: attachedDatabase.typeMapping .read(DriftSqlType.string, data['${effectivePrefix}puzzle_type']), choices: $PuzzlesItemTableTable.$converterchoicesn.fromSql( attachedDatabase.typeMapping .read(DriftSqlType.string, data['${effectivePrefix}choices'])), puzzleId: attachedDatabase.typeMapping .read(DriftSqlType.int, data['${effectivePrefix}puzzle_id']), ); } @override $PuzzlesItemTableTable createAlias(String alias) { return $PuzzlesItemTableTable(attachedDatabase, alias); } static TypeConverter<List<String>, String> $converterchoices = const ListStringConverter(); static TypeConverter<List<String>?, String?> $converterchoicesn = NullAwareTypeConverter.wrap($converterchoices); } class PuzzlesItemTableData extends DataClass implements Insertable<PuzzlesItemTableData> { final int? id; final String? createdAt; final String? completedAt; final String? puzzleType; final List<String>? choices; final int? puzzleId; const PuzzlesItemTableData( {this.id, this.createdAt, this.completedAt, this.puzzleType, this.choices, this.puzzleId}); @override Map<String, Expression> toColumns(bool nullToAbsent) { final map = <String, Expression>{}; if (!nullToAbsent || id != null) { map['id'] = Variable<int>(id); } if (!nullToAbsent || createdAt != null) { map['created_at'] = Variable<String>(createdAt); } if (!nullToAbsent || completedAt != null) { map['completed_at'] = Variable<String>(completedAt); } if (!nullToAbsent || puzzleType != null) { map['puzzle_type'] = Variable<String>(puzzleType); } if (!nullToAbsent || choices != null) { final converter = $PuzzlesItemTableTable.$converterchoicesn; map['choices'] = Variable<String>(converter.toSql(choices)); } if (!nullToAbsent || puzzleId != null) { map['puzzle_id'] = Variable<int>(puzzleId); } return map; } PuzzlesItemTableCompanion toCompanion(bool nullToAbsent) { return PuzzlesItemTableCompanion( id: id == null && nullToAbsent ? const Value.absent() : Value(id), createdAt: createdAt == null && nullToAbsent ? const Value.absent() : Value(createdAt), completedAt: completedAt == null && nullToAbsent ? const Value.absent() : Value(completedAt), puzzleType: puzzleType == null && nullToAbsent ? const Value.absent() : Value(puzzleType), choices: choices == null && nullToAbsent ? const Value.absent() : Value(choices), puzzleId: puzzleId == null && nullToAbsent ? const Value.absent() : Value(puzzleId), ); } factory PuzzlesItemTableData.fromJson(Map<String, dynamic> json, {ValueSerializer? serializer}) { serializer ??= driftRuntimeOptions.defaultSerializer; return PuzzlesItemTableData( id: serializer.fromJson<int?>(json['id']), createdAt: serializer.fromJson<String?>(json['created_at']), completedAt: serializer.fromJson<String?>(json['completed_at']), puzzleType: serializer.fromJson<String?>(json['puzzle_type']), choices: serializer.fromJson<List<String>?>(json['choices']), puzzleId: serializer.fromJson<int?>(json['puzzle_id']), ); } @override Map<String, dynamic> toJson({ValueSerializer? serializer}) { serializer ??= driftRuntimeOptions.defaultSerializer; return <String, dynamic>{ 'id': serializer.toJson<int?>(id), 'created_at': serializer.toJson<String?>(createdAt), 'completed_at': serializer.toJson<String?>(completedAt), 'puzzle_type': serializer.toJson<String?>(puzzleType), 'choices': serializer.toJson<List<String>?>(choices), 'puzzle_id': serializer.toJson<int?>(puzzleId), }; } PuzzlesItemTableData copyWith( {Value<int?> id = const Value.absent(), Value<String?> createdAt = const Value.absent(), Value<String?> completedAt = const Value.absent(), Value<String?> puzzleType = const Value.absent(), Value<List<String>?> choices = const Value.absent(), Value<int?> puzzleId = const Value.absent()}) => PuzzlesItemTableData( id: id.present ? id.value : this.id, createdAt: createdAt.present ? createdAt.value : this.createdAt, completedAt: completedAt.present ? completedAt.value : this.completedAt, puzzleType: puzzleType.present ? puzzleType.value : this.puzzleType, choices: choices.present ? choices.value : this.choices, puzzleId: puzzleId.present ? puzzleId.value : this.puzzleId, ); @override String toString() { return (StringBuffer('PuzzlesItemTableData(') ..write('id: $id, ') ..write('createdAt: $createdAt, ') ..write('completedAt: $completedAt, ') ..write('puzzleType: $puzzleType, ') ..write('choices: $choices, ') ..write('puzzleId: $puzzleId') ..write(')')) .toString(); } @override int get hashCode => Object.hash(id, createdAt, completedAt, puzzleType, choices, puzzleId); @override bool operator ==(Object other) => identical(this, other) || (other is PuzzlesItemTableData && other.id == this.id && other.createdAt == this.createdAt && other.completedAt == this.completedAt && other.puzzleType == this.puzzleType && other.choices == this.choices && other.puzzleId == this.puzzleId); } class PuzzlesItemTableCompanion extends UpdateCompanion<PuzzlesItemTableData> { final Value<int?> id; final Value<String?> createdAt; final Value<String?> completedAt; final Value<String?> puzzleType; final Value<List<String>?> choices; final Value<int?> puzzleId; const PuzzlesItemTableCompanion({ this.id = const Value.absent(), this.createdAt = const Value.absent(), this.completedAt = const Value.absent(), this.puzzleType = const Value.absent(), this.choices = const Value.absent(), this.puzzleId = const Value.absent(), }); PuzzlesItemTableCompanion.insert({ this.id = const Value.absent(), this.createdAt = const Value.absent(), this.completedAt = const Value.absent(), this.puzzleType = const Value.absent(), this.choices = const Value.absent(), this.puzzleId = const Value.absent(), }); static Insertable<PuzzlesItemTableData> custom({ Expression<int>? id, Expression<String>? createdAt, Expression<String>? completedAt, Expression<String>? puzzleType, Expression<String>? choices, Expression<int>? puzzleId, }) { return RawValuesInsertable({ if (id != null) 'id': id, if (createdAt != null) 'created_at': createdAt, if (completedAt != null) 'completed_at': completedAt, if (puzzleType != null) 'puzzle_type': puzzleType, if (choices != null) 'choices': choices, if (puzzleId != null) 'puzzle_id': puzzleId, }); } PuzzlesItemTableCompanion copyWith( {Value<int?>? id, Value<String?>? createdAt, Value<String?>? completedAt, Value<String?>? puzzleType, Value<List<String>?>? choices, Value<int?>? puzzleId}) { return PuzzlesItemTableCompanion( id: id ?? this.id, createdAt: createdAt ?? this.createdAt, completedAt: completedAt ?? this.completedAt, puzzleType: puzzleType ?? this.puzzleType, choices: choices ?? this.choices, puzzleId: puzzleId ?? this.puzzleId, ); } @override Map<String, Expression> toColumns(bool nullToAbsent) { final map = <String, Expression>{}; if (id.present) { map['id'] = Variable<int>(id.value); } if (createdAt.present) { map['created_at'] = Variable<String>(createdAt.value); } if (completedAt.present) { map['completed_at'] = Variable<String>(completedAt.value); } if (puzzleType.present) { map['puzzle_type'] = Variable<String>(puzzleType.value); } if (choices.present) { final converter = $PuzzlesItemTableTable.$converterchoicesn; map['choices'] = Variable<String>(converter.toSql(choices.value)); } if (puzzleId.present) { map['puzzle_id'] = Variable<int>(puzzleId.value); } return map; } @override String toString() { return (StringBuffer('PuzzlesItemTableCompanion(') ..write('id: $id, ') ..write('createdAt: $createdAt, ') ..write('completedAt: $completedAt, ') ..write('puzzleType: $puzzleType, ') ..write('choices: $choices, ') ..write('puzzleId: $puzzleId') ..write(')')) .toString(); } } class $PuzzlesTableTable extends PuzzlesTable with TableInfo<$PuzzlesTableTable, PuzzlesTableData> { @override final GeneratedDatabase attachedDatabase; final String? _alias; $PuzzlesTableTable(this.attachedDatabase, [this._alias]); static const VerificationMeta _idMeta = const VerificationMeta('id'); @override late final GeneratedColumn<int> id = GeneratedColumn<int>( 'id', aliasedName, true, hasAutoIncrement: true, type: DriftSqlType.int, requiredDuringInsert: false, defaultConstraints: GeneratedColumn.constraintIsAlways('PRIMARY KEY AUTOINCREMENT')); static const VerificationMeta _createdAtMeta = const VerificationMeta('createdAt'); @override late final GeneratedColumn<String> createdAt = GeneratedColumn<String>( 'created_at', aliasedName, true, type: DriftSqlType.string, requiredDuringInsert: false); static const VerificationMeta _completedAtMeta = const VerificationMeta('completedAt'); @override late final GeneratedColumn<String> completedAt = GeneratedColumn<String>( 'completed_at', aliasedName, true, type: DriftSqlType.string, requiredDuringInsert: false); static const VerificationMeta _puzzleTypeMeta = const VerificationMeta('puzzleType'); @override late final GeneratedColumn<String> puzzleType = GeneratedColumn<String>( 'puzzle_type', aliasedName, true, type: DriftSqlType.string, requiredDuringInsert: false); @override List<GeneratedColumn> get $columns => [id, createdAt, completedAt, puzzleType]; @override String get aliasedName => _alias ?? 'puzzles_table'; @override String get actualTableName => 'puzzles_table'; @override VerificationContext validateIntegrity(Insertable<PuzzlesTableData> instance, {bool isInserting = false}) { final context = VerificationContext(); final data = instance.toColumns(true); if (data.containsKey('id')) { context.handle(_idMeta, id.isAcceptableOrUnknown(data['id']!, _idMeta)); } if (data.containsKey('created_at')) { context.handle(_createdAtMeta, createdAt.isAcceptableOrUnknown(data['created_at']!, _createdAtMeta)); } if (data.containsKey('completed_at')) { context.handle( _completedAtMeta, completedAt.isAcceptableOrUnknown( data['completed_at']!, _completedAtMeta)); } if (data.containsKey('puzzle_type')) { context.handle( _puzzleTypeMeta, puzzleType.isAcceptableOrUnknown( data['puzzle_type']!, _puzzleTypeMeta)); } return context; } @override Set<GeneratedColumn> get $primaryKey => {id}; @override PuzzlesTableData map(Map<String, dynamic> data, {String? tablePrefix}) { final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; return PuzzlesTableData( id: attachedDatabase.typeMapping .read(DriftSqlType.int, data['${effectivePrefix}id']), createdAt: attachedDatabase.typeMapping .read(DriftSqlType.string, data['${effectivePrefix}created_at']), completedAt: attachedDatabase.typeMapping .read(DriftSqlType.string, data['${effectivePrefix}completed_at']), puzzleType: attachedDatabase.typeMapping .read(DriftSqlType.string, data['${effectivePrefix}puzzle_type']), ); } @override $PuzzlesTableTable createAlias(String alias) { return $PuzzlesTableTable(attachedDatabase, alias); } } class PuzzlesTableData extends DataClass implements Insertable<PuzzlesTableData> { final int? id; final String? createdAt; final String? completedAt; final String? puzzleType; const PuzzlesTableData( {this.id, this.createdAt, this.completedAt, this.puzzleType}); @override Map<String, Expression> toColumns(bool nullToAbsent) { final map = <String, Expression>{}; if (!nullToAbsent || id != null) { map['id'] = Variable<int>(id); } if (!nullToAbsent || createdAt != null) { map['created_at'] = Variable<String>(createdAt); } if (!nullToAbsent || completedAt != null) { map['completed_at'] = Variable<String>(completedAt); } if (!nullToAbsent || puzzleType != null) { map['puzzle_type'] = Variable<String>(puzzleType); } return map; } PuzzlesTableCompanion toCompanion(bool nullToAbsent) { return PuzzlesTableCompanion( id: id == null && nullToAbsent ? const Value.absent() : Value(id), createdAt: createdAt == null && nullToAbsent ? const Value.absent() : Value(createdAt), completedAt: completedAt == null && nullToAbsent ? const Value.absent() : Value(completedAt), puzzleType: puzzleType == null && nullToAbsent ? const Value.absent() : Value(puzzleType), ); } factory PuzzlesTableData.fromJson(Map<String, dynamic> json, {ValueSerializer? serializer}) { serializer ??= driftRuntimeOptions.defaultSerializer; return PuzzlesTableData( id: serializer.fromJson<int?>(json['id']), createdAt: serializer.fromJson<String?>(json['created_at']), completedAt: serializer.fromJson<String?>(json['completed_at']), puzzleType: serializer.fromJson<String?>(json['puzzle_type']), ); } @override Map<String, dynamic> toJson({ValueSerializer? serializer}) { serializer ??= driftRuntimeOptions.defaultSerializer; return <String, dynamic>{ 'id': serializer.toJson<int?>(id), 'created_at': serializer.toJson<String?>(createdAt), 'completed_at': serializer.toJson<String?>(completedAt), 'puzzle_type': serializer.toJson<String?>(puzzleType), }; } PuzzlesTableData copyWith( {Value<int?> id = const Value.absent(), Value<String?> createdAt = const Value.absent(), Value<String?> completedAt = const Value.absent(), Value<String?> puzzleType = const Value.absent()}) => PuzzlesTableData( id: id.present ? id.value : this.id, createdAt: createdAt.present ? createdAt.value : this.createdAt, completedAt: completedAt.present ? completedAt.value : this.completedAt, puzzleType: puzzleType.present ? puzzleType.value : this.puzzleType, ); @override String toString() { return (StringBuffer('PuzzlesTableData(') ..write('id: $id, ') ..write('createdAt: $createdAt, ') ..write('completedAt: $completedAt, ') ..write('puzzleType: $puzzleType') ..write(')')) .toString(); } @override int get hashCode => Object.hash(id, createdAt, completedAt, puzzleType); @override bool operator ==(Object other) => identical(this, other) || (other is PuzzlesTableData && other.id == this.id && other.createdAt == this.createdAt && other.completedAt == this.completedAt && other.puzzleType == this.puzzleType); } class PuzzlesTableCompanion extends UpdateCompanion<PuzzlesTableData> { final Value<int?> id; final Value<String?> createdAt; final Value<String?> completedAt; final Value<String?> puzzleType; const PuzzlesTableCompanion({ this.id = const Value.absent(), this.createdAt = const Value.absent(), this.completedAt = const Value.absent(), this.puzzleType = const Value.absent(), }); PuzzlesTableCompanion.insert({ this.id = const Value.absent(), this.createdAt = const Value.absent(), this.completedAt = const Value.absent(), this.puzzleType = const Value.absent(), }); static Insertable<PuzzlesTableData> custom({ Expression<int>? id, Expression<String>? createdAt, Expression<String>? completedAt, Expression<String>? puzzleType, }) { return RawValuesInsertable({ if (id != null) 'id': id, if (createdAt != null) 'created_at': createdAt, if (completedAt != null) 'completed_at': completedAt, if (puzzleType != null) 'puzzle_type': puzzleType, }); } PuzzlesTableCompanion copyWith( {Value<int?>? id, Value<String?>? createdAt, Value<String?>? completedAt, Value<String?>? puzzleType}) { return PuzzlesTableCompanion( id: id ?? this.id, createdAt: createdAt ?? this.createdAt, completedAt: completedAt ?? this.completedAt, puzzleType: puzzleType ?? this.puzzleType, ); } @override Map<String, Expression> toColumns(bool nullToAbsent) { final map = <String, Expression>{}; if (id.present) { map['id'] = Variable<int>(id.value); } if (createdAt.present) { map['created_at'] = Variable<String>(createdAt.value); } if (completedAt.present) { map['completed_at'] = Variable<String>(completedAt.value); } if (puzzleType.present) { map['puzzle_type'] = Variable<String>(puzzleType.value); } return map; } @override String toString() { return (StringBuffer('PuzzlesTableCompanion(') ..write('id: $id, ') ..write('createdAt: $createdAt, ') ..write('completedAt: $completedAt, ') ..write('puzzleType: $puzzleType') ..write(')')) .toString(); } } abstract class _$MyDatabase extends GeneratedDatabase { _$MyDatabase(QueryExecutor e) : super(e); late final $PuzzlesItemTableTable puzzlesItemTable = $PuzzlesItemTableTable(this); late final $PuzzlesTableTable puzzlesTable = $PuzzlesTableTable(this); late final PuzzlesDao puzzlesDao = PuzzlesDao(this as MyDatabase); late final PuzzlesItemDao puzzlesItemDao = PuzzlesItemDao(this as MyDatabase); @override Iterable<TableInfo<Table, Object?>> get allTables => allSchemaEntities.whereType<TableInfo<Table, Object?>>(); @override List<DatabaseSchemaEntity> get allSchemaEntities => [puzzlesItemTable, puzzlesTable]; }
0
mirrored_repositories/puzzles/packages/local_storage_puzzles_api/lib/src
mirrored_repositories/puzzles/packages/local_storage_puzzles_api/lib/src/database/model_converters.dart
import 'dart:convert'; import 'package:drift/drift.dart'; import 'package:puzzles_api/puzzles_api.dart'; /// {@template puzzles_converter} /// Convert [Puzzle] to a drift obj /// {@endtemplate} class PuzzleConverter extends TypeConverter<Puzzle, String> { /// {@macro puzzles_converter} Puzzle? mapToDart(String? fromDb) { return Puzzle.fromJson( json.decode(fromDb!) as Map<String, dynamic>, ); } /// {@macro puzzles_converter} String? mapToSql(Puzzle? value) { return json.encode(value?.toJson()); } /// {@macro puzzles_converter} @override Puzzle fromSql(String fromDb) { return Puzzle.fromJson( json.decode(fromDb) as Map<String, dynamic>, ); } /// {@macro puzzles_converter} @override String toSql(Puzzle value) { return json.encode(value.toJson()); } } /// {@template puzzles_items_converter} /// Convert [PuzzleItem] to a drift obj /// {@endtemplate} class PuzzlesItemsModelConverter extends TypeConverter<PuzzleItem, String> { /// {@macro puzzles_items_converter} PuzzleItem? mapToDart(String? fromDb) { return PuzzleItem.fromJson( json.decode(fromDb!) as Map<String, dynamic>, ); } /// {@macro puzzles_items_converter} String? mapToSql(PuzzleItem? value) { return json.encode(value?.toJson()); } /// {@macro puzzles_items_converter} @override PuzzleItem fromSql(String fromDb) { return PuzzleItem.fromJson( json.decode(fromDb) as Map<String, dynamic>, ); } /// {@macro puzzles_items_converter} @override String toSql(PuzzleItem value) { return json.encode(value.toJson()); } } /// Custom converter for List<String> class ListStringConverter extends TypeConverter<List<String>, String> { /// Custom converter for List<String> const ListStringConverter(); @override List<String> fromSql(String? fromDb) { if (fromDb == null) return []; final dynamic decoded = jsonDecode(fromDb); if (decoded is List<dynamic>) { return decoded.cast<String>(); } return []; } @override String toSql(List<String> value) { return jsonEncode(value); } }
0
mirrored_repositories/puzzles/packages/local_storage_puzzles_api/lib/src/database
mirrored_repositories/puzzles/packages/local_storage_puzzles_api/lib/src/database/daos/puzzle_items_dao.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'puzzle_items_dao.dart'; // ignore_for_file: type=lint mixin _$PuzzlesItemDaoMixin on DatabaseAccessor<MyDatabase> { $PuzzlesItemTableTable get puzzlesItemTable => attachedDatabase.puzzlesItemTable; }
0
mirrored_repositories/puzzles/packages/local_storage_puzzles_api/lib/src/database
mirrored_repositories/puzzles/packages/local_storage_puzzles_api/lib/src/database/daos/puzzles_dao.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'puzzles_dao.dart'; // ignore_for_file: type=lint mixin _$PuzzlesDaoMixin on DatabaseAccessor<MyDatabase> { $PuzzlesTableTable get puzzlesTable => attachedDatabase.puzzlesTable; }
0
mirrored_repositories/puzzles/packages/local_storage_puzzles_api/lib/src/database
mirrored_repositories/puzzles/packages/local_storage_puzzles_api/lib/src/database/daos/puzzles_dao.dart
import 'package:drift/drift.dart'; import 'package:local_storage_puzzles_api/src/database/db.dart'; import 'package:local_storage_puzzles_api/src/database/tables.dart'; import 'package:puzzles_api/puzzles_api.dart'; part 'puzzles_dao.g.dart'; @DriftAccessor(tables: [PuzzlesTable]) /// {@macro puzzles_api} class PuzzlesDao extends DatabaseAccessor<MyDatabase> with _$PuzzlesDaoMixin { /// {@macro puzzles_api} PuzzlesDao(super.db); /// Insert a PuzzlesModel object Future<void> insertPuzzle(Puzzle puzzle) => into(puzzlesTable) .insertOnConflictUpdate(PuzzlesTableData.fromJson(puzzle.toJson())); /// Update a Puzzle object Future<void> updatePuzzle(Puzzle puzzle) => update(puzzlesTable).replace(PuzzlesTableData.fromJson(puzzle.toJson())); /// Delete a Puzzle object Future<void> deletePuzzle(Puzzle puzzle) => delete(puzzlesTable).delete(PuzzlesTableData.fromJson(puzzle.toJson())); /// Get all Puzzle objects Future<List<Puzzle>>? getAllPuzzles() async { final puzzles = await select(puzzlesTable).get(); return puzzles.map((puzzle) => Puzzle.fromJson(puzzle.toJson())).toList(); } /// Provide a [Stream] of all puzzles Stream<List<Puzzle>> streamAllPuzzles() { return select(puzzlesTable).watch().map((puzzles) { return puzzles.map((puzzle) => Puzzle.fromJson(puzzle.toJson())).toList(); }); } /// Get a Puzzle object by id Future<Puzzle?>? getPuzzleById(int id) async { final puzzle = await (select(puzzlesTable)..where((p) => p.id.equals(id))).getSingle(); return Puzzle.fromJson(puzzle.toJson()); } }
0
mirrored_repositories/puzzles/packages/local_storage_puzzles_api/lib/src/database
mirrored_repositories/puzzles/packages/local_storage_puzzles_api/lib/src/database/daos/puzzle_items_dao.dart
import 'package:drift/drift.dart'; import 'package:local_storage_puzzles_api/src/database/db.dart'; import 'package:local_storage_puzzles_api/src/database/tables.dart'; import 'package:puzzles_api/puzzles_api.dart'; part 'puzzle_items_dao.g.dart'; @DriftAccessor(tables: [PuzzlesItemTable]) /// {@macro puzzles_api} class PuzzlesItemDao extends DatabaseAccessor<MyDatabase> with _$PuzzlesItemDaoMixin { /// {@macro puzzles_api} PuzzlesItemDao(super.db); /// Insert a PuzzleItem object Future<void> insertPuzzleItem(PuzzleItem puzzleItem) => into(puzzlesItemTable).insertOnConflictUpdate( PuzzlesItemTableData.fromJson(puzzleItem.toJson()), ); /// Update a PuzzleItem object Future<void> updatePuzzleItem(PuzzleItem puzzleItem) => update(puzzlesItemTable) .replace(PuzzlesItemTableData.fromJson(puzzleItem.toJson())); /// Delete a PuzzleItem object given [puzzleItem] Future<void> deletePuzzleItem(PuzzleItem puzzleItem) => delete(puzzlesItemTable) .delete(PuzzlesItemTableData.fromJson(puzzleItem.toJson())); /// Get all PuzzleItem objects given puzzle [id] Future<List<PuzzleItem>>? getAllPuzzlesItems(int id) async { final puzzleItems = await select(puzzlesItemTable).get(); return puzzleItems .map((puzzleItem) => PuzzleItem.fromJson(puzzleItem.toJson())) .toList(); } /// Provide a [Stream] of all PuzzleItems given puzzle [id] Stream<List<PuzzleItem>> streamAllPuzzlesItems(int id) { return select(puzzlesItemTable).watch().map((puzzleItems) { return puzzleItems .map((puzzleItem) => PuzzleItem.fromJson(puzzleItem.toJson())) .toList(); }); } /// Get a PuzzleItem object by id Future<PuzzleItem?>? getPuzzleItemById(int id) async { final puzzleItem = await (select(puzzlesItemTable) ..where((p) => p.id.equals(id))) .getSingleOrNull(); return puzzleItem != null ? PuzzleItem.fromJson(puzzleItem.toJson()) : null; } }
0
mirrored_repositories/puzzles/packages/local_storage_puzzles_api/test
mirrored_repositories/puzzles/packages/local_storage_puzzles_api/test/src/local_storage_puzzles_api_test.dart
// ignore_for_file: prefer_const_constructors, flutter_style_todos import 'package:flutter_test/flutter_test.dart'; import 'package:local_storage_puzzles_api/local_storage_puzzles_api.dart'; import 'package:mockito/mockito.dart'; import 'package:puzzles_api/puzzles_api.dart'; class MockLocalStoragePuzzlesApi extends Mock implements LocalStoragePuzzlesApi { @override Future<void> deletePuzzle(Puzzle puzzle) async { return Future.value(); } @override Future<void> deletePuzzleItem(PuzzleItem puzzleItem) { // Delete the puzzle item from a mock local storage return Future.value(); } @override Future<List<Puzzle>?>? getAllPuzzles() { // Fetch all puzzles from a mock local storage and return as a List<Puzzle> return Future.value([puzzle]); } @override Future<List<PuzzleItem>?>? getAllPuzzlesItems(int id) { // Fetch all puzzle items for the given puzzle ID from a mock local storage // and return as a List<PuzzleItem> return Future.value([puzzleItem]); } @override Future<Puzzle?>? getPuzzleById(int id) { // Fetch the puzzle with the given ID from a mock local storage and return //as a Puzzle object return Future.value(puzzle); } @override Future<PuzzleItem?>? getPuzzleItemById(int id) { // Fetch the puzzle item with the given ID from a mock local storage and //return as a PuzzleItem object return Future.value(puzzleItem); } @override Future<void> insertPuzzle(Puzzle puzzle) { // Insert the puzzle into a mock local storage return Future.value(); } @override Future<void> insertPuzzleItem(PuzzleItem puzzleItem) { // Insert the puzzle item into a mock local storage return Future.value(); } @override Stream<List<Puzzle>?>? streamAllPuzzles() { // Stream all puzzles from a mock local storage and return as a // Stream<List<Puzzle>> return Stream.value([]); } @override Stream<List<PuzzleItem>?>? streamAllPuzzlesItems(int id) { // Stream all puzzle items for the given puzzle ID from a mock local //storage and return as a Stream<List<PuzzleItem>> return Stream.value([puzzleItem]); } @override Future<void> updatePuzzle(Puzzle puzzle) { // Update the puzzle in a mock local storage return Future.value(); } @override Future<void> updatePuzzleItem(PuzzleItem puzzleItem) { // Update the puzzle item in a mock local storage return Future.value(); } } // Test data final puzzle = Puzzle( id: 1, createdAt: DateTime.november.toString(), completedAt: DateTime.november.toString(), puzzleType: 'Type 1', ); final puzzleItem = PuzzleItem( id: 1, puzzleId: 1, createdAt: DateTime.november.toString(), completedAt: DateTime.november.toString(), choices: const ['Item 1'], ); void main() { TestWidgetsFlutterBinding.ensureInitialized(); late MockLocalStoragePuzzlesApi localStoragePuzzlesApi; setUp(() { localStoragePuzzlesApi = MockLocalStoragePuzzlesApi(); }); // Tests for LocalStoragePuzzlesApi test('Insert puzzle', () async { await localStoragePuzzlesApi.insertPuzzle(puzzle); final retrievedPuzzle = await localStoragePuzzlesApi.getPuzzleById(1); expect(retrievedPuzzle, equals(puzzle)); }); test('Update puzzle', () async { await localStoragePuzzlesApi.insertPuzzle(puzzle); final updatedPuzzle = puzzle.copyWith(puzzleType: 'Type 1'); await localStoragePuzzlesApi.updatePuzzle(updatedPuzzle); final retrievedPuzzle = await localStoragePuzzlesApi.getPuzzleById(1); expect(retrievedPuzzle?.puzzleType, equals('Type 1')); }); // ignore: todo // TODO(deletePuzzle): test delete puzzle // test('Delete puzzle', () async { // // Insert the puzzle into local storage // await localStoragePuzzlesApi.insertPuzzle(puzzle); // // Delay to allow time for the puzzle to be inserted // await Future.delayed(Duration(seconds: 2)); // // Delete the puzzle from local storage // await localStoragePuzzlesApi.deletePuzzle(puzzle); // // Delay to allow time for the puzzle to be deleted // await Future.delayed(Duration(seconds: 2)); // // Get the retrieved puzzle // final retrievedPuzzle = await localStoragePuzzlesApi.getPuzzleById(1); // // Print the retrieved puzzle for debugging // print('retrievedPuzzle: $retrievedPuzzle'); // // Check if the retrieved puzzle is null // expect(retrievedPuzzle, isNull); // }); test('Get all puzzles', () async { await localStoragePuzzlesApi.insertPuzzle(puzzle); final puzzles = await localStoragePuzzlesApi.getAllPuzzles(); expect(puzzles?.length, equals(1)); expect(puzzles?.first, equals(puzzle)); }); test('Get all puzzles', () async { // Insert the puzzle into local storage await localStoragePuzzlesApi.insertPuzzle(puzzle); // Delay to allow time for the stream to emit the puzzle // ignore: inference_failure_on_instance_creation await Future.delayed(Duration(seconds: 2)); // Get the first emitted value from the stream final puzzles = await localStoragePuzzlesApi.getAllPuzzles(); // Print the puzzles for debugging // Check the length of the puzzles list expect(puzzles?.length, equals(1)); // Check if the first puzzle in the list matches the expected puzzle expect(puzzles?.first, equals(puzzle)); }); // Tests for PuzzleItem test('Insert puzzleItem', () async { await localStoragePuzzlesApi.insertPuzzle(puzzle); await localStoragePuzzlesApi.insertPuzzleItem(puzzleItem); final retrievedPuzzleItem = await localStoragePuzzlesApi.getPuzzleItemById(1); expect(retrievedPuzzleItem, equals(puzzleItem)); }); }
0
mirrored_repositories/puzzles/packages/local_storage_puzzles_api/test/src
mirrored_repositories/puzzles/packages/local_storage_puzzles_api/test/src/database/db_test.dart
import 'package:drift/drift.dart'; import 'package:drift/native.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:local_storage_puzzles_api/src/database/db.dart'; import 'package:puzzles_api/puzzles_api.dart'; final puzzle = Puzzle( id: 1, createdAt: DateTime.november.toString(), completedAt: DateTime.november.toString(), puzzleType: 'xoxo', ); final puzzleItem = PuzzleItem( id: 1, puzzleId: 1, puzzleType: 'xoxo', createdAt: DateTime.november.toString(), completedAt: DateTime.november.toString(), choices: const ['Item 1', 'item 2'], ); void main() { TestWidgetsFlutterBinding.ensureInitialized(); late MyDatabase database; // Set up the database before each test setUp(() async { final inMemory = DatabaseConnection(NativeDatabase.memory()); // Initialize the database with the temporary file database = MyDatabase(inMemory); }); // Close the database after each test tearDown(() async { await database.close(); }); // Test inserting a Puzzle into the database // Test database connection and initialization test('Test Database Connection and Initialization', () async { // Check if the database is connected final entry = await database.puzzlesTable .insertReturning(PuzzlesTableData.fromJson(puzzle.toJson())); final result = await (database.puzzlesTable.select() ..where((tbl) => tbl.id.equals(1))) .getSingle(); expect(result, equals(entry)); }); }
0
mirrored_repositories/puzzles/packages/local_storage_puzzles_api/test/src/database
mirrored_repositories/puzzles/packages/local_storage_puzzles_api/test/src/database/daos/puzzles_item_dao_test.dart
import 'package:drift/drift.dart'; import 'package:drift/native.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:local_storage_puzzles_api/src/database/daos/puzzle_items_dao.dart'; import 'package:local_storage_puzzles_api/src/database/db.dart'; import 'package:mockito/mockito.dart'; import 'package:puzzles_api/puzzles_api.dart'; class MockPuzzlesItemDao extends Mock implements PuzzlesItemDao { @override Future<void> insertPuzzleItem(PuzzleItem puzzleItem) => Future.value(); @override Future<void> updatePuzzleItem(PuzzleItem puzzleItem) => Future.value(); @override Future<void> deletePuzzleItem(PuzzleItem puzzleItem) => Future.value(); @override Future<List<PuzzleItem>>? getAllPuzzlesItems(int id) => Future.value(puzzleItems); @override Stream<List<PuzzleItem>> streamAllPuzzlesItems(int id) => Stream.value(puzzleItems); @override Future<PuzzleItem?>? getPuzzleItemById(int id) => Future.value(puzzleItem); } final puzzleItems = [puzzleItem]; final puzzleItem = PuzzleItem( id: 1, puzzleId: 1, puzzleType: 'xoxo', createdAt: DateTime.november.toString(), completedAt: DateTime.november.toString(), choices: const ['Item 1', 'item 2'], ); void main() { TestWidgetsFlutterBinding.ensureInitialized(); late MyDatabase mockDatabase; late PuzzlesItemDao puzzlesItemDao; group('PuzzlesItemDao tests', () { setUp(() { final inMemory = DatabaseConnection(NativeDatabase.memory()); // Initialize the database with the temporary file mockDatabase = MyDatabase(inMemory); puzzlesItemDao = PuzzlesItemDao(mockDatabase); }); // Close the database after each test tearDown(() async { await mockDatabase.close(); }); test('Test insertPuzzleItem', () async { await puzzlesItemDao.insertPuzzleItem(puzzleItem); // ignore: inference_failure_on_instance_creation // Verify that the insertPuzzleItem method is called with the correct // argument final result = await puzzlesItemDao.getPuzzleItemById(1); expect(puzzleItem, equals(result)); }); test('Test updatePuzzleItem', () async { await puzzlesItemDao.insertPuzzleItem(puzzleItem); await puzzlesItemDao .updatePuzzleItem(puzzleItem.copyWith(createdAt: '12')); // Verify that the updatePuzzleItem method is called with the correct // argument final result = await puzzlesItemDao.getPuzzleItemById(1); expect(puzzleItem.copyWith(createdAt: '12'), equals(result)); }); test('Test deletePuzzleItem', () async { await puzzlesItemDao.insertPuzzleItem(puzzleItem); await puzzlesItemDao.deletePuzzleItem(puzzleItem); // Verify that the updatePuzzleItem method is called with the correct // argument final result = await puzzlesItemDao.getPuzzleItemById(1); expect(result, null); }); test('Test getAllPuzzlesItems', () async { const id = 1; await puzzlesItemDao.insertPuzzleItem(puzzleItem); final result = await puzzlesItemDao.getAllPuzzlesItems(id); // Verify that the result matches the expected puzzleItems expect(result, puzzleItems); }); test('Test streamAllPuzzlesItems', () async { const id = 1; await puzzlesItemDao.insertPuzzleItem(puzzleItem); final result = puzzlesItemDao.streamAllPuzzlesItems(id); // Verify that the streamAllPuzzlesItems method is called with the correct // argument // Verify that the result matches the expected puzzleItems expect(result, emits(puzzleItems)); }); }); }
0
mirrored_repositories/puzzles/packages/local_storage_puzzles_api/test/src/database
mirrored_repositories/puzzles/packages/local_storage_puzzles_api/test/src/database/daos/puzzles_dao_test.dart
import 'package:drift/drift.dart'; import 'package:drift/native.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:local_storage_puzzles_api/src/database/daos/puzzles_dao.dart'; import 'package:local_storage_puzzles_api/src/database/db.dart'; import 'package:mockito/mockito.dart'; import 'package:puzzles_api/puzzles_api.dart'; class MockPuzzlesDao extends Mock implements PuzzlesDao { @override Future<void> insertPuzzle(Puzzle puzzle) => Future.value(); @override Future<void> updatePuzzle(Puzzle puzzle) => Future.value(); @override Future<void> deletePuzzle(Puzzle puzzle) => Future.value(); @override Future<List<Puzzle>>? getAllPuzzles() => Future.value(puzzles); @override Stream<List<Puzzle>> streamAllPuzzles() => Stream.value(puzzles); @override Future<Puzzle?>? getPuzzleById(int id) => Future.value(puzzle); } final puzzles = [puzzle]; final puzzle = Puzzle( id: 1, puzzleType: 'xoxo', createdAt: DateTime.november.toString(), completedAt: DateTime.november.toString(), ); void main() { TestWidgetsFlutterBinding.ensureInitialized(); late MyDatabase mockDatabase; late PuzzlesDao puzzlesDao; group('PuzzlesDao tests', () { setUp(() { final inMemory = DatabaseConnection(NativeDatabase.memory()); // Initialize the database with the temporary file mockDatabase = MyDatabase(inMemory); puzzlesDao = PuzzlesDao(mockDatabase); }); // Close the database after each test tearDown(() async { await mockDatabase.close(); }); test('Test insertPuzzle', () async { await puzzlesDao.insertPuzzle(puzzle); // ignore: inference_failure_on_instance_creation // Verify that the insertPuzzle method is called with the correct // argument final result = await puzzlesDao.getPuzzleById(1); expect(puzzle, equals(result)); }); test('Test updatePuzzle', () async { await puzzlesDao.insertPuzzle(puzzle); await puzzlesDao.updatePuzzle(puzzle.copyWith(createdAt: '12')); // Verify that the updatePuzzle method is called with the correct // argument final result = await puzzlesDao.getPuzzleById(1); expect(puzzle.copyWith(createdAt: '12'), equals(result)); }); test('Test deletePuzzle', () async { await puzzlesDao.insertPuzzle(puzzle); await puzzlesDao.deletePuzzle(puzzle); // ignore: flutter_style_todos // ignore: todo // TODO(assert): assert on delete }); test('Test getAllPuzzles', () async { await puzzlesDao.insertPuzzle(puzzle); final result = await puzzlesDao.getAllPuzzles(); // Verify that the result matches the expected puzzles expect(result, puzzles); }); test('Test streamAllPuzzles', () async { await puzzlesDao.insertPuzzle(puzzle); final result = puzzlesDao.streamAllPuzzles(); // Verify that the streamAllPuzzles method is called with the correct // argument // Verify that the result matches the expected puzzles expect(result, emits(puzzles)); }); }); }
0
mirrored_repositories/QuizApp-Flutter
mirrored_repositories/QuizApp-Flutter/lib/generated_plugin_registrant.dart
// // Generated file. Do not edit. // // ignore_for_file: directives_ordering // ignore_for_file: lines_longer_than_80_chars import 'package:connectivity_plus_web/connectivity_plus_web.dart'; import 'package:fluttertoast/fluttertoast_web.dart'; import 'package:shared_preferences_web/shared_preferences_web.dart'; import 'package:url_launcher_web/url_launcher_web.dart'; import 'package:flutter_web_plugins/flutter_web_plugins.dart'; // ignore: public_member_api_docs void registerPlugins(Registrar registrar) { ConnectivityPlusPlugin.registerWith(registrar); FluttertoastWebPlugin.registerWith(registrar); SharedPreferencesPlugin.registerWith(registrar); UrlLauncherPlugin.registerWith(registrar); registrar.registerMessageHandler(); }
0
mirrored_repositories/QuizApp-Flutter
mirrored_repositories/QuizApp-Flutter/lib/main.dart
import 'package:flutter/material.dart'; import 'package:nb_utils/nb_utils.dart'; import 'package:quiz/Screens/QuizSplashScreen.dart'; /* MIT License Copyright (c) 2024 Muhammad Fiaz Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ void main() async { // await initialize(); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Quiz App', home: QuizSplashScreen(), debugShowCheckedModeBanner: false, navigatorKey: navigatorKey, ); } }
0
mirrored_repositories/QuizApp-Flutter/lib
mirrored_repositories/QuizApp-Flutter/lib/Screens/QuizDetails.dart
import 'package:flutter/material.dart'; import 'package:nb_utils/nb_utils.dart'; import 'package:quiz/Screens/QuizCard.dart'; import 'package:quiz/model/QuizModels.dart'; import 'package:quiz/utils/AppWidget.dart'; import 'package:quiz/utils/QuizColors.dart'; import 'package:quiz/utils/QuizConstant.dart'; import 'package:quiz/utils/QuizDataGenerator.dart'; import 'package:quiz/utils/QuizStrings.dart'; import 'package:quiz/utils/QuizWidget.dart'; class QuizDetails extends StatefulWidget { static String tag = '/QuizDetails'; @override _QuizDetailsState createState() => _QuizDetailsState(); } class _QuizDetailsState extends State<QuizDetails> { late List<QuizTestModel> mList; @override void initState() { super.initState(); mList = quizGetData(); } @override Widget build(BuildContext context) { changeStatusColor(quiz_app_background); return Scaffold( backgroundColor: quiz_app_background, body: Column( children: <Widget>[ quizTopBar(quiz_lbl_biology_basics), Expanded( child: SingleChildScrollView( child: Column( children: <Widget>[ SizedBox( height: 20, ), text(quiz_lbl_biology_amp_scientific_method, isLongText: true, fontFamily: fontBold, isCentered: true, fontSize: textSizeXLarge), text(quiz_text_4_to_8_lesson, textColor: quiz_textColorSecondary), SizedBox( height: 10, ), ListView.builder( scrollDirection: Axis.vertical, itemCount: mList.length, shrinkWrap: true, physics: NeverScrollableScrollPhysics(), itemBuilder: (context, index) { return quizList(mList[index], index); }), ], ), ), ) ], ), ); } } // ignore: must_be_immutable, camel_case_types class quizList extends StatelessWidget { late var width; late QuizTestModel model; quizList(QuizTestModel model, int pos) { this.model = model; } @override Widget build(BuildContext context) { width = MediaQuery.of(context).size.width; return Container( margin: EdgeInsets.only(left: 16, bottom: 16, right: 16), decoration: boxDecoration(radius: 10, showShadow: true, bgColor: quiz_white), padding: EdgeInsets.all(16), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Row( children: <Widget>[ Container( decoration: BoxDecoration(shape: BoxShape.circle, color: quiz_color_setting), width: width / 6.5, height: width / 6.5, padding: EdgeInsets.all(10), child: commonCacheImageWidget( model.image, ), ), SizedBox( width: 16, ), Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ text(model.type, textColor: quiz_textColorSecondary, fontSize: textSizeSMedium), text( model.heading, fontFamily: fontMedium, ), ], ) ], ), SizedBox( height: 16, ), text(model.description, textColor: quiz_textColorSecondary), SizedBox( height: 16, ), quizButton( textContent: quiz_lbl_begin, onPressed: () { QuizCards().launch(context); }) ], ), ); } }
0
mirrored_repositories/QuizApp-Flutter/lib
mirrored_repositories/QuizApp-Flutter/lib/Screens/QuizAllList.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart'; import 'package:nb_utils/nb_utils.dart'; import 'package:quiz/Screens/QuizDetails.dart'; import 'package:quiz/model/QuizModels.dart'; import 'package:quiz/utils/AppWidget.dart'; import 'package:quiz/utils/QuizColors.dart'; import 'package:quiz/utils/QuizConstant.dart'; import 'package:quiz/utils/QuizDataGenerator.dart'; import 'package:quiz/utils/QuizStrings.dart'; class QuizAllList extends StatefulWidget { static String tag = '/QuizAllList'; @override _QuizAllListState createState() => _QuizAllListState(); } class _QuizAllListState extends State<QuizAllList> { late List<NewQuizModel> mListings; int selectedPos = 1; @override void initState() { super.initState(); selectedPos = 1; mListings = getQuizData(); } @override Widget build(BuildContext context) { var width = MediaQuery.of(context).size.width; final quizAll = StaggeredGridView.countBuilder( crossAxisCount: 4, mainAxisSpacing: 4.0, crossAxisSpacing: 4.0, staggeredTileBuilder: (index) => StaggeredTile.fit(2), scrollDirection: Axis.vertical, itemCount: mListings.length, physics: NeverScrollableScrollPhysics(), shrinkWrap: true, itemBuilder: (context, index) { changeStatusColor(quiz_app_background); return Container( margin: EdgeInsets.all(8), child: Column( children: <Widget>[ ClipRRect( borderRadius: BorderRadius.only(topLeft: Radius.circular(16.0), topRight: Radius.circular(16.0)), child: CachedNetworkImage( placeholder: placeholderWidgetFn() as Widget Function(BuildContext, String)?, imageUrl: mListings[index].quizImage, height: width * 0.4, width: MediaQuery.of(context).size.width / 0.25, fit: BoxFit.cover, ), ), Container( decoration: BoxDecoration( borderRadius: BorderRadius.only(bottomLeft: Radius.circular(16.0), bottomRight: Radius.circular(16.0)), color: quiz_white, ), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ text(mListings[index].quizName, fontSize: textSizeMedium, maxLine: 2, fontFamily: fontMedium).paddingOnly(top: 8, left: 16, right: 16, bottom: 8), text(mListings[index].totalQuiz, textColor: quiz_textColorSecondary).paddingOnly(left: 16, right: 16, bottom: 8), ], ), ), ], ), ).cornerRadiusWithClipRRect(16).onTap(() { QuizDetails().launch(context); }); }, //gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2, childAspectRatio: 0.67, mainAxisSpacing: 16, crossAxisSpacing: 16), ); Widget quizCompleted = StaggeredGridView.countBuilder( crossAxisCount: 4, mainAxisSpacing: 4.0, crossAxisSpacing: 4.0, staggeredTileBuilder: (index) => StaggeredTile.fit(2), scrollDirection: Axis.vertical, itemCount: mListings.length, physics: NeverScrollableScrollPhysics(), shrinkWrap: true, itemBuilder: (context, index) { changeStatusColor(quiz_app_background); return Container( margin: EdgeInsets.all(8), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ ClipRRect( borderRadius: BorderRadius.only(topLeft: Radius.circular(16.0), topRight: Radius.circular(16.0)), child: CachedNetworkImage( placeholder: placeholderWidgetFn() as Widget Function(BuildContext, String)?, imageUrl: mListings[index].quizImage, height: width * 0.4, width: MediaQuery.of(context).size.width / 0.25, fit: BoxFit.cover, ), ), Container( decoration: BoxDecoration( borderRadius: BorderRadius.only(bottomLeft: Radius.circular(16.0), bottomRight: Radius.circular(16.0)), color: quiz_white, ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ text(mListings[index].quizName, fontSize: textSizeMedium, maxLine: 2, fontFamily: fontMedium).paddingOnly(top: 8, left: 16, right: 16, bottom: 8), text(mListings[index].totalQuiz, textColor: quiz_textColorSecondary).paddingOnly(left: 16, right: 16, bottom: 16), LinearProgressIndicator( value: 0.5, backgroundColor: textSecondaryColor.withOpacity(0.2), valueColor: AlwaysStoppedAnimation<Color>(quiz_green), ).paddingOnly(left: 16, right: 16, bottom: 16), ], ), ), ], ), ).cornerRadiusWithClipRRect(16).onTap(() { QuizDetails().launch(context); }); }, //gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2, childAspectRatio: 0.60, mainAxisSpacing: 16, crossAxisSpacing: 16), ); return SafeArea( child: Scaffold( backgroundColor: quiz_app_background, body: SingleChildScrollView( child: Container( child: Column( children: <Widget>[ SizedBox(height: 40), Container( width: width, decoration: boxDecoration(radius: spacing_middle, bgColor: quiz_white, showShadow: false), margin: EdgeInsets.fromLTRB(16, 0, 16, 16), child: Row( children: <Widget>[ Flexible( child: GestureDetector( onTap: () { selectedPos = 1; setState(() {}); }, child: Container( padding: EdgeInsets.all(8.0), width: width, decoration: BoxDecoration( borderRadius: BorderRadius.only(topLeft: Radius.circular(spacing_middle), bottomLeft: Radius.circular(spacing_middle)), color: selectedPos == 1 ? quiz_white : Colors.transparent, border: Border.all(color: selectedPos == 1 ? quiz_white : Colors.transparent), ), child: text( quiz_lbl_All, fontSize: textSizeMedium, isCentered: true, fontFamily: fontMedium, textColor: selectedPos == 1 ? quiz_textColorPrimary : quiz_textColorSecondary, ), ), ), flex: 1, ), Container(height: 40, width: 1, color: quiz_light_gray).center(), Flexible( child: GestureDetector( onTap: () { setState(() { selectedPos = 2; }); }, child: Container( padding: EdgeInsets.all(16.0), width: width, decoration: BoxDecoration( borderRadius: BorderRadius.only(topRight: Radius.circular(spacing_middle), bottomRight: Radius.circular(spacing_middle)), color: selectedPos == 2 ? quiz_white : Colors.transparent, border: Border.all(color: selectedPos == 2 ? quiz_white : Colors.transparent), ), child: text( quiz_lbl_Completed, fontSize: textSizeMedium, isCentered: true, fontFamily: fontMedium, textColor: selectedPos == 2 ? quiz_textColorPrimary : quiz_textColorSecondary, ), ), ), flex: 1, ), ], ), ), SingleChildScrollView( physics: ScrollPhysics(), child: Container( margin: EdgeInsets.only(right: 8, left: 8), child: selectedPos == 1 ? quizAll : quizCompleted, ), ), ], ), ), ), ), ); } }
0
mirrored_repositories/QuizApp-Flutter/lib
mirrored_repositories/QuizApp-Flutter/lib/Screens/QuizDashboard.dart
import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:quiz/Screens/QuizAllList.dart'; import 'package:quiz/Screens/QuizHome.dart'; import 'package:quiz/Screens/QuizProfile.dart'; import 'package:quiz/utils/AppWidget.dart'; import 'package:quiz/utils/QuizColors.dart'; import 'package:quiz/utils/QuizImages.dart'; class QuizDashboard extends StatefulWidget { static String tag = '/QuizDashboard'; @override _QuizDashboardState createState() => _QuizDashboardState(); } class _QuizDashboardState extends State<QuizDashboard> { var selectedIndex = 0; var pages = [ QuizHome(), QuizAllList(), QuizProfile(), ]; @override void initState() { super.initState(); selectedIndex = 0; } void _onItemTapped(int index) { setState(() { selectedIndex = index; if (selectedIndex == 0) { } else if (selectedIndex == 1) { } else if (selectedIndex == 2) {} }); } Widget quizItem(var pos, var icon, var title) { return GestureDetector( onTap: () { setState(() { _onItemTapped(pos); }); }, child: Container( height: 55, alignment: Alignment.center, child: Column( children: <Widget>[ SvgPicture.asset( icon, width: 20, height: 20, color: selectedIndex == pos ? quiz_colorPrimary : quiz_icon_color, ), text( title, textColor: selectedIndex == pos ? quiz_colorPrimary : quiz_icon_color, ) ], ), ), ); } @override Widget build(BuildContext context) { changeStatusColor(quiz_app_background); return Scaffold( backgroundColor: quiz_app_background, body: SafeArea( child: pages[selectedIndex], ), bottomNavigationBar: Container( //padding: EdgeInsets.all(20), decoration: BoxDecoration( color: quiz_white, border: Border.all( color: quiz_ShadowColor, ), borderRadius: BorderRadius.only(topLeft: Radius.circular(20), topRight: Radius.circular(20)), boxShadow: [ BoxShadow( color: quiz_ShadowColor, blurRadius: 10, spreadRadius: 2, offset: Offset(0, 3.0), ), ], ), child: Padding( padding: const EdgeInsets.only(left: 0.0, right: 0, top: 8), child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: <Widget>[ quizItem(0, quiz_ic_homes, "Home"), quizItem(1, quiz_ic_quiz, "Quiz"), quizItem(2, quiz_ic_user, "Profile"), ], ), ), ), ); } }
0
mirrored_repositories/QuizApp-Flutter/lib
mirrored_repositories/QuizApp-Flutter/lib/Screens/QuizSearch.dart
import 'package:flutter/material.dart'; import 'package:quiz/Screens/RepoScreen.dart'; import 'package:quiz/model/QuizModels.dart'; import 'package:quiz/utils/QuizColors.dart'; import 'package:quiz/utils/QuizDataGenerator.dart'; class QuizSearch extends StatefulWidget { static String tag = '/QuizSearch'; @override _QuizSearchState createState() => _QuizSearchState(); } class _QuizSearchState extends State<QuizSearch> { late List<NewQuizModel> mListings; var searchCont = TextEditingController(); @override void initState() { super.initState(); mListings = getQuizData(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: quiz_app_background, body: RepoScreen(enableAppbar: true), ); } }
0
mirrored_repositories/QuizApp-Flutter/lib
mirrored_repositories/QuizApp-Flutter/lib/Screens/QuizProfile.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:nb_utils/nb_utils.dart'; import 'package:quiz/Screens/RepoScreen.dart'; import 'package:quiz/Screens/QuizSettings.dart'; import 'package:quiz/model/QuizModels.dart'; import 'package:quiz/utils/AppWidget.dart'; import 'package:quiz/utils/QuizColors.dart'; import 'package:quiz/utils/QuizConstant.dart'; import 'package:quiz/utils/QuizDataGenerator.dart'; import 'package:quiz/utils/QuizImages.dart'; import 'package:quiz/utils/QuizStrings.dart'; class QuizProfile extends StatefulWidget { static String tag = '/QuizProfile'; @override _QuizProfileState createState() => _QuizProfileState(); } class _QuizProfileState extends State<QuizProfile> { late List<QuizBadgesModel> mList; late List<QuizScoresModel> mList1; int selectedPos = 1; @override void initState() { super.initState(); selectedPos = 1; mList = quizBadgesData(); mList1 = quizScoresData(); } @override Widget build(BuildContext context) { var width = MediaQuery.of(context).size.width; final imgview = Container( color: quiz_app_background, child: Column( children: <Widget>[ Stack( alignment: Alignment.bottomRight, children: <Widget>[ Container( height: width * 0.35, width: width * 0.35, decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: quiz_white, width: 4)), child: CircleAvatar(backgroundImage: CachedNetworkImageProvider(quiz_img_People2), radius: MediaQuery.of(context).size.width / 8.5), ), Container( height: 30, width: 30, decoration: BoxDecoration(shape: BoxShape.circle, border: Border.all(color: quiz_white, width: 2), color: quiz_white), child: Icon(Icons.edit, size: 20).onTap(() { RepoScreen(enableAppbar: true).launch(context); }), ).paddingOnly(right: 16, top: 16).onTap(() { print("Edit profile"); }) ], ), text(quiz_lbl, textColor: quiz_textColorPrimary, fontSize: textSizeLargeMedium, fontFamily: fontBold).paddingOnly(top: 24), text(quiz_lbl_Xp, textColor: quiz_textColorSecondary, fontSize: textSizeMedium, fontFamily: fontRegular).paddingOnly(top: 8), SizedBox(height: 30), Container( width: width, decoration: boxDecoration(radius: spacing_middle, bgColor: quiz_white, showShadow: false), margin: EdgeInsets.fromLTRB(16, 0, 16, 16), child: Row( children: <Widget>[ Flexible( child: GestureDetector( onTap: () { setState(() { selectedPos = 1; }); }, child: Container( padding: EdgeInsets.all(8.0), width: width, decoration: BoxDecoration( borderRadius: BorderRadius.only(topLeft: Radius.circular(spacing_middle), bottomLeft: Radius.circular(spacing_middle)), color: selectedPos == 1 ? quiz_white : Colors.transparent, border: Border.all(color: selectedPos == 1 ? quiz_white : Colors.transparent), ), child: text( quiz_lbl_Badges, fontSize: textSizeMedium, fontFamily: fontSemibold, isCentered: true, textColor: selectedPos == 1 ? quiz_textColorPrimary : quiz_textColorSecondary, ), ), ), flex: 1, ), Container( height: 40, width: 1, color: quiz_light_gray, ).center(), Flexible( child: GestureDetector( onTap: () { setState(() { selectedPos = 2; }); }, child: Container( padding: EdgeInsets.all(16.0), width: width, decoration: BoxDecoration( borderRadius: BorderRadius.only(topRight: Radius.circular(spacing_middle), bottomRight: Radius.circular(spacing_middle)), color: selectedPos == 2 ? quiz_white : Colors.transparent, border: Border.all(color: selectedPos == 2 ? quiz_white : Colors.transparent), ), child: text( quiz_lbl_Scores, fontSize: textSizeMedium, fontFamily: fontSemibold, isCentered: true, textColor: selectedPos == 2 ? quiz_textColorPrimary : quiz_textColorSecondary, ), )), flex: 1, ), ], ), ), selectedPos == 1 ? Container( decoration: boxDecoration(bgColor: quiz_white, radius: 10, showShadow: true), width: MediaQuery.of(context).size.width - 32, child: ListView.builder( scrollDirection: Axis.vertical, itemCount: mList.length, shrinkWrap: true, physics: ScrollPhysics(), itemBuilder: (BuildContext context, int index) => GestureDetector( onTap: () {}, child: Container( child: Row( children: <Widget>[ commonCacheImageWidget( mList[index].img, height: 50, width: 50, ).paddingOnly(right: 8), Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[text(mList[index].title, fontFamily: fontMedium, textColor: quiz_textColorPrimary), text(mList[index].subtitle, textColor: quiz_textColorSecondary)], ), ], ), ).paddingAll(8), ))).paddingOnly(bottom: 16) : Container( decoration: boxDecoration(bgColor: quiz_white, radius: 10, showShadow: true), width: MediaQuery.of(context).size.width - 32, child: ListView.builder( scrollDirection: Axis.vertical, itemCount: mList1.length, shrinkWrap: true, physics: ScrollPhysics(), itemBuilder: (BuildContext context, int index) => GestureDetector( onTap: () {}, child: Container( child: Row( children: <Widget>[ CachedNetworkImage( placeholder: placeholderWidgetFn() as Widget Function(BuildContext, String)?, imageUrl: mList1[index].img, height: 50, width: 50, fit: BoxFit.fill, ).cornerRadiusWithClipRRect(25).paddingOnly(right: 16), Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ text(mList1[index].title, fontFamily: fontMedium, textColor: quiz_textColorPrimary), Row( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[text(mList1[index].totalQuiz, textColor: quiz_textColorSecondary), text(mList1[index].scores, textColor: quiz_textColorSecondary, fontSize: textSizeMedium, fontFamily: fontRegular)], ) ], ), ], ), ).paddingAll(8), ))).paddingOnly(bottom: 16) ], ), ).center(); changeStatusColor(quiz_app_background); return SafeArea( child: Scaffold( backgroundColor: quiz_app_background, appBar: AppBar( actions: <Widget>[ IconButton( icon: Icon(Icons.settings), color: blackColor, onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (context) => QuizSettings())), ), ], leading: Container(), backgroundColor: quiz_app_background, elevation: 0.0, ), body: SingleChildScrollView( physics: ScrollPhysics(), child: Container(color: quiz_app_background, child: imgview), ), ), ); } }
0
mirrored_repositories/QuizApp-Flutter/lib
mirrored_repositories/QuizApp-Flutter/lib/Screens/QuizHome.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:nb_utils/nb_utils.dart'; import 'package:quiz/Screens/QuizDetails.dart'; import 'package:quiz/Screens/QuizNewList.dart'; import 'package:quiz/Screens/QuizSearch.dart'; import 'package:quiz/model/QuizModels.dart'; import 'package:quiz/utils/AppWidget.dart'; import 'package:quiz/utils/QuizColors.dart'; import 'package:quiz/utils/QuizConstant.dart'; import 'package:quiz/utils/QuizDataGenerator.dart'; import 'package:quiz/utils/QuizStrings.dart'; import 'package:quiz/utils/QuizWidget.dart'; class QuizHome extends StatefulWidget { static String tag = '/QuizHome'; @override _QuizHomeState createState() => _QuizHomeState(); } class _QuizHomeState extends State<QuizHome> { late List<NewQuizModel> mListings; @override void initState() { super.initState(); mListings = getQuizData(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: quiz_app_background, body: SafeArea( child: Stack( children: <Widget>[ SingleChildScrollView( padding: EdgeInsets.only(bottom: 16), child: Column( children: <Widget>[ SizedBox(height: 30), text(quiz_lbl_hi_antonio, fontFamily: fontBold, fontSize: textSizeXLarge), text(quiz_lbl_what_would_you_like_to_learn_n_today_search_below, textColor: quiz_textColorSecondary, isLongText: true, isCentered: true), SizedBox(height: 30), Container( margin: EdgeInsets.all(16.0), decoration: boxDecoration(radius: 10, showShadow: true, bgColor: quiz_white), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Expanded(child: quizEditTextStyle(quiz_lbl_search, isPassword: false)), Container( margin: EdgeInsets.only(right: 10), decoration: boxDecoration(radius: 10, showShadow: false, bgColor: quiz_colorPrimary), padding: EdgeInsets.all(10), child: Icon(Icons.search, color: quiz_white), ).onTap(() { QuizSearch().launch(context); setState(() {}); }) ], ), ), Padding( padding: const EdgeInsets.all(16.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ text(quiz_lbl_new_quiz, textAllCaps: true, fontFamily: fontMedium, fontSize: textSizeNormal), text( quiz_lbl_view_all, textColor: quiz_textColorSecondary, ).onTap(() { setState(() { QuizListing().launch(context); }); }), ], ), ), SizedBox( //height: MediaQuery.of(context).size.width * 0.8, height: 300, child: ListView.builder( scrollDirection: Axis.horizontal, itemCount: mListings.length, shrinkWrap: true, physics: ScrollPhysics(), itemBuilder: (BuildContext context, int index) => GestureDetector( onTap: () { QuizDetails().launch(context); }, child: NewQuiz(mListings[index], index), ), ), ).paddingOnly(bottom: 16), ], ), ), ], ), ), ); } } // ignore: must_be_immutable class NewQuiz extends StatelessWidget { late NewQuizModel model; NewQuiz(NewQuizModel model, int pos) { this.model = model; } @override Widget build(BuildContext context) { var w = MediaQuery.of(context).size.width; return Container( margin: EdgeInsets.only(left: 16), width: MediaQuery.of(context).size.width * 0.75, decoration: boxDecoration(radius: 16, showShadow: true, bgColor: quiz_white), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Stack( alignment: Alignment.topRight, children: <Widget>[ ClipRRect( borderRadius: BorderRadius.only(topLeft: Radius.circular(16.0), topRight: Radius.circular(16.0)), child: CachedNetworkImage(placeholder: placeholderWidgetFn() as Widget Function(BuildContext, String)?, imageUrl: model.quizImage, height: w * 0.4, width: MediaQuery.of(context).size.width * 0.75, fit: BoxFit.cover), ), ], ), Padding( padding: const EdgeInsets.all(16.0), child: Row( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ text(model.quizName, fontSize: textSizeMedium, isLongText: true, fontFamily: fontMedium, isCentered: false), text(model.totalQuiz, textColor: quiz_textColorSecondary), ], ), Icon(Icons.arrow_forward, color: quiz_textColorSecondary), ], ), ), ], ), ); } }
0
mirrored_repositories/QuizApp-Flutter/lib
mirrored_repositories/QuizApp-Flutter/lib/Screens/QuizMobileVerify.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:nb_utils/nb_utils.dart'; import 'package:quiz/Screens/QuizDashboard.dart'; import 'package:quiz/Screens/QuizVerifcation.dart'; import 'package:quiz/utils/AppWidget.dart'; import 'package:quiz/utils/QuizColors.dart'; import 'package:quiz/utils/QuizConstant.dart'; import 'package:quiz/utils/QuizStrings.dart'; import 'package:quiz/utils/QuizWidget.dart'; import 'package:quiz/utils/codePicker/country_code_picker.dart'; class QuizMobileVerify extends StatefulWidget { static String tag = '/QuizMobileVerify'; @override _QuizMobileVerifyState createState() => _QuizMobileVerifyState(); } class _QuizMobileVerifyState extends State<QuizMobileVerify> { @override Widget build(BuildContext context) { changeStatusColor(quiz_app_background); return Scaffold( appBar: AppBar( title: text(quiz_lbl_let_started, fontSize: textSizeLargeMedium, fontFamily: fontMedium), leading: Icon( Icons.arrow_back, color: quiz_colorPrimary, size: 30, ).onTap(() { Navigator.of(context).pop(); }), actions: <Widget>[ Padding( padding: EdgeInsets.only(right: 16.0), child: GestureDetector( onTap: () { setState(() { QuizDashboard().launch(context); }); }, child: text(quiz_lbl_skip, textColor: quiz_textColorSecondary, fontSize: textSizeMedium, fontFamily: fontMedium).center())), ], centerTitle: true, backgroundColor: quiz_app_background, elevation: 0.0, ), body: SafeArea( child: SingleChildScrollView( child: Container( height: MediaQuery.of(context).size.height, color: quiz_app_background, child: Column( children: <Widget>[ SizedBox(height: 20), text(quiz_info_let_started, textColor: quiz_textColorSecondary, isLongText: true, isCentered: true).center(), SizedBox(height: 20), Container( margin: EdgeInsets.all(24.0), decoration: boxDecoration(bgColor: quiz_white, color: quiz_white, showShadow: true, radius: 10), child: Row( children: <Widget>[ SizedBox(width: 5), CountryCodePicker(onChanged: print, showFlag: true), Container( height: 30.0, width: 1.0, color: quiz_colorPrimary, margin: const EdgeInsets.only(left: 10.0, right: 10.0), ), Expanded( child: TextFormField( keyboardType: TextInputType.number, maxLength: 10, style: TextStyle(fontSize: textSizeLargeMedium, fontFamily: fontRegular), decoration: InputDecoration( contentPadding: EdgeInsets.fromLTRB(16, 22, 16, 22), counterText: "", hintText: quiz_hint_Mobile_Number, hintStyle: TextStyle(color: quiz_textColorPrimary, fontSize: textSizeMedium), border: InputBorder.none, ), ), ) ], ), ), SizedBox(height: 20), Container( child: Column( children: <Widget>[ text(quiz_lbl_already_have_an_account), text(quiz_lbl_sign_in, textColor: quiz_colorPrimary, textAllCaps: true), ], ).onTap(() { finish(context); }), ).onTap(() { Navigator.of(context).pop(); }), SizedBox(height: 20), Container( margin: EdgeInsets.all(24.0), child: quizButton( textContent: quiz_lbl_continue, onPressed: () { setState(() { QuizVerification().launch(context); }); }, ), ) ], ), ), ), ), ); } }
0
mirrored_repositories/QuizApp-Flutter/lib
mirrored_repositories/QuizApp-Flutter/lib/Screens/QuizCard.dart
import 'package:flutter/material.dart'; import 'package:nb_utils/nb_utils.dart'; import 'package:quiz/Screens/RepoScreen.dart'; import 'package:quiz/utils/AppWidget.dart'; import 'package:quiz/utils/QuizCard.dart'; import 'package:quiz/utils/QuizColors.dart'; import 'package:quiz/utils/QuizConstant.dart'; class QuizCards extends StatefulWidget { static String tag = '/QuizCards'; @override _QuizCardsState createState() => _QuizCardsState(); } class _QuizCardsState extends State<QuizCards> { List<Widget> cardList = []; void removeCards(index) { setState(() { cardList.removeAt(index); }); } @override void initState() { super.initState(); cardList = _generateCards(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: quiz_app_background, body: SafeArea( child: Stack( alignment: Alignment.center, children: <Widget>[ Container( child: Stack(alignment: Alignment.center, children: cardList), ), Container( alignment: Alignment.topCenter, child: Row( children: <Widget>[ IconButton( onPressed: () { finish(context); }, icon: Icon( Icons.close, color: quiz_colorPrimary, ), ), Expanded( child: LinearProgressIndicator( value: 0.5, backgroundColor: textSecondaryColor.withOpacity(0.2), valueColor: AlwaysStoppedAnimation<Color>( quiz_green, ), ).paddingAll(16), ) ], ), ) ], ), )); } List<Widget> _generateCards() { List<Quiz> planetCard = []; planetCard.add( Quiz("How many basic steps are there in scientific method?", "Eight Steps", "Ten Steps", "Two Steps", "One Steps", 70.0), ); planetCard.add( Quiz("Which blood vessels have the smallest diameter? ", "Capillaries", "Arterioles", "Venules", "Lymphatic", 80.0), ); planetCard.add(Quiz("The substrate of photo-respiration is", "Phruvic acid", "Glucose", "Fructose", "Glycolate", 90.0)); planetCard.add(Quiz("Which one of these animal is jawless?", "Shark", "Myxine", "Trygon", "Sphyrna", 100.0)); planetCard.add( Quiz("How many basic steps are there in scientific method?", "Eight Steps", "Ten Steps", "One Steps", "Three Steps", 110.0), ); List<Widget> cardList = []; for (int x = 0; x < 5; x++) { cardList.add( Positioned( top: planetCard[x].topMargin, child: Draggable( onDragEnd: (drag) { if (x == 0) { setState(() { RepoScreen().launch(context); }); } removeCards(x); }, childWhenDragging: Container(), feedback: Material( child: GestureDetector( child: Container( decoration: boxDecoration(radius: 20, bgColor: quiz_white, showShadow: true), child: Column( children: <Widget>[ Container( height: 200.0, width: 320.0, child: Container( margin: EdgeInsets.only(top: 50), padding: EdgeInsets.fromLTRB(20, 16, 20, 16), child: text(planetCard[x].cardImage, fontSize: textSizeLarge, fontFamily: fontBold, isLongText: true), ), ), Container( padding: EdgeInsets.only(top: 10.0, bottom: 10.0), child: Column( children: <Widget>[ quizCardSelection("A.", planetCard[x].option1, () { removeCards(x); }), quizCardSelection("B.", planetCard[x].option2, () { removeCards(x); }), quizCardSelection("C.", planetCard[x].option3, () { removeCards(x); }), quizCardSelection("D.", planetCard[x].option4, () { removeCards(x); }), ], )) ], ), ), ), ), child: GestureDetector( child: Container( decoration: boxDecoration(radius: 20, bgColor: quiz_white, showShadow: true), child: Column( children: <Widget>[ Container( height: 200.0, width: 320.0, child: Container( margin: EdgeInsets.only(top: 50), padding: EdgeInsets.fromLTRB(20, 16, 20, 16), child: text(planetCard[x].cardImage, fontSize: textSizeLarge, fontFamily: fontBold, isLongText: true), )), Container( padding: EdgeInsets.only(top: 10.0, bottom: 10.0), child: Column( children: <Widget>[ quizCardSelection("A.", planetCard[x].option1, () { removeCards(x); }), quizCardSelection("B.", planetCard[x].option2, () { removeCards(x); }), quizCardSelection("C.", planetCard[x].option3, () { removeCards(x); }), quizCardSelection("D.", planetCard[x].option4, () { removeCards(x); }), ], )) ], )), )), ), ); } return cardList; } } Widget quizCardSelection(var option, var option1, onPressed) { return InkWell( onTap: () { onPressed(); }, child: Container( margin: EdgeInsets.fromLTRB(16, 0, 16, 16), decoration: boxDecoration(showShadow: false, bgColor: quiz_edit_background, radius: 10, color: quiz_view_color), padding: EdgeInsets.fromLTRB(16, 10, 16, 10), width: 320, child: Stack( alignment: Alignment.center, children: <Widget>[ Center( child: text(option1, textColor: quiz_textColorSecondary), ), Align( alignment: Alignment.topLeft, child: text(option, textColor: quiz_textColorSecondary), ) ], ), ), ); }
0
mirrored_repositories/QuizApp-Flutter/lib
mirrored_repositories/QuizApp-Flutter/lib/Screens/RepoButton.dart
import 'package:flutter/material.dart'; import 'package:nb_utils/nb_utils.dart'; import 'package:quiz/utils/QuizColors.dart'; import 'package:url_launcher/url_launcher.dart'; class RepoButton extends StatelessWidget { @override Widget build(BuildContext context) { return AppButton( text: 'Check out the Repo', color: quiz_colorPrimary, textStyle: boldTextStyle(color: Colors.white), shapeBorder: RoundedRectangleBorder(borderRadius: radius(10)), onTap: () { launch("https://github.com/muhammad-fiaz/QuizApp-Flutter"); }, ); } }
0
mirrored_repositories/QuizApp-Flutter/lib
mirrored_repositories/QuizApp-Flutter/lib/Screens/QuizSignUp.dart
import 'package:flutter/material.dart'; import 'package:nb_utils/nb_utils.dart'; import 'package:quiz/Screens/QuizCreatePassword.dart'; import 'package:quiz/utils/AppWidget.dart'; import 'package:quiz/utils/QuizColors.dart'; import 'package:quiz/utils/QuizConstant.dart'; import 'package:quiz/utils/QuizStrings.dart'; import 'package:quiz/utils/QuizWidget.dart'; class QuizSignUp extends StatefulWidget { static String tag = '/QuizSignUp'; @override _QuizSignUpState createState() => _QuizSignUpState(); } class _QuizSignUpState extends State<QuizSignUp> { @override Widget build(BuildContext context) { changeStatusColor(quiz_app_background); return Scaffold( appBar: AppBar( title: text(quiz_lbl_create_account, fontSize: textSizeLargeMedium, fontFamily: fontMedium), leading: Icon( Icons.arrow_back, color: quiz_colorPrimary, size: 30, ).onTap(() { Navigator.of(context).pop(); }), centerTitle: true, backgroundColor: quiz_app_background, elevation: 0.0, ), body: SafeArea( child: Container( height: MediaQuery.of(context).size.height, color: quiz_app_background, child: SingleChildScrollView( child: Column( children: <Widget>[ SizedBox(height: 20), text(quiz_info_sign_up, textColor: quiz_textColorSecondary, isLongText: true, isCentered: true).center(), Container( margin: EdgeInsets.all(24.0), decoration: boxDecoration(bgColor: quiz_white, color: quiz_white, showShadow: true, radius: 10), child: quizEditTextStyle(quiz_hint_your_email, isPassword: false), ), SizedBox(height: 20), Container( child: Column( children: <Widget>[ text(quiz_lbl_already_have_an_account), text(quiz_lbl_sign_in, textColor: quiz_colorPrimary, textAllCaps: true), ], ), ).onTap(() { Navigator.of(context).pop(); }), SizedBox(height: 20), Container( margin: EdgeInsets.all(24.0), child: quizButton( textContent: quiz_lbl_continue, onPressed: () { setState(() { QuizCreatePassword().launch(context); }); }, ), ) ], ), ), ), ), ); } }
0
mirrored_repositories/QuizApp-Flutter/lib
mirrored_repositories/QuizApp-Flutter/lib/Screens/QuizSplashScreen.dart
import 'package:flutter/material.dart'; import 'package:quiz/Screens/QuizSignIn.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:nb_utils/nb_utils.dart'; import 'package:quiz/utils/AppWidget.dart'; import '../onBoardingScreens/view/onBoardingScreen.dart'; class QuizSplashScreen extends StatefulWidget { @override _QuizSplashScreenState createState() => _QuizSplashScreenState(); } class _QuizSplashScreenState extends State<QuizSplashScreen> { @override void initState() { super.initState(); init(); } void init() async { // Add logic to check if onboarding is complete SharedPreferences prefs = await SharedPreferences.getInstance(); bool onboardingComplete = prefs.getBool('onboarding_complete') ?? false; if (onboardingComplete) { await 3.seconds.delay.then((value) => push(QuizSignIn(), pageRouteAnimation: PageRouteAnimation.Slide, isNewTask: true)); } else { await 3.seconds.delay.then((value) => push(onBoardingScreenHome(), pageRouteAnimation: PageRouteAnimation.Slide, isNewTask: true)); } } @override void setState(fn) { if (mounted) super.setState(fn); } @override Widget build(BuildContext context) { return Scaffold( body: Container( child: Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ commonCacheImageWidget("images/quiz/ic_background.png", height: 250, width: 250), ], ).withWidth(context.width()), ), ); } }
0
mirrored_repositories/QuizApp-Flutter/lib
mirrored_repositories/QuizApp-Flutter/lib/Screens/QuizNewList.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart'; import 'package:nb_utils/nb_utils.dart'; import 'package:quiz/Screens/RepoScreen.dart'; import 'package:quiz/model/QuizModels.dart'; import 'package:quiz/utils/AppWidget.dart'; import 'package:quiz/utils/QuizColors.dart'; import 'package:quiz/utils/QuizConstant.dart'; import 'package:quiz/utils/QuizDataGenerator.dart'; import 'package:quiz/utils/QuizImages.dart'; import 'package:quiz/utils/QuizStrings.dart'; class QuizListing extends StatefulWidget { static String tag = '/QuizListing'; @override _QuizListingState createState() => _QuizListingState(); } class _QuizListingState extends State<QuizListing> { late List<NewQuizModel> mListings; var selectedGrid = true; var selectedList = false; @override void initState() { super.initState(); mListings = getQuizData(); } @override Widget build(BuildContext context) { var w = MediaQuery.of(context).size.width; final listing = Container( child: ListView.builder( scrollDirection: Axis.vertical, itemCount: mListings.length, shrinkWrap: true, physics: ScrollPhysics(), itemBuilder: (BuildContext context, int index) => GestureDetector( onTap: () { RepoScreen(enableAppbar: true).launch(context); }, child: Container( decoration: boxDecoration(radius: 16, showShadow: true, bgColor: quiz_white), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Stack( alignment: Alignment.topRight, children: <Widget>[ ClipRRect( borderRadius: BorderRadius.only(topLeft: Radius.circular(16.0), topRight: Radius.circular(16.0)), child: CachedNetworkImage(placeholder: placeholderWidgetFn() as Widget Function(BuildContext, String)?, imageUrl: mListings[index].quizImage, height: w * 0.4, width: MediaQuery.of(context).size.width / 0.25, fit: BoxFit.cover), ), ], ), Padding( padding: const EdgeInsets.all(16.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ text(mListings[index].quizName, fontSize: textSizeMedium, isLongText: true, fontFamily: fontMedium), SizedBox(height: 8), text(mListings[index].totalQuiz, textColor: quiz_textColorSecondary), ], ), ), ], ), ).paddingOnly(bottom: spacing_standard_new), ), ), ); final gridList = StaggeredGridView.countBuilder( crossAxisCount: 4, mainAxisSpacing: 4.0, crossAxisSpacing: 4.0, staggeredTileBuilder: (index) => StaggeredTile.fit(2), scrollDirection: Axis.vertical, itemCount: mListings.length, physics: NeverScrollableScrollPhysics(), shrinkWrap: true, itemBuilder: (context, index) { changeStatusColor(quiz_app_background); return Container( margin: EdgeInsets.all(8), //decoration: boxDecoration(radius: 16, showShadow: true, bgColor: quiz_white), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ ClipRRect( borderRadius: BorderRadius.only(topLeft: Radius.circular(16.0), topRight: Radius.circular(16.0)), child: CachedNetworkImage( placeholder: placeholderWidgetFn() as Widget Function(BuildContext, String)?, imageUrl: mListings[index].quizImage, height: w * 0.4, width: MediaQuery.of(context).size.width / 0.25, fit: BoxFit.cover, ), ), Container( decoration: BoxDecoration( borderRadius: BorderRadius.only(bottomLeft: Radius.circular(16.0), bottomRight: Radius.circular(16.0)), color: quiz_white, ), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ text(mListings[index].quizName, fontSize: textSizeMedium, maxLine: 2, fontFamily: fontMedium).paddingOnly(top: 8, left: 16, right: 16, bottom: 8), text(mListings[index].totalQuiz, textColor: quiz_textColorSecondary).paddingOnly(left: 16, right: 16, bottom: 16), ], ), ), ], ), ).cornerRadiusWithClipRRect(16).onTap(() { RepoScreen(enableAppbar: true).launch(context); }); }, //gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2, childAspectRatio: 0.58, crossAxisSpacing: 16, mainAxisSpacing: 16), ); changeStatusColor(quiz_app_background); return Scaffold( appBar: AppBar( title: text(quiz_lbl_new_quiz, fontSize: textSizeLargeMedium, fontFamily: fontMedium), leading: Icon( Icons.arrow_back, color: quiz_colorPrimary, size: 30, ).onTap(() { Navigator.of(context).pop(); }), centerTitle: true, backgroundColor: quiz_app_background, elevation: 0.0, ), body: SingleChildScrollView( child: SafeArea( child: Container( color: quiz_app_background, child: Column( children: <Widget>[ Row( mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[ commonCacheImageWidget( Quiz_ic_Grid, height: 20, width: 20, ).onTap(() { setState(() { selectedList = false; selectedGrid = true; }); }).paddingOnly(top: 8, right: 16), commonCacheImageWidget( Quiz_ic_List, height: 20, width: 20, ).onTap(() { setState(() { selectedList = true; selectedGrid = false; }); }).paddingOnly(top: 8, right: 16), ], ), SingleChildScrollView( child: Container( margin: EdgeInsets.all(16), child: selectedGrid ? gridList : listing, )) ], ), ), ), ), ); } }
0
mirrored_repositories/QuizApp-Flutter/lib
mirrored_repositories/QuizApp-Flutter/lib/Screens/QuizSignIn.dart
import 'package:flutter/material.dart'; import 'package:nb_utils/nb_utils.dart'; import 'package:quiz/Screens/QuizDashboard.dart'; import 'package:quiz/Screens/QuizSignUp.dart'; import 'package:quiz/utils/AppWidget.dart'; import 'package:quiz/utils/QuizColors.dart'; import 'package:quiz/utils/QuizConstant.dart'; import 'package:quiz/utils/QuizStrings.dart'; import 'package:quiz/utils/QuizWidget.dart'; class QuizSignIn extends StatefulWidget { static String tag = '/QuizSignIn'; @override _QuizSignInState createState() => _QuizSignInState(); } class _QuizSignInState extends State<QuizSignIn> { @override Widget build(BuildContext context) { changeStatusColor(quiz_app_background); return Scaffold( backgroundColor: quiz_app_background, body: SafeArea( child: SingleChildScrollView( child: Container( height: MediaQuery.of(context).size.height, color: quiz_app_background, child: Column( children: <Widget>[ SizedBox(height: 16), text(quiz_title_login, fontSize: textSizeNormal, fontFamily: fontBold), text(quiz_info_login, textColor: quiz_textColorSecondary, isLongText: true, isCentered: true).center(), Container( margin: EdgeInsets.all(24.0), decoration: boxDecoration(bgColor: quiz_white, color: quiz_white, showShadow: true, radius: 10), child: Column( children: <Widget>[ quizEditTextStyle(quiz_hint_your_email, isPassword: false), quizDivider(), quizEditTextStyle(quiz_hint_your_password), ], ), ), SizedBox(height: 30), Container( child: Column( children: <Widget>[ text(quiz_lbl_don_t_have_an_account), text(quiz_lbl_create_account, textColor: quiz_colorPrimary, fontFamily: fontSemibold), ], ), ).onTap(() { setState(() { QuizSignUp().launch(context); }); }), SizedBox( height: 10, ), Container( margin: EdgeInsets.all(24.0), child: quizButton( textContent: quiz_lbl_continue, onPressed: () { setState(() { QuizDashboard().launch(context); }); })) ], ), ), ), ), ); } }
0
mirrored_repositories/QuizApp-Flutter/lib
mirrored_repositories/QuizApp-Flutter/lib/Screens/QuizCreatePassword.dart
import 'package:flutter/material.dart'; import 'package:nb_utils/nb_utils.dart'; import 'package:quiz/Screens/QuizMobileVerify.dart'; import 'package:quiz/utils/AppWidget.dart'; import 'package:quiz/utils/QuizColors.dart'; import 'package:quiz/utils/QuizConstant.dart'; import 'package:quiz/utils/QuizStrings.dart'; import 'package:quiz/utils/QuizWidget.dart'; class QuizCreatePassword extends StatefulWidget { static String tag = '/QuizCreatePassword'; @override _QuizCreatePasswordState createState() => _QuizCreatePasswordState(); } class _QuizCreatePasswordState extends State<QuizCreatePassword> { var obscureText = true; @override void initState() { super.initState(); setState(() {}); } @override Widget build(BuildContext context) { changeStatusColor(quiz_app_background); return Scaffold( appBar: AppBar( title: text(quiz_lbl_Create_password, fontSize: textSizeLargeMedium, fontFamily: fontMedium), leading: Icon( Icons.arrow_back, color: quiz_colorPrimary, size: 30, ).onTap(() { Navigator.of(context).pop(); }), centerTitle: true, backgroundColor: quiz_app_background, elevation: 0.0, ), body: SafeArea( child: SingleChildScrollView( child: Container( height: MediaQuery.of(context).size.height, color: quiz_app_background, child: Column( children: <Widget>[ text(quiz_info_create_password, textColor: quiz_textColorSecondary, isLongText: true, isCentered: true).paddingOnly(left: 40, right: 40, top: 16), SizedBox(height: 20), Container( margin: EdgeInsets.all(24.0), decoration: boxDecoration(bgColor: quiz_white, color: quiz_white, showShadow: true, radius: 10), child: Column( children: <Widget>[ TextFormField( style: TextStyle(fontSize: textSizeMedium, fontFamily: fontMedium), obscureText: obscureText, decoration: InputDecoration( contentPadding: EdgeInsets.fromLTRB(16, 22, 16, 22), border: InputBorder.none, hintText: quiz_hint_your_password, labelStyle: primaryTextStyle(size: 20, color: quiz_textColorPrimary), suffix: text(obscureText ? "Show" : "Hide", textColor: quiz_textColorSecondary, fontSize: textSizeNormal, fontFamily: fontMedium).onTap(() { setState(() { obscureText = !obscureText; }); }), //suffixText: (obscureText ? "show" : "hide") ), ), ], ), ), SizedBox(height: 20), Container( child: Column( children: <Widget>[ text(quiz_lbl_already_have_an_account), text(quiz_lbl_sign_in, textColor: quiz_colorPrimary, textAllCaps: true), ], ), ).onTap(() { finish(context); }), SizedBox(height: 20), Container( margin: EdgeInsets.all(24.0), child: quizButton( textContent: quiz_lbl_continue, onPressed: () { setState(() { QuizMobileVerify().launch(context); }); }, ), ) ], ), ), ), ), ); } }
0
mirrored_repositories/QuizApp-Flutter/lib
mirrored_repositories/QuizApp-Flutter/lib/Screens/QuizVerifcation.dart
import 'package:flutter/material.dart'; import 'package:nb_utils/nb_utils.dart'; import 'package:quiz/Screens/RepoScreen.dart'; import 'package:quiz/utils/AppWidget.dart'; import 'package:quiz/utils/QuizColors.dart'; import 'package:quiz/utils/QuizConstant.dart'; import 'package:quiz/utils/QuizStrings.dart'; import 'package:quiz/utils/QuizWidget.dart'; class QuizVerification extends StatefulWidget { static String tag = '/QuizMobileVerification'; @override _QuizVerificationState createState() => _QuizVerificationState(); } class _QuizVerificationState extends State<QuizVerification> { @override Widget build(BuildContext context) { changeStatusColor(quiz_app_background); return Scaffold( appBar: AppBar( title: text(quiz_title_Verification, fontSize: textSizeLargeMedium, fontFamily: fontMedium), leading: Icon( Icons.arrow_back, color: quiz_colorPrimary, size: 30, ).onTap(() { Navigator.of(context).pop(); }), centerTitle: true, backgroundColor: quiz_app_background, elevation: 0.0, ), body: SafeArea( child: SingleChildScrollView( child: Container( height: MediaQuery.of(context).size.height, color: quiz_app_background, child: Column( children: <Widget>[ SizedBox(height: 20), text(quiz_info_Verification, textColor: quiz_textColorSecondary, isLongText: true, isCentered: true).center(), SizedBox(height: 20), PinEntryTextField(fields: 4, fontSize: textSizeLargeMedium).center(), SizedBox(height: 20), Container( child: Column( children: <Widget>[ text(quiz_lbl_did_not_receive_code), text(quiz_lbl_Resend, textColor: quiz_colorPrimary, textAllCaps: true), ], ), ).onTap(() {}), SizedBox(height: 20), Container( margin: EdgeInsets.all(24.0), child: quizButton( textContent: quiz_lbl_continue, onPressed: () { setState(() { RepoScreen().launch(context); }); }, ), ), ], ), ), ), ), ); } }
0
mirrored_repositories/QuizApp-Flutter/lib
mirrored_repositories/QuizApp-Flutter/lib/Screens/QuizSettings.dart
import 'package:flutter/material.dart'; import 'package:nb_utils/nb_utils.dart'; import 'package:quiz/Screens/RepoScreen.dart'; import 'package:quiz/utils/AppWidget.dart'; import 'package:quiz/utils/QuizColors.dart'; import 'package:quiz/utils/QuizStrings.dart'; class QuizSettings extends StatefulWidget { static String tag = '/QuizSetting'; @override _QuizSettingsState createState() => _QuizSettingsState(); } class _QuizSettingsState extends State<QuizSettings> { @override Widget build(BuildContext context) { changeStatusColor(quiz_app_background); return Scaffold( backgroundColor: quiz_app_background, appBar: AppBar( title: Text( quiz_lbl_setting, style: primaryTextStyle(size: 18, fontFamily: "Medium"), ), leading: Icon( Icons.arrow_back, color: quiz_colorPrimary, size: 30, ).onTap(() { Navigator.of(context).pop(); }), centerTitle: true, backgroundColor: quiz_app_background, elevation: 0.0, ), body: Column( children: <Widget>[ Expanded( child: SingleChildScrollView( child: Container( margin: EdgeInsets.all(20), child: Column( children: <Widget>[ SizedBox(height: 8), Container( decoration: BoxDecoration(color: quiz_white, borderRadius: BorderRadius.circular(8), boxShadow: defaultBoxShadow()), margin: EdgeInsets.only(bottom: 20), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ quizSettingOptionPattern1(Icons.person, quiz_lbl_edit_profile, quiz_username).onTap(() { setState(() { RepoScreen(enableAppbar: true).launch(context); }); }), quizSettingOptionPattern1(Icons.email, quiz_lbl_email, quiz_email).onTap(() { setState(() { RepoScreen(enableAppbar: true).launch(context); }); }), quizSettingOptionPattern1(Icons.vpn_key, quiz_lbl_password, quiz_sub_info_password).onTap(() { setState(() { RepoScreen(enableAppbar: true).launch(context); }); }), ], ), ), Container( decoration: BoxDecoration(color: quiz_white, borderRadius: BorderRadius.circular(8), boxShadow: defaultBoxShadow()), margin: EdgeInsets.only(bottom: 20), child: Column( children: <Widget>[ quizSettingOptionPattern2(Icons.star, quiz_lbl_scoreboard), quizSettingOptionPattern2(Icons.add_box, quiz_lbl_new_course), quizSettingOptionPattern2(Icons.notifications, quiz_lbl_study_reminder), ], ), ), Container( decoration: BoxDecoration(color: quiz_white, borderRadius: BorderRadius.circular(8), boxShadow: defaultBoxShadow()), margin: EdgeInsets.only(bottom: 20), child: Column( children: <Widget>[ quizSettingOptionPattern3(Icons.help, quiz_lbl_help).onTap(() { setState(() { RepoScreen(enableAppbar: true).launch(context); }); }), quizSettingOptionPattern3(Icons.security, quiz_lbl_privacy), quizSettingOptionPattern3(Icons.chat_bubble, quiz_lbl_contact_us).onTap(() { setState(() { RepoScreen(enableAppbar: true).launch(context); }); }), ], ), ), Text( quiz_lbl_logout, style: boldTextStyle(color: quiz_colorPrimary, size: 18), ).paddingAll(16).onTap(() { finish(context); }) ], ), ), ), ), ], ), ); } } Widget quizSettingOptionPattern1(var settingIcon, var heading, var info) { return Padding( padding: EdgeInsets.fromLTRB(16, 10, 16, 10), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Row( children: <Widget>[ Container( decoration: BoxDecoration(shape: BoxShape.circle, color: quiz_color_setting), width: 45, height: 45, padding: EdgeInsets.all(4), child: Icon( settingIcon, color: quiz_white, ), ), SizedBox( width: 16, ), Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Text(heading), Text( info, style: primaryTextStyle(color: quiz_textColorSecondary, size: 14), ) ], ), ], ), Icon( Icons.keyboard_arrow_right, color: quiz_icon_color, ) ], ), ); } Widget quizSettingOptionPattern2(var icon, var heading) { bool isSwitched1 = false; return Padding( padding: EdgeInsets.fromLTRB(16, 10, 16, 10), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Row( children: <Widget>[ Container( decoration: BoxDecoration(shape: BoxShape.circle, color: quiz_color_setting), width: 45, height: 45, padding: EdgeInsets.all(4), child: Icon( icon, color: quiz_white, ), ), SizedBox( width: 16, ), Text(heading), ], ), Switch( value: isSwitched1, onChanged: (value) { // setState(() { isSwitched1 = value; // }); }, activeTrackColor: quiz_colorPrimary, activeColor: quiz_view_color, ) ], ), ); } Widget quizSettingOptionPattern3(var icon, var heading) { return Padding( padding: EdgeInsets.fromLTRB(16, 10, 16, 10), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Row( children: <Widget>[ Container( decoration: BoxDecoration(shape: BoxShape.circle, color: quiz_color_setting), width: 45, height: 45, padding: EdgeInsets.all(4), child: Icon( icon, color: quiz_white, ), ), SizedBox( width: 16, ), Text(heading), ], ), Icon( Icons.keyboard_arrow_right, color: quiz_icon_color, ) ], ), ); }
0
mirrored_repositories/QuizApp-Flutter/lib
mirrored_repositories/QuizApp-Flutter/lib/Screens/RepoScreen.dart
import 'package:flutter/material.dart'; import 'package:nb_utils/nb_utils.dart'; import 'package:quiz/Screens/RepoButton.dart'; import 'package:quiz/utils/AppWidget.dart'; class RepoScreen extends StatefulWidget { final bool? enableAppbar; RepoScreen({this.enableAppbar = false}); @override _RepoScreenState createState() => _RepoScreenState(); } class _RepoScreenState extends State<RepoScreen> { @override void initState() { super.initState(); init(); } void init() async { // } @override void setState(fn) { if (mounted) super.setState(fn); } @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( body: Stack( children: [ Icon(Icons.arrow_back, size: 24).paddingAll(16).onTap(() { finish(context); }).visible(widget.enableAppbar!), SizedBox( width: context.width(), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: [ Container( decoration: boxDecorationDefault(shape: BoxShape.circle), child: commonCacheImageWidget( "images/quiz/ic_background.png", height: 180, ).cornerRadiusWithClipRRect(90)), 22.height, Text( 'This is UI is Still in Active Development.', style: boldTextStyle(size: 22), textAlign: TextAlign.center, ), 16.height, RepoButton(), ], ), ).paddingAll(16), ], ), ), ); } }
0
mirrored_repositories/QuizApp-Flutter/lib
mirrored_repositories/QuizApp-Flutter/lib/model/QuizModels.dart
class NewQuizModel { var quizName = ""; var totalQuiz = ""; var quizImage = ""; } class QuizTestModel { var heading = ""; var image = ""; var description = ""; var type = ""; var status = ""; } class QuizRecentSearchDataModel { var name = ""; } class QuizBadgesModel { var title = ""; var subtitle = ""; var img = ""; } class QuizScoresModel { var title = ""; var totalQuiz = ""; var img = ""; var scores = ""; } class QuizContactUsModel { var title = ""; var subtitle = ""; }
0
mirrored_repositories/QuizApp-Flutter/lib
mirrored_repositories/QuizApp-Flutter/lib/onBoardingScreens/components.dart
/* MIT License Copyright (c) 2024 Muhammad Fiaz Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import 'package:flutter/material.dart'; import 'package:quiz/onBoardingScreens/utils/colors.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../Screens/QuizSignIn.dart'; class GetStartBtn extends StatelessWidget { const GetStartBtn({ Key? key, required this.size, required this.textTheme, }) : super(key: key); final Size size; final TextTheme textTheme; @override Widget build(BuildContext context) { return GestureDetector( onTap: () async { // Get the SharedPreferences instance SharedPreferences prefs = await SharedPreferences.getInstance(); // Set the onboarding complete flag to true await prefs.setBool('onboarding_complete', true); // Navigate to the home page Navigator.pushReplacement( context, MaterialPageRoute(builder: (context) => QuizSignIn()), ); }, child: Container( margin: const EdgeInsets.only(top: 60), width: size.width / 1.5, height: size.height / 13, decoration: BoxDecoration( color: MyColors.btnColor, borderRadius: BorderRadius.circular(15)), child: Center( child: Text("Get Started now", style: textTheme.headline4), ), ), ); } } class SkipBtn extends StatelessWidget { const SkipBtn({ Key? key, required this.size, required this.textTheme, required this.onTap, }) : super(key: key); final Size size; final TextTheme textTheme; final VoidCallback onTap; @override Widget build(BuildContext context) { return Container( margin: const EdgeInsets.only(top: 60), width: size.width / 1.5, height: size.height / 13, decoration: BoxDecoration( border: Border.all( color: MyColors.btnBorderColor, width: 2, ), borderRadius: BorderRadius.circular(15)), child: InkWell( borderRadius: BorderRadius.circular(15.0), onTap: onTap, splashColor: MyColors.btnBorderColor, child: Center( child: Text("Skip", style: textTheme.headline3), ), ), ); } }
0
mirrored_repositories/QuizApp-Flutter/lib/onBoardingScreens
mirrored_repositories/QuizApp-Flutter/lib/onBoardingScreens/view/onBoardingScreen.dart
import 'package:animate_do/animate_do.dart'; import 'package:flutter/material.dart'; import 'package:smooth_page_indicator/smooth_page_indicator.dart'; import '../components.dart'; import '../model/items_model.dart'; import '../utils/colors.dart'; // OnBoardingScreens Controller class onBoardingScreenHome extends StatefulWidget { const onBoardingScreenHome({Key? key}) : super(key: key); @override State<onBoardingScreenHome> createState() => _HomePageState(); } class _HomePageState extends State<onBoardingScreenHome> { PageController pageController = PageController(initialPage: 0); int currentIndex = 0; @override void dispose() { pageController.dispose(); super.dispose(); } Widget animation( int index, int delay, Widget child, ) { if (index == 1) { return FadeInDown( delay: Duration(milliseconds: delay), child: child, ); } return FadeInUp( delay: Duration(milliseconds: delay), child: child, ); } @override Widget build(BuildContext context) { var size = MediaQuery.of(context).size; var textTheme = Theme.of(context).textTheme; return SafeArea( child: Scaffold( body: SizedBox( width: size.width, height: size.height, child: Column( children: [ /// --------------------------- Expanded( flex: 3, child: PageView.builder( controller: pageController, itemCount: listOfItems.length, onPageChanged: (newIndex) { setState(() { currentIndex = newIndex; }); }, physics: const BouncingScrollPhysics(), itemBuilder: ((context, index) { return SizedBox( width: size.width, height: size.height, child: Column( children: [ /// IMG Container( margin: const EdgeInsets.fromLTRB(15, 40, 15, 10), width: size.width, height: size.height / 2.5, child: animation( index, 100, Image.asset(listOfItems[index].img), ), ), /// TITLE TEXT Padding( padding: const EdgeInsets.only(top: 25, bottom: 15), child: animation( index, 300, Text( listOfItems[index].title, textAlign: TextAlign.center, style: textTheme.headline1?.copyWith( fontSize: 24, fontWeight: FontWeight.bold) ), )), /// SUBTITLE TEXT animation( index, 500, Text( listOfItems[index].subTitle, textAlign: TextAlign.center, style: textTheme.headline2?.copyWith(fontSize: 16), ), ), ], ), ); }), ), ), /// --------------------------- Expanded( flex: 1, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ /// PAGE INDICATOR SmoothPageIndicator( controller: pageController, count: listOfItems.length, effect: const ExpandingDotsEffect( spacing: 6.0, radius: 10.0, dotWidth: 10.0, dotHeight: 10.0, expansionFactor: 3.8, dotColor: Colors.grey, activeDotColor: MyColors.btnColor, ), onDotClicked: (newIndex) { setState(() { currentIndex = newIndex; pageController.animateToPage(newIndex, duration: const Duration(milliseconds: 500), curve: Curves.ease); }); }, ), currentIndex == 2 /// GET STARTED BTN ? GetStartBtn(size: size, textTheme: textTheme) /// SKIP BTN : SkipBtn( size: size, textTheme: textTheme, onTap: () { setState(() { pageController.animateToPage(2, duration: const Duration(milliseconds: 1000), curve: Curves.fastOutSlowIn); }); }, ) ], ), ), ], ), )), ); } }
0
mirrored_repositories/QuizApp-Flutter/lib/onBoardingScreens
mirrored_repositories/QuizApp-Flutter/lib/onBoardingScreens/model/items_model.dart
class Chat { final String title; final String subtitle; Chat({ required this.title, required this.subtitle, }); } class Items { final String img; final String title; final String subTitle; final Chat chat; Items({ required this.img, required this.title, required this.subTitle, required this.chat, }); } // onBoardingScreens Intro Contents for Quiz App List<Items> listOfItems = [ Items( img: "images/quiz/quiz_logo.jpg", title: "Challenge your friends", subTitle: "Engage in quiz challenges with your friends\nand family using our app.", chat: Chat( title: "Quiz Challenges", subtitle: "Challenge your best friends to quiz battles.", ), ), Items( img: "images/quiz/quiz_logo.jpg", title: "Join exciting quiz groups", subTitle: "Find and join groups that share your quiz\ninterests and participate together.", chat: Chat( title: "Quiz Groups", subtitle: "Join groups with quiz enthusiasts.", ), ), Items( img: "images/quiz/quiz_logo.jpg", title: "Discover quiz enthusiasts", subTitle: "Connect with new people who share your\npassion for quizzes around the world.", chat: Chat( title: "Quiz Connections", subtitle: "Discover and chat with fellow quiz enthusiasts.", ), ), ];
0
mirrored_repositories/QuizApp-Flutter/lib/onBoardingScreens
mirrored_repositories/QuizApp-Flutter/lib/onBoardingScreens/utils/colors.dart
import 'package:flutter/material.dart'; class MyColors{ static const Color titleTextColor = Color(0xFF504e9c); static const Color btnColor = Color(0xFF4786ec); static const Color btnBorderColor = Color.fromARGB(255, 183, 181, 252); static const Color subTitleTextColor = Color(0xFF9593a8); }
0
mirrored_repositories/QuizApp-Flutter/lib
mirrored_repositories/QuizApp-Flutter/lib/utils/QuizColors.dart
import 'package:flutter/material.dart'; const t8_colorPrimary = Color(0xFF5362FB); const t8_colorPrimaryDark = Color(0xFF3D50FC); const t8_colorAccent = Color(0xFF22D8CD); const t8_color_red = Color(0xFFF12727); const t8_textColorPrimary = Color(0xFF333333); const t8_textColorSecondary = Color(0xFF918F8F); const t8_app_background = Color(0xFFf3f5f9); const t8_view_color = Color(0xFFDADADA); const t8_white = Color(0xFFffffff); const t8_icon_color = Color(0xFF747474); const t8_color_green = Color(0xFF8BC34A); const t8_edit_background = Color(0xFFF5F4F4); const t8_light_gray = Color(0xFFCECACA); const t8_colors_dots = Color(0xFF009688); const t8_green = Color(0xFF00FF00); const t8_red = Color(0xFFFF0000); const t8_color_setting = Color(0xFFACB5FD); const t8_color_message = Color(0xFF5362FB); const t8_color_mail = Color(0xFF62D3AB); const t8_color_facebook = Color(0xFF4872FB); const t8_color_twitter = Color(0xFF2CB6F8); const t8_color_transparent = Color(0xFF00FFFFFF); const t8_ShadowColor = Color(0X95E9EBF0); const t8_form_google = Color(0xFFF13B19); const quiz_colorPrimary = Color(0xFF5362FB); const quiz_colorPrimaryDark = Color(0xFF3D50FC); const quiz_colorAccent = Color(0xFF22D8CD); const quiz_color_red = Color(0xFFF12727); const quiz_textColorPrimary = Color(0xFF333333); const quiz_textColorSecondary = Color(0xFF918F8F); const quiz_app_background = Color(0xFFf3f5f9); const quiz_view_color = Color(0xFFDADADA); const quiz_white = Color(0xFFffffff); const quiz_icon_color = Color(0xFF747474); const quiz_color_green = Color(0xFF8BC34A); const quiz_edit_background = Color(0xFFF5F4F4); const quiz_light_gray = Color(0xFFCECACA); const quiz_colors_dots = Color(0xFF009688); const quiz_green = Color(0xFF00FF00); const quiz_red = Color(0xFFFF0000); const quiz_color_setting = Color(0xFFACB5FD); const quiz_color_message = Color(0xFF5362FB); const quiz_color_mail = Color(0xFF62D3AB); const quiz_color_facebook = Color(0xFF4872FB); const quiz_color_twitter = Color(0xFF2CB6F8); const quiz_color_transparent = Color(0xFF00FFFFFF); const quiz_ShadowColor = Color(0X95E9EBF0); const quiz_form_google = Color(0xFFF13B19);
0
mirrored_repositories/QuizApp-Flutter/lib
mirrored_repositories/QuizApp-Flutter/lib/utils/QuizCard.dart
class Quiz { var option1; var option2; var option3; var option4; var cardImage; double? topMargin; Quiz(String imagePath, String o1, String o2, String o3, String o4, double marginTop) { option1 = o1; option2 = o2; option3 = o3; option4 = o4; cardImage = imagePath; topMargin = marginTop; } }
0
mirrored_repositories/QuizApp-Flutter/lib
mirrored_repositories/QuizApp-Flutter/lib/utils/QuizImages.dart
const Url="https://github.com/muhammad-fiaz/QuizApp-Flutter/assets/75434191/06e28a7a-6239-4a3f-af88-4a49b272ce9e"; const quiz_ic_communication = "$Url"; const quiz_ic_communication2 = "$Url"; const quiz_ic_course1 = "$Url"; const quiz_ic_course2 = "$Url"; const quiz_ic_course3 = "$Url"; const quiz_ic_info = "$Url"; const quiz_ic_java = "$Url"; const quiz_ic_marketing = "$Url"; const quiz_ic_notification = "$Url"; const quiz_ic_study1 = "$Url"; const quiz_ic_study2 = "$Url"; const quiz_ic_quiz1 = "images/quiz/quiz_ic_quiz1.png"; const quiz_ic_quiz2 = "images/quiz/quiz_ic_quiz2.png"; const quiz_ic_quiz = "images/quiz/quiz_ic_quiz.svg"; const quiz_ic_homes = "images/quiz/quiz_ic_home.svg"; const quiz_ic_user = "images/quiz/quiz_ic_user.svg"; const quiz_ic_facebook = "images/quiz/quiz_ic_facebook.svg"; const quiz_ic_google = "images/quiz/quiz_ic_google.svg"; const quiz_ic_mail = "images/quiz/quiz_ic_mail.svg"; const quiz_ic_twitter = "images/quiz/quiz_ic_twitter.svg"; const Quiz_ic_Grid = "images/quiz/quiz_ic_grid.png"; const Quiz_ic_List = "images/quiz/quiz_ic_list.png"; const quiz_img_People1 = "$Url"; const quiz_img_People2 = "$Url"; const quiz_ic_list1 = "images/quiz/quiz_ic_list1.png"; const quiz_ic_list2 = "images/quiz/quiz_ic_list2.png"; const quiz_ic_list3 = "images/quiz/quiz_ic_list3.png"; const quiz_ic_list4 = "images/quiz/quiz_ic_list4.png"; const quiz_ic_list5 = "images/quiz/quiz_ic_list5.png";
0
mirrored_repositories/QuizApp-Flutter/lib
mirrored_repositories/QuizApp-Flutter/lib/utils/QuizDataGenerator.dart
import 'package:quiz/model/QuizModels.dart'; import 'package:quiz/utils/QuizImages.dart'; List<NewQuizModel> getQuizData() { List<NewQuizModel> list = []; NewQuizModel model1 = NewQuizModel(); model1.quizName = "Biology & The \nScientific Method"; model1.totalQuiz = "15 Quiz"; model1.quizImage = quiz_ic_study1; NewQuizModel model2 = NewQuizModel(); model2.quizName = "Geography Basics \nMethods"; model2.totalQuiz = "5 Quiz"; model2.quizImage = quiz_ic_study2; NewQuizModel model3 = NewQuizModel(); model3.quizName = "Java Basics \nOOPs Concept"; model3.totalQuiz = "10 Quiz"; model3.quizImage = quiz_ic_course3; NewQuizModel model4 = NewQuizModel(); model4.quizName = "Art and \nPainting Basic"; model4.totalQuiz = "10 Quiz"; model4.quizImage = quiz_ic_course1; NewQuizModel model5 = NewQuizModel(); model5.quizName = "Communication Basic"; model5.totalQuiz = "10 Quiz"; model5.quizImage = quiz_ic_communication; NewQuizModel model6 = NewQuizModel(); model6.quizName = "Investment and \nTypes"; model6.totalQuiz = "10 Quiz"; model6.quizImage = quiz_ic_course2; list.add(model1); list.add(model3); list.add(model6); list.add(model4); list.add(model5); list.add(model2); return list; } List<QuizTestModel> quizGetData() { List<QuizTestModel> list = []; QuizTestModel model1 = QuizTestModel(); model1.heading = "The Scientific Method"; model1.image = quiz_ic_quiz1; model1.type = "Quiz 1"; model1.description = "Let's put your memory on our first topic to test."; model1.status = "true"; QuizTestModel model2 = QuizTestModel(); model2.heading = "Introduction to Biology"; model2.image = quiz_ic_quiz2; model2.type = "Flashcards"; model2.description = "Complete the above test to unlock this one."; model2.status = "false"; QuizTestModel model3 = QuizTestModel(); model3.heading = "Controlled Experiments"; model3.image = quiz_ic_quiz1; model3.type = "Quiz 2"; model3.description = "Let's put your memory on our first topic to test."; model3.status = "false"; list.add(model1); list.add(model2); list.add(model3); return list; } List<QuizBadgesModel> quizBadgesData() { List<QuizBadgesModel> list = []; QuizBadgesModel model1 = QuizBadgesModel(); model1.title = "Achiever"; model1.subtitle = "Complete an exercise"; model1.img = quiz_ic_list2; QuizBadgesModel model2 = QuizBadgesModel(); model2.title = "Perectionistf"; model2.subtitle = "Finish All lesson of chapter"; model2.img = quiz_ic_list5; QuizBadgesModel model3 = QuizBadgesModel(); model3.title = "Scholar"; model3.subtitle = "Study two Cources"; model3.img = quiz_ic_list3; QuizBadgesModel model4 = QuizBadgesModel(); model4.title = "Champion"; model4.subtitle = "Finish #1 in Scoreboard"; model4.img = quiz_ic_list4; QuizBadgesModel model5 = QuizBadgesModel(); model5.title = "Focused"; model5.subtitle = "Study every day for 30 days"; model5.img = quiz_ic_list5; list.add(model1); list.add(model2); list.add(model3); list.add(model4); list.add(model5); return list; } List<QuizScoresModel> quizScoresData() { List<QuizScoresModel> list = []; QuizScoresModel model1 = QuizScoresModel(); model1.title = "Biology Basics"; model1.totalQuiz = "20 Quiz"; model1.img = quiz_ic_course1; model1.scores = "30/50"; QuizScoresModel model2 = QuizScoresModel(); model2.title = "Java Basics"; model2.totalQuiz = "30 Quiz"; model2.img = quiz_ic_course2; model2.scores = "30/50"; QuizScoresModel model3 = QuizScoresModel(); model3.title = "Art & Painting Basics"; model3.totalQuiz = "10 Quiz"; model3.img = quiz_ic_course3; model3.scores = "10/50"; list.add(model1); list.add(model2); list.add(model3); return list; } List<QuizContactUsModel> quizContactUsData() { List<QuizContactUsModel> list = []; QuizContactUsModel model1 = QuizContactUsModel(); model1.title = "Call Request"; model1.subtitle = "+00 356 646 234"; QuizContactUsModel model2 = QuizContactUsModel(); model2.title = "Email"; model2.subtitle = "Response within 24 business hours"; list.add(model1); list.add(model2); return list; }
0
mirrored_repositories/QuizApp-Flutter/lib
mirrored_repositories/QuizApp-Flutter/lib/utils/QuizConstant.dart
/*fonts*/ const fontRegular = 'Regular'; const fontMedium = 'Medium'; const fontSemibold = 'Semibold'; const fontBold = 'Bold'; /* font sizes*/ const textSizeSmall = 12.0; const textSizeSMedium = 14.0; const textSizeMedium = 16.0; const textSizeLargeMedium = 18.0; const textSizeNormal = 20.0; const textSizeLarge = 24.0; const textSizeXLarge = 28.0; const textSizeXXLarge = 30.0; const spacing_middle = 10.0; const spacing_standard_new = 16.0; const BaseUrl = 'https://github.com/muhammad-fiaz/QuizApp-Flutter';
0
mirrored_repositories/QuizApp-Flutter/lib
mirrored_repositories/QuizApp-Flutter/lib/utils/QuizCardDetail.dart
import 'package:flutter/material.dart'; // ignore: must_be_immutable class QuizCardDetails extends StatefulWidget { int index; String imageAddress; String? placeDetails; QuizCardDetails(this.imageAddress, this.index); @override State<StatefulWidget> createState() => QuizCardDetailsState(imageAddress, index); } class QuizCardDetailsState extends State<QuizCardDetails> { int index; String imageAddress; late String placeDetails; QuizCardDetailsState(this.imageAddress, this.index); @override void initState() { super.initState(); setState(() { getData(index); }); } getData(value) { switch (value) { case 0: placeDetails = 'Mussoorie, located around an hour from Derahdun in Uttarakhand, is a popular weekend destination for north Indians, as well as honeymooners. One of the reasons for Mussoories popularity is that it has a lot of facilities developed especially for tourists. Take a cable car to Gun Hill, enjoy a beautiful nature walk along Camels Back Road, have a picnic at Kempty Falls, or ride a horse up to Lal Tibba (the highest peak in Mussoorie). Mussoorie also offers a superb view of the Himalayas.'; break; case 1: placeDetails = "Manali, in Himachal Pradesh, is one of the top adventure travel destinations in India.Manali, with its soothing backdrop of the Himalayas, offers a blend of tranquility and adventure that makes it one of northern India's most popular destinations. Although it's a popular place to go off on treks, you can do as little or as much as you want there. Located in the Kullu Valley of Himachal Pradesh, it's bordered by cool pine forest and the raging Beas River, which give it a special energy."; break; case 2: placeDetails = "Sikkim's capital, Gangtok, sits along a cloudy mountain ridge about 5,500 feet above sea level. Sikkim only became part of India in 1975. Before that, it was a small independent Buddhist kingdom with its own monarchy after the end of British rule. Gangtok is a popular base for travel throughout the state, particularly with trekkers. It's a well-organized and clean city with strict littering, traffic and tobacco laws. Attractions include monasteries, viewpoints, a cable car, and a zoo that houses rare animals rescued from traders and poachers."; break; case 3: placeDetails = "Darjeeling is also famous for its lush tea gardens. In addition, it's blessed with a stunning view of Mount Kanchenjunga, the world's third highest peak. Some of Darjeeling's most popular attractions include historic toy train, monasteries, botanical gardens, a zoo, and the Darjeeling-Rangeet Valley Passenger Ropeway (the longest aerial tramway in Asia). Darjeeling is a great place to walk around and explore the tea estates, villages, and markets. "; break; case 4: placeDetails = "The hill station of Nainital, in the Kumaon region of Uttarakhand, was a popular summer retreat for the British during the time they ruled India. It features the serene, emerald-colored Naini Lake and an action-filled strip called The Mall, lined with restaurants, shops, hotels, and markets. Enjoy one of the many forest walks, explore the surrounding area on horseback, or relax on a boat in the lake."; break; } } @override Widget build(BuildContext context) { return Scaffold( body: ListView( children: <Widget>[ Stack( children: <Widget>[ Container( height: 800.0, width: double.infinity, ), Container( padding: EdgeInsets.all(10.0), height: 500.0, width: double.infinity, decoration: BoxDecoration( borderRadius: BorderRadius.only( bottomLeft: Radius.circular(20.0), bottomRight: Radius.circular(20.0), ), image: DecorationImage( image: NetworkImage(imageAddress), fit: BoxFit.fill, )), ), Positioned( top: 420.0, left: 10.0, right: 10.0, child: Material( elevation: 10.0, borderRadius: BorderRadius.circular(20.0), child: Container( height: 380.0, decoration: BoxDecoration( //borderRadius: BorderRadius.circular(20.0) ), padding: EdgeInsets.only( left: 20.0, right: 10.0, top: 20.0, ), child: Text( placeDetails, textAlign: TextAlign.left, style: TextStyle(fontSize: 20.0, fontStyle: FontStyle.italic), ), ), ), ) ], ), ], ), ); } }
0
mirrored_repositories/QuizApp-Flutter/lib
mirrored_repositories/QuizApp-Flutter/lib/utils/QuizStrings.dart
const quiz_lbl_continue = "CONTINUE"; const quiz_hint_your_password = "Your Password"; const quiz_hint_your_email = "Your Email"; const quiz_info_login = "Enter your login details to \n access your account"; const quiz_info_sign_up = "Start by entering your email \n address below."; const quiz_lbl_forgot = "Forgot"; const quiz_lbl_show = "Show"; const quiz_lbl_allow = "Allow"; const quiz_title_login = "Log In"; const quiz_lbl_don_t_have_an_account = "Don\'t have an account?"; const quiz_lbl_create_account = "CREATE ACCOUNT"; const quiz_title_Create_account = "Create Account"; const quiz_info_create_password = "Your password must have at \n least one symbol &amp; 8 or \n more characters."; const quiz_lbl_already_have_an_account = "Already have an account?"; const quiz_lbl_sign_in = "Sign In"; const quiz_lbl_skip = "SKIP"; const quiz_lbl_let_started = "Let's Get Started"; const quiz_info_let_started = "Enter your mobile number to \n enable 2- step verification "; const quiz_hint_Mobile_Number = "Mobile Number"; const quiz_lbl_Create_password = "Create Password"; const quiz_title_Verification = "Verification"; const quiz_lbl_did_not_receive_code = "I didn't recevice a code"; const quiz_lbl_Resend = "Resend"; const quiz_info_Verification = "we texted you a code to verify \n your phone number"; const quiz_lbl_notifications = "Notifications"; const quiz_info_notification = "Stay notified about new course \n updates, scoreboard states and \n new friend follows."; const quiz_lbl_new_quiz = "New Quiz"; const quiz_lbl_view_all = "View all"; const quiz_lbl_search = "Search"; const quiz_lbl_what_would_you_like_to_learn_n_today_search_below = "What would you like to learn \n today? Search below."; const quiz_lbl_hi_antonio = "Hi, User!"; const quiz_title_new_account = "New Account"; const quiz_title_bottom_navigation = "Bottom Navigation"; const quiz_lbl_biology_basics = "Biology basics"; const quiz_lbl_biology_amp_scientific_method = "Biology & The \n Scientific Method"; const quiz_text_4_to_8_lesson = "4 to 8 lesson"; const quiz_lbl_begin = "Begin"; const quiz_lbl_setting = "Settings"; const quiz_lbl_edit_profile = "Edit Profile"; const quiz_username = "User Name"; const quiz_lbl_email = "Email"; const quiz_email = "[email protected]"; const quiz_lbl_password = "Password"; const quiz_sub_info_password = "updated 2 week ago"; const quiz_lbl_scoreboard = "Scoreboard"; const quiz_lbl_new_course = "New Courses"; const quiz_lbl_study_reminder = "Study Reminder"; const quiz_lbl_help = "Help Center"; const quiz_lbl_privacy = "Privacy & Terms"; const quiz_lbl_contact_us = "Contact Us"; const quiz_lbl_logout = "Log out"; const quiz_lbl = "User Name"; const quiz_lbl_Xp = "1,53,675 XP"; const Quiz_lbl_Edit_Profile = "Edit Profile"; const quiz_hint_First_name = "Your First Name"; const quiz_hint_Last_name = "Your Last Name"; const quiz_hint_Mobile_no = "Your Mobile Number"; const quiz_Save_Profile = "SAVE PROFILE"; const quiz_lbl_Update_email = "Update Email"; const quiz_info_Update_email = "Enter your new email \n address below"; const quiz_lbl_email_Verify = "we will send an email to verify \n your email address"; const quiz_lbl_save = "SAVE"; const quiz_lbl_Change_password = "Change Password"; const quiz_hint_Old_Password = "Old Password"; const quiz_hint_new_Password = "New Password"; const quiz_hint_confirm_password = "Confirm Password"; const quiz_lbl_Help_Center = "Help Center"; const quiz_hint_Description = "Description"; const quiz_lbl_Contact_us = "Contact Us"; const quiz_lbl_Badges = "BADGES"; const quiz_lbl_Scores = "SCORES"; const quiz_lbl_All = "ALL"; const quiz_lbl_Completed = "COMPLETED"; const quiz_lbl_Submit = "SUBMIT"; const quiz_Successfully_Save_Profile = "Successfully Save Profile"; const quiz_Successfully_Email_Updated = "Successfully Email Updated"; const quiz_Password_Updated = "Password Updated"; const quiz_Thank_you_Successfully_Added = "Thank you Successfully Added"; const quiz_Submitted = "Submitted";
0
mirrored_repositories/QuizApp-Flutter/lib
mirrored_repositories/QuizApp-Flutter/lib/utils/AppWidget.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:html/parser.dart'; import 'package:nb_utils/nb_utils.dart'; Widget text( String? text, { var fontSize = 18.0, Color? textColor, var fontFamily, var isCentered = false, var maxLine = 1, var latterSpacing = 0.5, bool textAllCaps = false, var isLongText = false, bool lineThrough = false, }) { return Text( textAllCaps ? text!.toUpperCase() : text!, textAlign: isCentered ? TextAlign.center : TextAlign.start, maxLines: isLongText ? null : maxLine, overflow: TextOverflow.ellipsis, style: TextStyle( fontFamily: fontFamily, fontSize: fontSize, color: textColor ?? textSecondaryColor, height: 1.5, letterSpacing: latterSpacing, decoration: lineThrough ? TextDecoration.lineThrough : TextDecoration.none, ), ); } BoxDecoration boxDecoration({double radius = 2, Color color = Colors.transparent, Color? bgColor, var showShadow = false}) { return BoxDecoration( color: bgColor, boxShadow: showShadow ? defaultBoxShadow(shadowColor: shadowColorGlobal) : [BoxShadow(color: Colors.transparent)], border: Border.all(color: color), borderRadius: BorderRadius.all(Radius.circular(radius)), ); } void changeStatusColor(Color color) async { setStatusBarColor(color); } Widget commonCacheImageWidget(String? url, {double? height, double? width, BoxFit? fit}) { if (url.validate().startsWith('http')) { if (isMobile) { return CachedNetworkImage( placeholder: placeholderWidgetFn() as Widget Function(BuildContext, String)?, imageUrl: '$url', height: height, width: width, fit: fit ?? BoxFit.cover, errorWidget: (_, __, ___) { return SizedBox(height: height, width: width); }, ); } else { return Image.network(url!, height: height, width: width, fit: fit ?? BoxFit.cover); } } else { return Image.asset(url!, height: height, width: width, fit: fit ?? BoxFit.cover); } } class CustomTheme extends StatelessWidget { final Widget? child; CustomTheme({required this.child}); @override Widget build(BuildContext context) { return Theme( data: ThemeData.light(), child: child!, ); } } Widget? Function(BuildContext, String) placeholderWidgetFn() => (_, s) => placeholderWidget(); Widget placeholderWidget() => Image.asset('images/quiz/empty_image_placeholder.jpg', fit: BoxFit.cover); String parseHtmlString(String? htmlString) { return parse(parse(htmlString).body!.text).documentElement!.text; }
0
mirrored_repositories/QuizApp-Flutter/lib
mirrored_repositories/QuizApp-Flutter/lib/utils/QuizWidget.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:fluttertoast/fluttertoast.dart'; import 'package:nb_utils/nb_utils.dart'; import 'package:quiz/utils/AppWidget.dart'; import 'package:quiz/utils/QuizColors.dart'; import 'QuizConstant.dart'; TextFormField quizEditTextStyle(var hintText, {isPassword = true}) { return TextFormField( style: TextStyle(fontSize: textSizeMedium, fontFamily: fontRegular), obscureText: isPassword, decoration: InputDecoration( contentPadding: EdgeInsets.fromLTRB(16, 22, 16, 22), hintText: hintText, border: InputBorder.none, hintStyle: TextStyle(color: quiz_textColorSecondary), ), ); } Divider quizDivider() { return Divider( height: 1, color: t8_view_color, thickness: 1, ); } // ignore: must_be_immutable, camel_case_types class quizButton extends StatefulWidget { var textContent; // var icon; VoidCallback onPressed; quizButton({ required this.textContent, required this.onPressed, // @required this.icon, }); @override quizButtonState createState() => quizButtonState(); } // ignore: camel_case_types class quizButtonState extends State<quizButton> { @override Widget build(BuildContext context) { return GestureDetector( onTap: widget.onPressed, child: Container( decoration: boxDecoration(bgColor: quiz_colorPrimary, radius: 16), padding: EdgeInsets.fromLTRB(16, 10, 16, 10), child: Stack( alignment: Alignment.center, children: <Widget>[ Center( child: text(widget.textContent, textColor: t8_white, fontFamily: fontMedium, textAllCaps: false), ), Align( alignment: Alignment.topRight, child: Container( decoration: BoxDecoration(shape: BoxShape.circle, color: quiz_colorPrimaryDark), width: 35, height: 35, child: Padding( padding: const EdgeInsets.all(8.0), child: Icon( Icons.arrow_forward, color: t8_white, size: 20, ), ), ), ), ], )), ); } } // ignore: must_be_immutable, camel_case_types class quizTopBar extends StatefulWidget { var titleName; quizTopBar(var this.titleName); @override State<StatefulWidget> createState() { return quizTopBarState(); } } // ignore: camel_case_types class quizTopBarState extends State<quizTopBar> { @override Widget build(BuildContext context) { return SafeArea( child: Container( width: MediaQuery.of(context).size.width, height: 60, child: Row( children: <Widget>[ IconButton( icon: Icon(Icons.arrow_back), color: t8_colorPrimary, onPressed: () { finish(context); }, ), Center( child: Text( widget.titleName, maxLines: 2, style: TextStyle(fontFamily: fontBold, fontSize: 22, color: t8_textColorPrimary), ).center(), ) ], ), ), ); } } Container quizHeaderText(var text) { return Container( margin: EdgeInsets.only(top: 16), child: Text( text, maxLines: 2, style: TextStyle(fontFamily: fontBold, fontSize: 22, color: t8_textColorPrimary), ), ); } class PinEntryTextField extends StatefulWidget { final String? lastPin; final int fields; final onSubmit; final fieldWidth; final fontSize; final isTextObscure; final showFieldAsBox; PinEntryTextField({this.lastPin, this.fields = 4, this.onSubmit, this.fieldWidth = 40.0, this.fontSize = 16.0, this.isTextObscure = false, this.showFieldAsBox = false}) : assert(fields > 0); @override State createState() { return PinEntryTextFieldState(); } } class PinEntryTextFieldState extends State<PinEntryTextField> { late List<String?> _pin; late List<FocusNode?> _focusNodes; late List<TextEditingController?> _textControllers; Widget textfields = Container(); @override void initState() { super.initState(); _pin = List<String?>.filled(widget.fields, null, growable: false); _focusNodes = List<FocusNode?>.filled(widget.fields, null, growable: false); _textControllers = List<TextEditingController?>.filled(widget.fields, null, growable: false); WidgetsBinding.instance!.addPostFrameCallback((_) { setState(() { if (widget.lastPin != null) { for (var i = 0; i < widget.lastPin!.length; i++) { _pin[i] = widget.lastPin![i]; } } textfields = generateTextFields(context); }); }); } @override void dispose() { _textControllers.forEach((TextEditingController? t) => t!.dispose()); super.dispose(); } Widget generateTextFields(BuildContext context) { List<Widget> textFields = List.generate(widget.fields, (int i) { return buildTextField(i, context); }); if (_pin.first != null) { FocusScope.of(context).requestFocus(_focusNodes[0]); } return Row(mainAxisAlignment: MainAxisAlignment.center, verticalDirection: VerticalDirection.down, children: textFields); } void clearTextFields() { _textControllers.forEach((TextEditingController? tEditController) => tEditController!.clear()); _pin.clear(); } Widget buildTextField(int i, BuildContext context) { if (_focusNodes[i] == null) { _focusNodes[i] = FocusNode(); } if (_textControllers[i] == null) { _textControllers[i] = TextEditingController(); if (widget.lastPin != null) { _textControllers[i]!.text = widget.lastPin![i]; } } _focusNodes[i]!.addListener(() { if (_focusNodes[i]!.hasFocus) {} }); return Container( width: widget.fieldWidth, margin: EdgeInsets.only(right: 10.0), child: TextField( controller: _textControllers[i], keyboardType: TextInputType.number, textAlign: TextAlign.center, maxLength: 1, style: TextStyle(color: Colors.black, fontFamily: fontMedium, fontSize: widget.fontSize), focusNode: _focusNodes[i], obscureText: widget.isTextObscure, decoration: InputDecoration(counterText: "", border: widget.showFieldAsBox ? OutlineInputBorder(borderSide: BorderSide(width: 2.0)) : null), onChanged: (String str) { setState(() { _pin[i] = str; }); if (i + 1 != widget.fields) { _focusNodes[i]!.unfocus(); if (_pin[i] == '') { FocusScope.of(context).requestFocus(_focusNodes[i - 1]); } else { FocusScope.of(context).requestFocus(_focusNodes[i + 1]); } } else { _focusNodes[i]!.unfocus(); if (_pin[i] == '') { FocusScope.of(context).requestFocus(_focusNodes[i - 1]); } } if (_pin.every((String? digit) => digit != null && digit != '')) { widget.onSubmit(_pin.join()); } }, onSubmitted: (String str) { if (_pin.every((String? digit) => digit != null && digit != '')) { widget.onSubmit(_pin.join()); } }, ), ); } @override Widget build(BuildContext context) { return textfields; } } showToast(String caption) { Fluttertoast.showToast(msg: caption, toastLength: Toast.LENGTH_LONG, gravity: ToastGravity.BOTTOM, backgroundColor: getColorFromHex("5362FB"), textColor: quiz_white, fontSize: 16.0); }
0
mirrored_repositories/QuizApp-Flutter/lib/utils
mirrored_repositories/QuizApp-Flutter/lib/utils/percent_indicator/circular_percent_indicator.dart
//import 'dart:math'; import 'dart:math' as math; import 'package:flutter/material.dart'; enum CircularStrokeCap { butt, round, square } enum ArcType { HALF, FULL, } // ignore: must_be_immutable class CircularPercentIndicator extends StatefulWidget { ///Percent value between 0.0 and 1.0 final double? percent; final double radius; ///Width of the progress bar of the circle final double lineWidth; ///Width of the unfilled background of the progress bar final double backgroundWidth; ///Color of the background of the circle , default = transparent final Color fillColor; ///First color applied to the complete circle final Color backgroundColor; Color? get progressColor => _progressColor; Color? _progressColor; ///true if you want the circle to have animation final bool animation; ///duration of the animation in milliseconds, It only applies if animation attribute is true final int animationDuration; ///widget at the top of the circle final Widget? header; ///widget at the bottom of the circle final Widget? footer; ///widget inside the circle final Widget? center; final LinearGradient? linearGradient; ///The kind of finish to place on the end of lines drawn, values supported: butt, round, square final CircularStrokeCap? circularStrokeCap; ///the angle which the circle will start the progress (in degrees, eg: 0.0, 45.0, 90.0) final double startAngle; /// set true if you want to animate the linear from the last percent value you set final bool animateFromLastPercent; /// set false if you don't want to preserve the state of the widget final bool addAutomaticKeepAlive; /// set the arc type final ArcType? arcType; /// set a circular background color when use the arcType property final Color? arcBackgroundColor; /// set true when you want to display the progress in reverse mode final bool reverse; /// Creates a mask filter that takes the progress shape being drawn and blurs it. final MaskFilter? maskFilter; /// set a circular curve animation type final Curve curve; /// set true when you want to restart the animation, it restarts only when reaches 1.0 as a value /// defaults to false final bool restartAnimation; CircularPercentIndicator( {Key? key, this.percent = 0.0, this.lineWidth = 5.0, this.startAngle = 0.0, required this.radius, this.fillColor = Colors.transparent, this.backgroundColor = const Color(0xFFB8C7CB), Color? progressColor, this.backgroundWidth = -1, //negative values ignored, replaced with lineWidth this.linearGradient, this.animation = false, this.animationDuration = 500, this.header, this.footer, this.center, this.addAutomaticKeepAlive = true, this.circularStrokeCap, this.arcBackgroundColor, this.arcType, this.animateFromLastPercent = false, this.reverse = false, this.curve = Curves.linear, this.maskFilter, this.restartAnimation = false}) : super(key: key) { if (linearGradient != null && progressColor != null) { throw ArgumentError('Cannot provide both linearGradient and progressColor'); } _progressColor = progressColor ?? Colors.red; assert(startAngle >= 0.0); if (percent! < 0.0 || percent! > 1.0) { throw Exception("Percent value must be a double between 0.0 and 1.0"); } if (arcType == null && arcBackgroundColor != null) { throw ArgumentError('arcType is required when you arcBackgroundColor'); } } @override _CircularPercentIndicatorState createState() => _CircularPercentIndicatorState(); } class _CircularPercentIndicatorState extends State<CircularPercentIndicator> with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin { AnimationController? _animationController; late Animation _animation; double? _percent = 0.0; @override void dispose() { if (_animationController != null) { _animationController!.dispose(); } super.dispose(); } @override void initState() { if (widget.animation) { _animationController = AnimationController(vsync: this, duration: Duration(milliseconds: widget.animationDuration)); _animation = Tween(begin: 0.0, end: widget.percent).animate( CurvedAnimation(parent: _animationController!, curve: widget.curve), )..addListener(() { setState(() { _percent = _animation.value; }); if (widget.restartAnimation && _percent == 1.0) { _animationController!.repeat(min: 0, max: 1.0); } }); _animationController!.forward(); } else { _updateProgress(); } super.initState(); } @override void didUpdateWidget(CircularPercentIndicator oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.percent != widget.percent || oldWidget.startAngle != widget.startAngle) { if (_animationController != null) { _animationController!.duration = Duration(milliseconds: widget.animationDuration); _animation = Tween(begin: widget.animateFromLastPercent ? oldWidget.percent : 0.0, end: widget.percent).animate( CurvedAnimation(parent: _animationController!, curve: widget.curve), ); _animationController!.forward(from: 0.0); } else { _updateProgress(); } } } _updateProgress() { setState(() { _percent = widget.percent; }); } @override Widget build(BuildContext context) { super.build(context); List<Widget>? items = []; if (widget.header != null) { items.add(widget.header!); } items.add(Container( height: widget.radius + widget.lineWidth, width: widget.radius, child: CustomPaint( painter: CirclePainter( progress: _percent! * 360, progressColor: widget.progressColor, backgroundColor: widget.backgroundColor, startAngle: widget.startAngle, circularStrokeCap: widget.circularStrokeCap, radius: (widget.radius / 2) - widget.lineWidth / 2, lineWidth: widget.lineWidth, backgroundWidth: //negative values ignored, replaced with lineWidth widget.backgroundWidth >= 0.0 ? (widget.backgroundWidth) : widget.lineWidth, arcBackgroundColor: widget.arcBackgroundColor, arcType: widget.arcType, reverse: widget.reverse, linearGradient: widget.linearGradient, maskFilter: widget.maskFilter), child: (widget.center != null) ? Center(child: widget.center) : Container(), ))); if (widget.footer != null) { items.add(widget.footer!); } return Material( color: widget.fillColor, child: Container( child: Column( mainAxisAlignment: MainAxisAlignment.center, mainAxisSize: MainAxisSize.min, children: items, ), ), ); } @override bool get wantKeepAlive => widget.addAutomaticKeepAlive; } class CirclePainter extends CustomPainter { final Paint _paintBackground = Paint(); final Paint _paintLine = Paint(); final Paint _paintBackgroundStartAngle = Paint(); final double? lineWidth; final double? backgroundWidth; final double? progress; final double radius; final Color? progressColor; final Color? backgroundColor; final CircularStrokeCap? circularStrokeCap; final double startAngle; final LinearGradient? linearGradient; final Color? arcBackgroundColor; final ArcType? arcType; final bool? reverse; final MaskFilter? maskFilter; CirclePainter( {this.lineWidth, this.backgroundWidth, this.progress, required this.radius, this.progressColor, this.backgroundColor, this.startAngle = 0.0, this.circularStrokeCap = CircularStrokeCap.round, this.linearGradient, this.reverse, this.arcBackgroundColor, this.arcType, this.maskFilter}) { _paintBackground.color = backgroundColor!; _paintBackground.style = PaintingStyle.stroke; _paintBackground.strokeWidth = backgroundWidth!; if (arcBackgroundColor != null) { _paintBackgroundStartAngle.color = arcBackgroundColor!; _paintBackgroundStartAngle.style = PaintingStyle.stroke; _paintBackgroundStartAngle.strokeWidth = lineWidth!; if (circularStrokeCap == CircularStrokeCap.round) { _paintBackgroundStartAngle.strokeCap = StrokeCap.round; } else if (circularStrokeCap == CircularStrokeCap.butt) { _paintBackgroundStartAngle.strokeCap = StrokeCap.butt; } else { _paintBackgroundStartAngle.strokeCap = StrokeCap.square; } } _paintLine.color = progressColor!; _paintLine.style = PaintingStyle.stroke; _paintLine.strokeWidth = lineWidth!; if (circularStrokeCap == CircularStrokeCap.round) { _paintLine.strokeCap = StrokeCap.round; } else if (circularStrokeCap == CircularStrokeCap.butt) { _paintLine.strokeCap = StrokeCap.butt; } else { _paintLine.strokeCap = StrokeCap.square; } } @override void paint(Canvas canvas, Size size) { final center = Offset(size.width / 2, size.height / 2); canvas.drawCircle(center, radius, _paintBackground); if (maskFilter != null) { _paintLine.maskFilter = maskFilter; } if (linearGradient != null) { /* _paintLine.shader = SweepGradient( center: FractionalOffset.center, startAngle: math.radians(-90.0 + startAngle), endAngle: math.radians(progress), //tileMode: TileMode.mirror, colors: linearGradient.colors) .createShader( Rect.fromCircle( center: center, radius: radius, ), );*/ _paintLine.shader = linearGradient!.createShader( Rect.fromCircle( center: center, radius: radius, ), ); } double fixedStartAngle = startAngle; double startAngleFixedMargin = 1.0; if (arcType != null) { if (arcType == ArcType.FULL) { fixedStartAngle = 220; startAngleFixedMargin = 172 / fixedStartAngle; } else { fixedStartAngle = 270; startAngleFixedMargin = 135 / fixedStartAngle; } } if (arcBackgroundColor != null) { canvas.drawArc( Rect.fromCircle(center: center, radius: radius), radians(-90.0 + fixedStartAngle) as double, radians(360 * startAngleFixedMargin) as double, false, _paintBackgroundStartAngle, ); } if (reverse!) { final start = radians(360 * startAngleFixedMargin - 90.0 + fixedStartAngle); final end = radians(-progress! * startAngleFixedMargin); canvas.drawArc( Rect.fromCircle( center: center, radius: radius, ), start as double, end as double, false, _paintLine, ); } else { final start = radians(-90.0 + fixedStartAngle); final end = radians(progress! * startAngleFixedMargin); canvas.drawArc( Rect.fromCircle( center: center, radius: radius, ), start as double, end as double, false, _paintLine, ); } } @override bool shouldRepaint(CustomPainter oldDelegate) { return true; } num radians(num deg) => deg * (math.pi / 180.0); }
0
mirrored_repositories/QuizApp-Flutter/lib/utils
mirrored_repositories/QuizApp-Flutter/lib/utils/percent_indicator/linear_percent_indicator.dart
import 'package:flutter/material.dart'; enum LinearStrokeCap { butt, round, roundAll } // ignore: must_be_immutable class LinearPercentIndicator extends StatefulWidget { ///Percent value between 0.0 and 1.0 final double? percent; final double? width; ///Height of the line final double lineHeight; ///Color of the background of the Line , default = transparent final Color fillColor; ///First color applied to the complete line final Color backgroundColor; Color? get progressColor => _progressColor; Color? _progressColor; ///true if you want the Line to have animation final bool animation; ///duration of the animation in milliseconds, It only applies if animation attribute is true final int animationDuration; ///widget at the left of the Line final Widget? leading; ///widget at the right of the Line final Widget? trailing; ///widget inside the Line final Widget? center; ///The kind of finish to place on the end of lines drawn, values supported: butt, round, roundAll final LinearStrokeCap? linearStrokeCap; ///alignment of the Row (leading-widget-center-trailing) final MainAxisAlignment alignment; ///padding to the LinearPercentIndicator final EdgeInsets padding; /// set true if you want to animate the linear from the last percent value you set final bool animateFromLastPercent; /// If present, this will make the progress bar colored by this gradient. /// /// This will override [progressColor]. It is an error to provide both. final LinearGradient? linearGradient; /// set false if you don't want to preserve the state of the widget final bool addAutomaticKeepAlive; /// set true if you want to animate the linear from the right to left (RTL) final bool isRTL; /// Creates a mask filter that takes the progress shape being drawn and blurs it. final MaskFilter? maskFilter; /// Set true if you want to display only part of [linearGradient] based on percent value /// (ie. create 'VU effect'). If no [linearGradient] is specified this option is ignored. final bool clipLinearGradient; /// set a linear curve animation type final Curve curve; /// set true when you want to restart the animation, it restarts only when reaches 1.0 as a value /// defaults to false final bool restartAnimation; LinearPercentIndicator( {Key? key, this.fillColor = Colors.transparent, this.percent = 0.0, this.lineHeight = 5.0, this.width, this.backgroundColor = const Color(0xFFB8C7CB), this.linearGradient, Color? progressColor, this.animation = false, this.animationDuration = 500, this.animateFromLastPercent = false, this.isRTL = false, this.leading, this.trailing, this.center, this.addAutomaticKeepAlive = true, this.linearStrokeCap, this.padding = const EdgeInsets.symmetric(horizontal: 10.0), this.alignment = MainAxisAlignment.start, this.maskFilter, this.clipLinearGradient = false, this.curve = Curves.linear, this.restartAnimation = false}) : super(key: key) { if (linearGradient != null && progressColor != null) { throw ArgumentError('Cannot provide both linearGradient and progressColor'); } _progressColor = progressColor ?? Colors.red; if (percent! < 0.0 || percent! > 1.0) { throw new Exception("Percent value must be a double between 0.0 and 1.0"); } } @override _LinearPercentIndicatorState createState() => _LinearPercentIndicatorState(); } class _LinearPercentIndicatorState extends State<LinearPercentIndicator> with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin { AnimationController? _animationController; late Animation _animation; double? _percent = 0.0; @override void dispose() { if (_animationController != null) { _animationController!.dispose(); } super.dispose(); } @override void initState() { if (widget.animation) { _animationController = new AnimationController(vsync: this, duration: Duration(milliseconds: widget.animationDuration)); _animation = Tween(begin: 0.0, end: widget.percent).animate( CurvedAnimation(parent: _animationController!, curve: widget.curve), )..addListener(() { setState(() { _percent = _animation.value; }); if (widget.restartAnimation && _percent == 1.0) { _animationController!.repeat(min: 0, max: 1.0); } }); _animationController!.forward(); } else { _updateProgress(); } super.initState(); } @override void didUpdateWidget(LinearPercentIndicator oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.percent != widget.percent) { if (_animationController != null) { _animationController!.duration = Duration(milliseconds: widget.animationDuration); _animation = Tween(begin: widget.animateFromLastPercent ? oldWidget.percent : 0.0, end: widget.percent).animate( CurvedAnimation(parent: _animationController!, curve: widget.curve), ); _animationController!.forward(from: 0.0); } else { _updateProgress(); } } } _updateProgress() { setState(() { _percent = widget.percent; }); } @override Widget build(BuildContext context) { super.build(context); List<Widget>? items = []; if (widget.leading != null) { items.add(widget.leading!); } final hasSetWidth = widget.width != null; var containerWidget = Container( width: hasSetWidth ? widget.width : double.infinity, height: widget.lineHeight, padding: widget.padding, child: CustomPaint( painter: LinearPainter( isRTL: widget.isRTL, progress: _percent, center: widget.center, progressColor: widget.progressColor, linearGradient: widget.linearGradient, backgroundColor: widget.backgroundColor, linearStrokeCap: widget.linearStrokeCap, lineWidth: widget.lineHeight, maskFilter: widget.maskFilter, clipLinearGradient: widget.clipLinearGradient, ), child: (widget.center != null) ? Center(child: widget.center) : Container(), ), ); if (hasSetWidth) { items.add(containerWidget); } else { items.add(Expanded( child: containerWidget, )); } if (widget.trailing != null) { items.add(widget.trailing!); } return Material( color: Colors.transparent, child: Container( color: widget.fillColor, child: Row( mainAxisAlignment: widget.alignment, crossAxisAlignment: CrossAxisAlignment.center, children: items, ), ), ); } @override bool get wantKeepAlive => widget.addAutomaticKeepAlive; } class LinearPainter extends CustomPainter { final Paint _paintBackground = new Paint(); final Paint _paintLine = new Paint(); final lineWidth; final progress; final center; final isRTL; final Color? progressColor; final Color? backgroundColor; final LinearStrokeCap? linearStrokeCap; final LinearGradient? linearGradient; final MaskFilter? maskFilter; final bool? clipLinearGradient; LinearPainter({ this.lineWidth, this.progress, this.center, this.isRTL, this.progressColor, this.backgroundColor, this.linearStrokeCap = LinearStrokeCap.butt, this.linearGradient, this.maskFilter, this.clipLinearGradient, }) { _paintBackground.color = backgroundColor!; _paintBackground.style = PaintingStyle.stroke; _paintBackground.strokeWidth = lineWidth; _paintLine.color = progress.toString() == "0.0" ? progressColor!.withOpacity(0.0) : progressColor!; _paintLine.style = PaintingStyle.stroke; _paintLine.strokeWidth = lineWidth; if (linearStrokeCap == LinearStrokeCap.round) { _paintLine.strokeCap = StrokeCap.round; } else if (linearStrokeCap == LinearStrokeCap.butt) { _paintLine.strokeCap = StrokeCap.butt; } else { _paintLine.strokeCap = StrokeCap.round; _paintBackground.strokeCap = StrokeCap.round; } } @override void paint(Canvas canvas, Size size) { final start = Offset(0.0, size.height / 2); final end = Offset(size.width, size.height / 2); canvas.drawLine(start, end, _paintBackground); if (maskFilter != null) { _paintLine.maskFilter = maskFilter; } if (isRTL) { final xProgress = size.width - size.width * progress; if (linearGradient != null) { _paintLine.shader = _createGradientShaderRightToLeft(size, xProgress); } canvas.drawLine(end, Offset(xProgress, size.height / 2), _paintLine); } else { final xProgress = size.width * progress; if (linearGradient != null) { _paintLine.shader = _createGradientShaderLeftToRight(size, xProgress); } canvas.drawLine(start, Offset(xProgress, size.height / 2), _paintLine); } } Shader _createGradientShaderRightToLeft(Size size, double xProgress) { Offset shaderEndPoint = clipLinearGradient! ? Offset.zero : Offset(xProgress, size.height); return linearGradient!.createShader( Rect.fromPoints( Offset(size.width, size.height), shaderEndPoint, ), ); } Shader _createGradientShaderLeftToRight(Size size, double xProgress) { Offset shaderEndPoint = clipLinearGradient! ? Offset(size.width, size.height) : Offset(xProgress, size.height); return linearGradient!.createShader( Rect.fromPoints( Offset.zero, shaderEndPoint, ), ); } @override bool shouldRepaint(CustomPainter oldDelegate) { return true; } }
0
mirrored_repositories/QuizApp-Flutter/lib/utils
mirrored_repositories/QuizApp-Flutter/lib/utils/percent_indicator/percent_indicator.dart
library percent_indicator; export 'circular_percent_indicator.dart'; export 'linear_percent_indicator.dart';
0
mirrored_repositories/QuizApp-Flutter/lib/utils
mirrored_repositories/QuizApp-Flutter/lib/utils/codePicker/selection_dialog.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:nb_utils/nb_utils.dart'; import 'package:quiz/utils/AppWidget.dart'; import '../../../main.dart'; import 'country_code.dart'; /// selection dialog used for selection of the country code class SelectionDialog extends StatefulWidget { final List<CountryCode> elements; final bool? showCountryOnly; final InputDecoration searchDecoration; final TextStyle? searchStyle; final WidgetBuilder? emptySearchBuilder; final bool? showFlag; /// elements passed as favorite final List<CountryCode> favoriteElements; SelectionDialog(this.elements, this.favoriteElements, {Key? key, this.showCountryOnly, this.emptySearchBuilder, InputDecoration searchDecoration = const InputDecoration(), this.searchStyle, this.showFlag}) : this.searchDecoration = searchDecoration.copyWith(prefixIcon: Icon(Icons.search)), super(key: key); @override State<StatefulWidget> createState() => _SelectionDialogState(); } class _SelectionDialogState extends State<SelectionDialog> { /// this is useful for filtering purpose late List<CountryCode> filteredElements; @override Widget build(BuildContext context) => CustomTheme( child: SimpleDialog( title: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ text("Select Country Code", textColor: textPrimaryColor, fontSize: 16.0, fontFamily: "Semibold"), SizedBox(height: 8), TextField( style: widget.searchStyle, decoration: InputDecoration( filled: true, hintText: "Search Country", hintStyle: secondaryTextStyle(), border: InputBorder.none, ), onChanged: _filterElements, ) ], ), children: [ Container( margin: EdgeInsets.only(top: 16), width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height, child: ListView( children: [ widget.favoriteElements.isEmpty ? DecoratedBox(decoration: BoxDecoration()) : Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[] ..addAll(widget.favoriteElements .map( (f) => SimpleDialogOption( child: _buildOption(f), onPressed: () { _selectItem(f); }, ), ) .toList()) ..add(Divider())), ]..addAll(filteredElements.isEmpty ? [_buildEmptySearchWidget(context)] : filteredElements.map((e) => SimpleDialogOption( key: Key(e.toLongString()), child: _buildOption(e), onPressed: () { _selectItem(e); }, ))))), ], ), ); Widget _buildOption(CountryCode e) { return Container( width: 400, child: Flex( direction: Axis.horizontal, children: <Widget>[ widget.showFlag! ? Flexible( child: Padding( padding: EdgeInsets.only(right: 16.0), child: CachedNetworkImage( placeholder: placeholderWidgetFn() as Widget Function(BuildContext, String)?, imageUrl: e.flagUri!, width: 25.0, ), ), ) : Container(), Expanded( flex: 4, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Expanded(child: text(e.toLongString(), fontSize: 14.0, textColor: textPrimaryColor)), text(e.dialCode, fontSize: 14.0, textColor: textPrimaryColor, fontFamily: "SemiBold"), ], ), ), ], ), ); } Widget _buildEmptySearchWidget(BuildContext context) { if (widget.emptySearchBuilder != null) { return widget.emptySearchBuilder!(context); } return Center(child: Text('No Country Found')); } @override void initState() { filteredElements = widget.elements; super.initState(); } void _filterElements(String s) { s = s.toUpperCase(); setState(() { filteredElements = widget.elements.where((e) => e.code!.contains(s) || e.dialCode!.contains(s) || e.name!.toUpperCase().contains(s)).toList(); }); } void _selectItem(CountryCode e) { Navigator.pop(context, e); } }
0
mirrored_repositories/QuizApp-Flutter/lib/utils
mirrored_repositories/QuizApp-Flutter/lib/utils/codePicker/country_codes.dart
List<Map> codes = [ {"name": "افغانستان", "code": "AF", "dial_code": "+93"}, {"name": "Åland", "code": "AX", "dial_code": "+358"}, {"name": "Shqipëria", "code": "AL", "dial_code": "+355"}, {"name": "الجزائر", "code": "DZ", "dial_code": "+213"}, {"name": "American Samoa", "code": "AS", "dial_code": "+1684"}, {"name": "Andorra", "code": "AD", "dial_code": "+376"}, {"name": "Angola", "code": "AO", "dial_code": "+244"}, {"name": "Anguilla", "code": "AI", "dial_code": "+1264"}, {"name": "Antarctica", "code": "AQ", "dial_code": "+672"}, {"name": "Antigua and Barbuda", "code": "AG", "dial_code": "+1268"}, {"name": "Argentina", "code": "AR", "dial_code": "+54"}, {"name": "Հայաստան", "code": "AM", "dial_code": "+374"}, {"name": "Aruba", "code": "AW", "dial_code": "+297"}, {"name": "Australia", "code": "AU", "dial_code": "+61"}, {"name": "Österreich", "code": "AT", "dial_code": "+43"}, {"name": "Azərbaycan", "code": "AZ", "dial_code": "+994"}, {"name": "Bahamas", "code": "BS", "dial_code": "+1242"}, {"name": "‏البحرين", "code": "BH", "dial_code": "+973"}, {"name": "Bangladesh", "code": "BD", "dial_code": "+880"}, {"name": "Barbados", "code": "BB", "dial_code": "+1246"}, {"name": "Белару́сь", "code": "BY", "dial_code": "+375"}, {"name": "België", "code": "BE", "dial_code": "+32"}, {"name": "Belize", "code": "BZ", "dial_code": "+501"}, {"name": "Bénin", "code": "BJ", "dial_code": "+229"}, {"name": "Bermuda", "code": "BM", "dial_code": "+1441"}, {"name": "ʼbrug-yul", "code": "BT", "dial_code": "+975"}, {"name": "Bolivia", "code": "BO", "dial_code": "+591"}, {"name": "Bosna i Hercegovina", "code": "BA", "dial_code": "+387"}, {"name": "Botswana", "code": "BW", "dial_code": "+267"}, {"name": "Bouvetøya", "code": "BV", "dial_code": "+47"}, {"name": "Brasil", "code": "BR", "dial_code": "+55"}, {"name": "British Indian Ocean Territory", "code": "IO", "dial_code": "+246"}, {"name": "Negara Brunei Darussalam", "code": "BN", "dial_code": "+673"}, {"name": "България", "code": "BG", "dial_code": "+359"}, {"name": "Burkina Faso", "code": "BF", "dial_code": "+226"}, {"name": "Burundi", "code": "BI", "dial_code": "+257"}, {"name": "Kâmpŭchéa", "code": "KH", "dial_code": "+855"}, {"name": "Cameroon", "code": "CM", "dial_code": "+237"}, {"name": "Canada", "code": "CA", "dial_code": "+1"}, {"name": "Cabo Verde", "code": "CV", "dial_code": "+238"}, {"name": "Cayman Islands", "code": "KY", "dial_code": "+ 345"}, {"name": "Ködörösêse tî Bêafrîka", "code": "CF", "dial_code": "+236"}, {"name": "Tchad", "code": "TD", "dial_code": "+235"}, {"name": "Chile", "code": "CL", "dial_code": "+56"}, {"name": "中国", "code": "CN", "dial_code": "+86"}, {"name": "Christmas Island", "code": "CX", "dial_code": "+61"}, {"name": "Cocos (Keeling) Islands", "code": "CC", "dial_code": "+61"}, {"name": "Colombia", "code": "CO", "dial_code": "+57"}, {"name": "Komori", "code": "KM", "dial_code": "+269"}, {"name": "République du Congo", "code": "CG", "dial_code": "+242"}, {"name": "République démocratique du Congo", "code": "CD", "dial_code": "+243"}, {"name": "Cook Islands", "code": "CK", "dial_code": "+682"}, {"name": "Costa Rica", "code": "CR", "dial_code": "+506"}, {"name": "Côte d'Ivoire", "code": "CI", "dial_code": "+225"}, {"name": "Hrvatska", "code": "HR", "dial_code": "+385"}, {"name": "Cuba", "code": "CU", "dial_code": "+53"}, {"name": "Κύπρος", "code": "CY", "dial_code": "+357"}, {"name": "Česká republika", "code": "CZ", "dial_code": "+420"}, {"name": "Danmark", "code": "DK", "dial_code": "+45"}, {"name": "Djibouti", "code": "DJ", "dial_code": "+253"}, {"name": "Dominica", "code": "DM", "dial_code": "+1767"}, {"name": "República Dominicana", "code": "DO", "dial_code": "+1"}, {"name": "Ecuador", "code": "EC", "dial_code": "+593"}, {"name": "مصر‎", "code": "EG", "dial_code": "+20"}, {"name": "El Salvador", "code": "SV", "dial_code": "+503"}, {"name": "Guinea Ecuatorial", "code": "GQ", "dial_code": "+240"}, {"name": "ኤርትራ", "code": "ER", "dial_code": "+291"}, {"name": "Eesti", "code": "EE", "dial_code": "+372"}, {"name": "ኢትዮጵያ", "code": "ET", "dial_code": "+251"}, {"name": "Falkland Islands", "code": "FK", "dial_code": "+500"}, {"name": "Føroyar", "code": "FO", "dial_code": "+298"}, {"name": "Fiji", "code": "FJ", "dial_code": "+679"}, {"name": "Suomi", "code": "FI", "dial_code": "+358"}, {"name": "France", "code": "FR", "dial_code": "+33"}, {"name": "Guyane française", "code": "GF", "dial_code": "+594"}, {"name": "Polynésie française", "code": "PF", "dial_code": "+689"}, {"name": "Territoire des Terres australes et antarctiques fr", "code": "TF", "dial_code": "+262"}, {"name": "Gabon", "code": "GA", "dial_code": "+241"}, {"name": "Gambia", "code": "GM", "dial_code": "+220"}, {"name": "საქართველო", "code": "GE", "dial_code": "+995"}, {"name": "Deutschland", "code": "DE", "dial_code": "+49"}, {"name": "Ghana", "code": "GH", "dial_code": "+233"}, {"name": "Gibraltar", "code": "GI", "dial_code": "+350"}, {"name": "Ελλάδα", "code": "GR", "dial_code": "+30"}, {"name": "Kalaallit Nunaat", "code": "GL", "dial_code": "+299"}, {"name": "Grenada", "code": "GD", "dial_code": "+1473"}, {"name": "Guadeloupe", "code": "GP", "dial_code": "+590"}, {"name": "Guam", "code": "GU", "dial_code": "+1671"}, {"name": "Guatemala", "code": "GT", "dial_code": "+502"}, {"name": "Guernsey", "code": "GG", "dial_code": "+44"}, {"name": "Guinée", "code": "GN", "dial_code": "+224"}, {"name": "Guiné-Bissau", "code": "GW", "dial_code": "+245"}, {"name": "Guyana", "code": "GY", "dial_code": "+592"}, {"name": "Haïti", "code": "HT", "dial_code": "+509"}, {"name": "Heard Island and McDonald Islands", "code": "HM", "dial_code": "+0"}, {"name": "Vaticano", "code": "VA", "dial_code": "+379"}, {"name": "Honduras", "code": "HN", "dial_code": "+504"}, {"name": "香港", "code": "HK", "dial_code": "+852"}, {"name": "Magyarország", "code": "HU", "dial_code": "+36"}, {"name": "Ísland", "code": "IS", "dial_code": "+354"}, {"name": "भारत", "code": "IN", "dial_code": "+91"}, {"name": "Indonesia", "code": "ID", "dial_code": "+62"}, {"name": "ایران", "code": "IR", "dial_code": "+98"}, {"name": "العراق", "code": "IQ", "dial_code": "+964"}, {"name": "Éire", "code": "IE", "dial_code": "+353"}, {"name": "Isle of Man", "code": "IM", "dial_code": "+44"}, {"name": "יִשְׂרָאֵל", "code": "IL", "dial_code": "+972"}, {"name": "Italia", "code": "IT", "dial_code": "+39"}, {"name": "Jamaica", "code": "JM", "dial_code": "+1876"}, {"name": "日本", "code": "JP", "dial_code": "+81"}, {"name": "Jersey", "code": "JE", "dial_code": "+44"}, {"name": "الأردن", "code": "JO", "dial_code": "+962"}, {"name": "Қазақстан", "code": "KZ", "dial_code": "+7"}, {"name": "Kenya", "code": "KE", "dial_code": "+254"}, {"name": "Kiribati", "code": "KI", "dial_code": "+686"}, {"name": "북한", "code": "KP", "dial_code": "+850"}, {"name": "대한민국", "code": "KR", "dial_code": "+82"}, {"name": "Republika e Kosovës", "code": "XK", "dial_code": "+383"}, {"name": "الكويت", "code": "KW", "dial_code": "+965"}, {"name": "Кыргызстан", "code": "KG", "dial_code": "+996"}, {"name": "ສປປລາວ", "code": "LA", "dial_code": "+856"}, {"name": "Latvija", "code": "LV", "dial_code": "+371"}, {"name": "لبنان", "code": "LB", "dial_code": "+961"}, {"name": "Lesotho", "code": "LS", "dial_code": "+266"}, {"name": "Liberia", "code": "LR", "dial_code": "+231"}, {"name": "‏ليبيا", "code": "LY", "dial_code": "+218"}, {"name": "Liechtenstein", "code": "LI", "dial_code": "+423"}, {"name": "Lietuva", "code": "LT", "dial_code": "+370"}, {"name": "Luxembourg", "code": "LU", "dial_code": "+352"}, {"name": "澳門", "code": "MO", "dial_code": "+853"}, {"name": "Македонија", "code": "MK", "dial_code": "+389"}, {"name": "Madagasikara", "code": "MG", "dial_code": "+261"}, {"name": "Malawi", "code": "MW", "dial_code": "+265"}, {"name": "Malaysia", "code": "MY", "dial_code": "+60"}, {"name": "Maldives", "code": "MV", "dial_code": "+960"}, {"name": "Mali", "code": "ML", "dial_code": "+223"}, {"name": "Malta", "code": "MT", "dial_code": "+356"}, {"name": "M̧ajeļ", "code": "MH", "dial_code": "+692"}, {"name": "Martinique", "code": "MQ", "dial_code": "+596"}, {"name": "موريتانيا", "code": "MR", "dial_code": "+222"}, {"name": "Maurice", "code": "MU", "dial_code": "+230"}, {"name": "Mayotte", "code": "YT", "dial_code": "+262"}, {"name": "México", "code": "MX", "dial_code": "+52"}, {"name": "Micronesia", "code": "FM", "dial_code": "+691"}, {"name": "Moldova", "code": "MD", "dial_code": "+373"}, {"name": "Monaco", "code": "MC", "dial_code": "+377"}, {"name": "Монгол улс", "code": "MN", "dial_code": "+976"}, {"name": "Црна Гора", "code": "ME", "dial_code": "+382"}, {"name": "Montserrat", "code": "MS", "dial_code": "+1664"}, {"name": "المغرب", "code": "MA", "dial_code": "+212"}, {"name": "Moçambique", "code": "MZ", "dial_code": "+258"}, {"name": "Myanma", "code": "MM", "dial_code": "+95"}, {"name": "Namibia", "code": "NA", "dial_code": "+264"}, {"name": "Nauru", "code": "NR", "dial_code": "+674"}, {"name": "नपल", "code": "NP", "dial_code": "+977"}, {"name": "Nederland", "code": "NL", "dial_code": "+31"}, {"name": "Netherlands Antilles", "code": "AN", "dial_code": "+599"}, {"name": "Nouvelle-Calédonie", "code": "NC", "dial_code": "+687"}, {"name": "New Zealand", "code": "NZ", "dial_code": "+64"}, {"name": "Nicaragua", "code": "NI", "dial_code": "+505"}, {"name": "Niger", "code": "NE", "dial_code": "+227"}, {"name": "Nigeria", "code": "NG", "dial_code": "+234"}, {"name": "Niuē", "code": "NU", "dial_code": "+683"}, {"name": "Norfolk Island", "code": "NF", "dial_code": "+672"}, {"name": "Northern Mariana Islands", "code": "MP", "dial_code": "+1670"}, {"name": "Norge", "code": "NO", "dial_code": "+47"}, {"name": "عمان", "code": "OM", "dial_code": "+968"}, {"name": "Pakistan", "code": "PK", "dial_code": "+92"}, {"name": "Palau", "code": "PW", "dial_code": "+680"}, {"name": "فلسطين", "code": "PS", "dial_code": "+970"}, {"name": "Panamá", "code": "PA", "dial_code": "+507"}, {"name": "Papua Niugini", "code": "PG", "dial_code": "+675"}, {"name": "Paraguay", "code": "PY", "dial_code": "+595"}, {"name": "Perú", "code": "PE", "dial_code": "+51"}, {"name": "Pilipinas", "code": "PH", "dial_code": "+63"}, {"name": "Pitcairn Islands", "code": "PN", "dial_code": "+64"}, {"name": "Polska", "code": "PL", "dial_code": "+48"}, {"name": "Portugal", "code": "PT", "dial_code": "+351"}, {"name": "Puerto Rico", "code": "PR", "dial_code": "+1939"}, {"name": "Puerto Rico", "code": "PR", "dial_code": "+1787"}, {"name": "قطر", "code": "QA", "dial_code": "+974"}, {"name": "România", "code": "RO", "dial_code": "+40"}, {"name": "Россия", "code": "RU", "dial_code": "+7"}, {"name": "Rwanda", "code": "RW", "dial_code": "+250"}, {"name": "La Réunion", "code": "RE", "dial_code": "+262"}, {"name": "Saint-Barthélemy", "code": "BL", "dial_code": "+590"}, {"name": "Saint Helena", "code": "SH", "dial_code": "+290"}, {"name": "Saint Kitts and Nevis", "code": "KN", "dial_code": "+1869"}, {"name": "Saint Lucia", "code": "LC", "dial_code": "+1758"}, {"name": "Saint-Martin", "code": "MF", "dial_code": "+590"}, {"name": "Saint-Pierre-et-Miquelon", "code": "PM", "dial_code": "+508"}, {"name": "Saint Vincent and the Grenadines", "code": "VC", "dial_code": "+1784"}, {"name": "Samoa", "code": "WS", "dial_code": "+685"}, {"name": "San Marino", "code": "SM", "dial_code": "+378"}, {"name": "São Tomé e Príncipe", "code": "ST", "dial_code": "+239"}, {"name": "العربية السعودية", "code": "SA", "dial_code": "+966"}, {"name": "Sénégal", "code": "SN", "dial_code": "+221"}, {"name": "Србија", "code": "RS", "dial_code": "+381"}, {"name": "Seychelles", "code": "SC", "dial_code": "+248"}, {"name": "Sierra Leone", "code": "SL", "dial_code": "+232"}, {"name": "Singapore", "code": "SG", "dial_code": "+65"}, {"name": "Slovensko", "code": "SK", "dial_code": "+421"}, {"name": "Slovenija", "code": "SI", "dial_code": "+386"}, {"name": "Solomon Islands", "code": "SB", "dial_code": "+677"}, {"name": "Soomaaliya", "code": "SO", "dial_code": "+252"}, {"name": "South Africa", "code": "ZA", "dial_code": "+27"}, {"name": "South Sudan", "code": "SS", "dial_code": "+211"}, {"name": "South Georgia", "code": "GS", "dial_code": "+500"}, {"name": "España", "code": "ES", "dial_code": "+34"}, {"name": "śrī laṃkāva", "code": "LK", "dial_code": "+94"}, {"name": "السودان", "code": "SD", "dial_code": "+249"}, {"name": "Suriname", "code": "SR", "dial_code": "+597"}, {"name": "Svalbard og Jan Mayen", "code": "SJ", "dial_code": "+47"}, {"name": "Swaziland", "code": "SZ", "dial_code": "+268"}, {"name": "Sverige", "code": "SE", "dial_code": "+46"}, {"name": "Schweiz", "code": "CH", "dial_code": "+41"}, {"name": "سوريا", "code": "SY", "dial_code": "+963"}, {"name": "臺灣", "code": "TW", "dial_code": "+886"}, {"name": "Тоҷикистон", "code": "TJ", "dial_code": "+992"}, {"name": "Tanzania", "code": "TZ", "dial_code": "+255"}, {"name": "ประเทศไทย", "code": "TH", "dial_code": "+66"}, {"name": "Timor-Leste", "code": "TL", "dial_code": "+670"}, {"name": "Togo", "code": "TG", "dial_code": "+228"}, {"name": "Tokelau", "code": "TK", "dial_code": "+690"}, {"name": "Tonga", "code": "TO", "dial_code": "+676"}, {"name": "Trinidad and Tobago", "code": "TT", "dial_code": "+1868"}, {"name": "تونس", "code": "TN", "dial_code": "+216"}, {"name": "Türkiye", "code": "TR", "dial_code": "+90"}, {"name": "Türkmenistan", "code": "TM", "dial_code": "+993"}, {"name": "Turks and Caicos Islands", "code": "TC", "dial_code": "+1649"}, {"name": "Tuvalu", "code": "TV", "dial_code": "+688"}, {"name": "Uganda", "code": "UG", "dial_code": "+256"}, {"name": "Україна", "code": "UA", "dial_code": "+380"}, {"name": "دولة الإمارات العربية المتحدة", "code": "AE", "dial_code": "+971"}, {"name": "United Kingdom", "code": "GB", "dial_code": "+44"}, {"name": "United States", "code": "US", "dial_code": "+1"}, {"name": "Uruguay", "code": "UY", "dial_code": "+598"}, {"name": "O‘zbekiston", "code": "UZ", "dial_code": "+998"}, {"name": "Vanuatu", "code": "VU", "dial_code": "+678"}, {"name": "Venezuela", "code": "VE", "dial_code": "+58"}, {"name": "Việt Nam", "code": "VN", "dial_code": "+84"}, {"name": "British Virgin Islands", "code": "VG", "dial_code": "+1284"}, {"name": "United States Virgin Islands", "code": "VI", "dial_code": "+1340"}, {"name": "Wallis et Futuna", "code": "WF", "dial_code": "+681"}, {"name": "اليَمَن", "code": "YE", "dial_code": "+967"}, {"name": "Zambia", "code": "ZM", "dial_code": "+260"}, {"name": "Zimbabwe", "code": "ZW", "dial_code": "+263"} ];
0
mirrored_repositories/QuizApp-Flutter/lib/utils
mirrored_repositories/QuizApp-Flutter/lib/utils/codePicker/country_code.dart
mixin ToAlias {} @deprecated class CElement = CountryCode with ToAlias; /// Country element. This is the element that contains all the information class CountryCode { /// the name of the country String? name; /// the flag of the country String? flagUri; /// the country code (IT,AF..) String? code; /// the dial code (+39,+93..) String? dialCode; CountryCode({this.name, this.flagUri, this.code, this.dialCode}); @override String toString() => "$dialCode"; String toLongString() => "$name ($code)"; String toCountryCodeString() => "$code $dialCode"; String toCountryStringOnly() => '$name'; }
0