code
stringlengths
8
3.25M
repository
stringlengths
15
175
metadata
stringlengths
66
249
// Copyright 2021, the Flutter project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. /// Skipping stacks example /// Done using VRouter import 'package:flutter/material.dart'; import 'package:vrouter/vrouter.dart'; void main() { runApp(BooksApp()); } class Book { final String title; final Author author; Book(this.title, this.author); } class Author { String name; Author(this.name); } class AppState extends ChangeNotifier { final List<Book> books = [ Book('Stranger in a Strange Land', Author('Robert A. Heinlein')), Book('Foundation', Author('Isaac Asimov')), Book('Fahrenheit 451', Author('Ray Bradbury')), ]; List<Author> get authors => [...books.map((book) => book.author)]; } class BooksApp extends StatelessWidget { final AppState _appState = AppState(); @override Widget build(BuildContext context) { return VRouter( routes: [ // Books VWidget( path: '/', widget: BooksListScreen(books: _appState.books), stackedRoutes: [ VWidget( path: r'book/:bookId(\d+)', widget: Builder( builder: (context) { final bookId = int.parse(context.vRouter.pathParameters['bookId']!); return BookDetailsScreen( book: _appState.books[bookId], ); }, ), ), ], ), // Authors VWidget( path: '/authors', widget: AuthorsListScreen(authors: _appState.authors), stackedRoutes: [ VWidget( path: r'/author/:bookId(\d+)', widget: Builder( builder: (context) { final bookId = int.parse(context.vRouter.pathParameters['bookId']!); return AuthorDetailsScreen( author: _appState.books[bookId].author, ); }, ), ), ], ), // Redirect unknown VRouteRedirector(path: r'.+', redirectTo: '/'), ], ); } } class BooksListScreen extends StatelessWidget { final List<Book> books; BooksListScreen({required this.books}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: ListView( children: [ for (var book in books) ListTile( title: Text(book.title), subtitle: Text(book.author.name), onTap: () => context.vRouter.push('/book/${books.indexOf(book)}'), ) ], ), ); } } class AuthorsListScreen extends StatelessWidget { final List<Author> authors; AuthorsListScreen({required this.authors}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: ListView( children: [ ElevatedButton( onPressed: () => context.vRouter.push('/'), child: Text('Go to Books Screen'), ), for (var author in authors) ListTile( title: Text(author.name), onTap: () => context.vRouter.push('/author/${authors.indexOf(author)}'), ) ], ), ); } } class BookDetailsScreen extends StatelessWidget { final Book book; BookDetailsScreen({required this.book}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: Padding( padding: const EdgeInsets.all(8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(book.title, style: Theme.of(context).textTheme.headline6), ElevatedButton( onPressed: () => context.vRouter .push('/author/${context.vRouter.pathParameters['bookId']}'), child: Text(book.author.name), ), ], ), ), ); } } class AuthorDetailsScreen extends StatelessWidget { final Author author; AuthorDetailsScreen({ required this.author, }); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: Padding( padding: const EdgeInsets.all(8.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(author.name, style: Theme.of(context).textTheme.headline6), ], ), ), ); } }
uxr/nav2-usability/scenario_code/lib/skipping-stacks/skipping_stacks_vrouter.dart/0
{'file_path': 'uxr/nav2-usability/scenario_code/lib/skipping-stacks/skipping_stacks_vrouter.dart', 'repo_id': 'uxr', 'token_count': 2209}
include: package:dart_flutter_team_lints/analysis_options.yaml analyzer: language: strict-casts: true strict-inference: true strict-raw-types: true
uxr/surveys/survey-validator/analysis_options.yaml/0
{'file_path': 'uxr/surveys/survey-validator/analysis_options.yaml', 'repo_id': 'uxr', 'token_count': 61}
/// Very Good Dart analyzer settings and best practices /// used internally at [Very Good Ventures](https://verygood.ventures). library very_good_analysis;
very_good_analysis/lib/very_good_analysis.dart/0
{'file_path': 'very_good_analysis/lib/very_good_analysis.dart', 'repo_id': 'very_good_analysis', 'token_count': 36}
import 'package:mason/mason.dart'; import 'package:universal_io/io.dart'; import 'package:very_good_cli/src/commands/create/templates/templates.dart'; import 'package:very_good_cli/src/logger_extension.dart'; /// {@template very_good_core_template} /// A core Flutter app template. /// {@endtemplate} class VeryGoodCoreTemplate extends Template { /// {@macro very_good_core_template} VeryGoodCoreTemplate() : super( name: 'core', bundle: veryGoodCoreBundle, help: 'Generate a Very Good Flutter application.', ); @override Future<void> onGenerateComplete(Logger logger, Directory outputDir) async { await installFlutterPackages(logger, outputDir); await applyDartFixes(logger, outputDir); _logSummary(logger); } void _logSummary(Logger logger) { logger ..info('\n') ..created('Created a Very Good App! 🦄') ..info('\n') ..info( lightGray.wrap( ''' +----------------------------------------------------+ | Looking for more features? | | We have an enterprise-grade solution for companies | | called Very Good Start. | | | | For more info visit: | | https://verygood.ventures/solution/very-good-start | +----------------------------------------------------+''', ), ); } }
very_good_cli/lib/src/commands/create/templates/very_good_core/very_good_core_template.dart/0
{'file_path': 'very_good_cli/lib/src/commands/create/templates/very_good_core/very_good_core_template.dart', 'repo_id': 'very_good_cli', 'token_count': 602}
export 'very_good_flutter_plugin_bundle.dart'; export 'very_good_flutter_plugin_template.dart';
very_good_cli/lib/src/commands/create/templates/very_good_flutter_plugin/very_good_flutter_plugin.dart/0
{'file_path': 'very_good_cli/lib/src/commands/create/templates/very_good_flutter_plugin/very_good_flutter_plugin.dart', 'repo_id': 'very_good_cli', 'token_count': 35}
import 'package:flutter/material.dart'; import 'package:{{project_name.snakeCase()}}/counter/counter.dart'; import 'package:{{project_name.snakeCase()}}/l10n/l10n.dart'; class App extends StatelessWidget { const App({super.key}); @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData( appBarTheme: AppBarTheme( backgroundColor: Theme.of(context).colorScheme.inversePrimary, ), useMaterial3: true, ), localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, home: const CounterPage(), ); } }
very_good_core/brick/__brick__/{{project_name.snakeCase()}}/lib/app/view/app.dart/0
{'file_path': 'very_good_core/brick/__brick__/{{project_name.snakeCase()}}/lib/app/view/app.dart', 'repo_id': 'very_good_core', 'token_count': 249}
version: 2 updates: - package-ecosystem: "github-actions" directory: "/" schedule: interval: "daily" - package-ecosystem: "npm" directory: "/" schedule: interval: "daily"
very_good_coverage/.github/dependabot.yaml/0
{'file_path': 'very_good_coverage/.github/dependabot.yaml', 'repo_id': 'very_good_coverage', 'token_count': 85}
/// {{project_name.snakeCase()}}, {{description}} /// /// ```sh /// # activate {{project_name.snakeCase()}} /// dart pub global activate {{project_name.snakeCase()}} /// /// # see usage /// {{executable_name.snakeCase()}} --help /// ``` library {{project_name.snakeCase()}};
very_good_dart_cli/brick/__brick__/{{project_name.snakeCase()}}/lib/{{project_name.snakeCase()}}.dart/0
{'file_path': 'very_good_dart_cli/brick/__brick__/{{project_name.snakeCase()}}/lib/{{project_name.snakeCase()}}.dart', 'repo_id': 'very_good_dart_cli', 'token_count': 92}
export 'view/app.dart';
very_good_flame_game/brick/__brick__/{{project_name.snakeCase()}}/lib/app/app.dart/0
{'file_path': 'very_good_flame_game/brick/__brick__/{{project_name.snakeCase()}}/lib/app/app.dart', 'repo_id': 'very_good_flame_game', 'token_count': 10}
export 'title_page.dart';
very_good_flame_game/brick/__brick__/{{project_name.snakeCase()}}/lib/title/view/view.dart/0
{'file_path': 'very_good_flame_game/brick/__brick__/{{project_name.snakeCase()}}/lib/title/view/view.dart', 'repo_id': 'very_good_flame_game', 'token_count': 10}
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockingjay/mockingjay.dart'; import 'package:{{project_name.snakeCase()}}/game/cubit/cubit.dart'; import 'package:{{project_name.snakeCase()}}/l10n/l10n.dart'; import 'package:{{project_name.snakeCase()}}/loading/loading.dart'; import 'helpers.dart'; extension PumpApp on WidgetTester { Future<void> pumpApp( Widget widget, { MockNavigator? navigator, PreloadCubit? preloadCubit, AudioCubit? audioCubit, }) { return pumpWidget( MultiBlocProvider( providers: [ BlocProvider.value(value: preloadCubit ?? MockPreloadCubit()), ], child: MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, home: navigator != null ? MockNavigatorProvider(navigator: navigator, child: widget) : widget, ), ), ); } }
very_good_flame_game/brick/__brick__/{{project_name.snakeCase()}}/test/helpers/pump_app.dart/0
{'file_path': 'very_good_flame_game/brick/__brick__/{{project_name.snakeCase()}}/test/helpers/pump_app.dart', 'repo_id': 'very_good_flame_game', 'token_count': 444}
export 'audio/audio_cubit.dart';
very_good_flame_game/src/very_good_flame_game/lib/game/cubit/cubit.dart/0
{'file_path': 'very_good_flame_game/src/very_good_flame_game/lib/game/cubit/cubit.dart', 'repo_id': 'very_good_flame_game', 'token_count': 14}
name: very_good_flame_game description: A Very Good Flame Game created by Very Good Ventures. version: 1.0.0+1 publish_to: none environment: sdk: ">=3.1.0 <4.0.0" dependencies: audioplayers: ^5.2.0 bloc: ^8.1.2 equatable: ^2.0.5 flame: ^1.10.1 flame_audio: ^2.1.3 flame_behaviors: ^1.0.0 flutter: sdk: flutter flutter_bloc: ^8.1.3 flutter_localizations: sdk: flutter google_fonts: ^6.0.0 intl: ^0.18.0 dev_dependencies: bloc_test: ^9.1.5 flame_test: ^1.14.0 flutter_test: sdk: flutter mockingjay: ^0.5.0 mocktail: ^1.0.0 very_good_analysis: ^5.1.0 flutter: uses-material-design: true generate: true assets: - assets/audio/ - assets/images/ - assets/licenses/poppins/
very_good_flame_game/src/very_good_flame_game/pubspec.yaml/0
{'file_path': 'very_good_flame_game/src/very_good_flame_game/pubspec.yaml', 'repo_id': 'very_good_flame_game', 'token_count': 347}
name: very_good_flutter_plugin description: A Very Good federated Flutter plugin created by Very Good Ventures. repository: https://github.com/VeryGoodOpenSource/very_good_flutter_plugin version: 0.6.0 environment: mason: ">=0.1.0-dev.50 <0.1.0" vars: project_name: type: string description: The name of the flutter plugin default: my_plugin prompt: What is the name of the plugin? description: type: string description: A short description of the plugin default: A very good flutter plugin prompt: Please enter the plugin description. org_name: type: string description: The organization name default: com.example.verygood.plugin prompt: What is the organization name? platforms: type: array description: The list of supported platforms prompt: Which platforms would you like to support? defaults: - android - ios - linux - macos - web - windows values: - android - ios - linux - macos - web - windows publishable: type: boolean description: Whether the generated package is intended to be published. default: false prompt: Will the package be published?
very_good_flutter_plugin/brick/brick.yaml/0
{'file_path': 'very_good_flutter_plugin/brick/brick.yaml', 'repo_id': 'very_good_flutter_plugin', 'token_count': 432}
import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:my_plugin_platform_interface/my_plugin_platform_interface.dart'; import 'package:my_plugin_windows/my_plugin_windows.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('MyPluginWindows', () { const kPlatformName = 'Windows'; late MyPluginWindows myPlugin; late List<MethodCall> log; setUp(() async { myPlugin = MyPluginWindows(); log = <MethodCall>[]; TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler(myPlugin.methodChannel, (methodCall) async { log.add(methodCall); switch (methodCall.method) { case 'getPlatformName': return kPlatformName; default: return null; } }); }); test('can be registered', () { MyPluginWindows.registerWith(); expect(MyPluginPlatform.instance, isA<MyPluginWindows>()); }); test('getPlatformName returns correct name', () async { final name = await myPlugin.getPlatformName(); expect( log, <Matcher>[isMethodCall('getPlatformName', arguments: null)], ); expect(name, equals(kPlatformName)); }); }); }
very_good_flutter_plugin/src/my_plugin/my_plugin_windows/test/my_plugin_windows_test.dart/0
{'file_path': 'very_good_flutter_plugin/src/my_plugin/my_plugin_windows/test/my_plugin_windows_test.dart', 'repo_id': 'very_good_flutter_plugin', 'token_count': 502}
import 'package:example/advanced/people_cubit.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:very_good_infinite_list/very_good_infinite_list.dart'; class AdvancedExample extends StatelessWidget { const AdvancedExample({super.key}); static Route<void> route() { return MaterialPageRoute( builder: (context) { return BlocProvider( create: (_) => PeopleCubit(), child: const AdvancedExample(), ); }, ); } @override Widget build(BuildContext context) { final state = context.watch<PeopleCubit>().state; return Scaffold( appBar: AppBar( title: const Text('Advanced Example'), ), body: Column( children: [ _Header(), Expanded( child: InfiniteList( itemCount: state.values.length, isLoading: state.isLoading, hasError: state.error != null, hasReachedMax: state.hasReachedMax, onFetchData: () => context.read<PeopleCubit>().loadData(), separatorBuilder: (context, _) => const Divider(), itemBuilder: (context, index) { return ListTile( dense: true, title: Text(state.values[index].name), ); }, ), ), ], ), ); } } class _Header extends StatelessWidget { @override Widget build(BuildContext context) { return const SizedBox( width: double.infinity, child: Material( color: Colors.white, elevation: 2, child: Padding( padding: EdgeInsets.only( top: 16, bottom: 8, ), child: Text( 'A maximum of 24 items can be fetched.', textAlign: TextAlign.center, ), ), ), ); } }
very_good_infinite_list/example/lib/advanced/advanced_example.dart/0
{'file_path': 'very_good_infinite_list/example/lib/advanced/advanced_example.dart', 'repo_id': 'very_good_infinite_list', 'token_count': 931}
targets: $default: builders: source_gen|combining_builder: options: ignore_for_file: - implicit_dynamic_parameter - require_trailing_commas
very_good_performance/build.yaml/0
{'file_path': 'very_good_performance/build.yaml', 'repo_id': 'very_good_performance', 'token_count': 96}
export 'timeline/error_report.dart'; export 'timeline/success_report.dart'; export 'timeline/warning_report.dart';
very_good_performance/test/fixtures/fixtures.dart/0
{'file_path': 'very_good_performance/test/fixtures/fixtures.dart', 'repo_id': 'very_good_performance', 'token_count': 39}
import 'package:flame/components.dart'; import 'package:flame/game.dart'; import 'package:flame/input.dart'; import 'package:flame_behaviors/flame_behaviors.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; class ThresholdDragUpdateInfo implements DragUpdateInfo { factory ThresholdDragUpdateInfo(DragUpdateInfo info, EventDelta delta) { return ThresholdDragUpdateInfo._(delta, info.eventPosition, info.raw); } ThresholdDragUpdateInfo._(this.delta, this.eventPosition, this.raw); @override bool handled = false; @override final EventDelta delta; @override final EventPosition eventPosition; @override final DragUpdateDetails raw; } abstract class ThresholdDraggableBehavior<Parent extends Entity, TGame extends FlameGame> extends DraggableBehavior<Parent> with HasGameRef<TGame> { double get threshold; DragStartInfo? _dragStartInfo; Vector2? _currentPos; bool _didBreakThreshold = false; @override @nonVirtual bool onDragStart(DragStartInfo info) { _dragStartInfo = info; return false; } bool onReallyDragStart(DragStartInfo info) { return true; } bool onReallyDragUpdate(DragUpdateInfo info) { return true; } @override @mustCallSuper bool onDragUpdate(DragUpdateInfo info) { if (_didBreakThreshold) { return onReallyDragUpdate(info); } final dragStartInfo = _dragStartInfo!; _currentPos ??= dragStartInfo.eventPosition.viewport.clone(); _currentPos?.add(info.delta.viewport); final delta = _currentPos!.clone().distanceTo(dragStartInfo.eventPosition.viewport); _didBreakThreshold = delta > threshold; if (_didBreakThreshold) { onReallyDragStart(dragStartInfo); final offset = _currentPos! ..sub(dragStartInfo.eventPosition.viewport.clone()); final thresholdInfo = ThresholdDragUpdateInfo( info, EventDelta(gameRef, offset.toOffset()), ); return onReallyDragUpdate(thresholdInfo); } return true; } @override @mustCallSuper bool onDragEnd(DragEndInfo info) { _dragStartInfo = null; _currentPos = null; _didBreakThreshold = false; return super.onDragEnd(info); } @override @mustCallSuper bool onDragCancel() { _dragStartInfo = null; _currentPos = null; _didBreakThreshold = false; return super.onDragCancel(); } }
very_good_ranch/lib/game/behaviors/threshold_draggable_behavior.dart/0
{'file_path': 'very_good_ranch/lib/game/behaviors/threshold_draggable_behavior.dart', 'repo_id': 'very_good_ranch', 'token_count': 856}
import 'package:flame/components.dart'; import 'package:flame/effects.dart'; import 'package:flame_behaviors/flame_behaviors.dart'; import 'package:flame_bloc/flame_bloc.dart'; import 'package:flutter/widgets.dart'; import 'package:very_good_ranch/config.dart'; import 'package:very_good_ranch/game/bloc/blessing/blessing_bloc.dart'; import 'package:very_good_ranch/game/entities/entities.dart'; class LeavingBehavior extends Behavior<Unicorn> with FlameBlocReader<BlessingBloc, BlessingState> { static const double leavingAnimationDuration = 1; static const Curve leavingAnimationCurve = Curves.easeIn; EffectController? _effectController; @override void update(double dt) { if (parent.happiness <= Config.happinessThresholdToLeave && !parent.isLeaving) { _startLeaveAnimation(); } if (_effectController?.completed == true) { parent.removeFromParent(); } } void _startLeaveAnimation() { final effectController = _effectController = CurvedEffectController( leavingAnimationDuration, leavingAnimationCurve, ); bloc.add(UnicornDespawned(parent.evolutionStage)); parent.isLeaving = true; parent.unicornComponent ..add(OpacityEffect.fadeOut(effectController)) ..add(MoveByEffect(Vector2(0, -100), effectController)); } }
very_good_ranch/lib/game/entities/unicorn/behaviors/leaving_behavior.dart/0
{'file_path': 'very_good_ranch/lib/game/entities/unicorn/behaviors/leaving_behavior.dart', 'repo_id': 'very_good_ranch', 'token_count': 462}
part of 'settings_bloc.dart'; abstract class SettingsEvent extends Equatable { const SettingsEvent(); } class MusicVolumeChanged extends SettingsEvent { const MusicVolumeChanged(this.volume); final double volume; @override List<Object> get props => [volume]; }
very_good_ranch/lib/game_menu/bloc/settings/settings_event.dart/0
{'file_path': 'very_good_ranch/lib/game_menu/bloc/settings/settings_event.dart', 'repo_id': 'very_good_ranch', 'token_count': 77}
export 'loading_page.dart';
very_good_ranch/lib/loading/view/view.dart/0
{'file_path': 'very_good_ranch/lib/loading/view/view.dart', 'repo_id': 'very_good_ranch', 'token_count': 10}
/// GENERATED CODE - DO NOT MODIFY BY HAND /// ***************************************************** /// FlutterGen /// ***************************************************** // coverage:ignore-file // ignore_for_file: type=lint // ignore_for_file: directives_ordering,unnecessary_import import 'package:flutter/widgets.dart'; class $AssetsAnimationsGen { const $AssetsAnimationsGen(); /// File path: assets/animations/adult_eat.png AssetGenImage get adultEat => const AssetGenImage('assets/animations/adult_eat.png'); /// File path: assets/animations/adult_idle.png AssetGenImage get adultIdle => const AssetGenImage('assets/animations/adult_idle.png'); /// File path: assets/animations/adult_petted.png AssetGenImage get adultPetted => const AssetGenImage('assets/animations/adult_petted.png'); /// File path: assets/animations/adult_walk_cycle.png AssetGenImage get adultWalkCycle => const AssetGenImage('assets/animations/adult_walk_cycle.png'); /// File path: assets/animations/baby_eat.png AssetGenImage get babyEat => const AssetGenImage('assets/animations/baby_eat.png'); /// File path: assets/animations/baby_idle.png AssetGenImage get babyIdle => const AssetGenImage('assets/animations/baby_idle.png'); /// File path: assets/animations/baby_petted.png AssetGenImage get babyPetted => const AssetGenImage('assets/animations/baby_petted.png'); /// File path: assets/animations/baby_walk_cycle.png AssetGenImage get babyWalkCycle => const AssetGenImage('assets/animations/baby_walk_cycle.png'); /// File path: assets/animations/child_eat.png AssetGenImage get childEat => const AssetGenImage('assets/animations/child_eat.png'); /// File path: assets/animations/child_idle.png AssetGenImage get childIdle => const AssetGenImage('assets/animations/child_idle.png'); /// File path: assets/animations/child_petted.png AssetGenImage get childPetted => const AssetGenImage('assets/animations/child_petted.png'); /// File path: assets/animations/child_walk_cycle.png AssetGenImage get childWalkCycle => const AssetGenImage('assets/animations/child_walk_cycle.png'); /// File path: assets/animations/teen_eat.png AssetGenImage get teenEat => const AssetGenImage('assets/animations/teen_eat.png'); /// File path: assets/animations/teen_idle.png AssetGenImage get teenIdle => const AssetGenImage('assets/animations/teen_idle.png'); /// File path: assets/animations/teen_petted.png AssetGenImage get teenPetted => const AssetGenImage('assets/animations/teen_petted.png'); /// File path: assets/animations/teen_walk_cycle.png AssetGenImage get teenWalkCycle => const AssetGenImage('assets/animations/teen_walk_cycle.png'); } class $AssetsBackgroundGen { const $AssetsBackgroundGen(); /// File path: assets/background/barn.png AssetGenImage get barn => const AssetGenImage('assets/background/barn.png'); /// File path: assets/background/cow.png AssetGenImage get cow => const AssetGenImage('assets/background/cow.png'); /// File path: assets/background/flower_duo.png AssetGenImage get flowerDuo => const AssetGenImage('assets/background/flower_duo.png'); /// File path: assets/background/flower_group.png AssetGenImage get flowerGroup => const AssetGenImage('assets/background/flower_group.png'); /// File path: assets/background/flower_solo.png AssetGenImage get flowerSolo => const AssetGenImage('assets/background/flower_solo.png'); /// File path: assets/background/grass.png AssetGenImage get grass => const AssetGenImage('assets/background/grass.png'); /// File path: assets/background/lined_tree.png AssetGenImage get linedTree => const AssetGenImage('assets/background/lined_tree.png'); /// File path: assets/background/lined_tree_short.png AssetGenImage get linedTreeShort => const AssetGenImage('assets/background/lined_tree_short.png'); /// File path: assets/background/sheep.png AssetGenImage get sheep => const AssetGenImage('assets/background/sheep.png'); /// File path: assets/background/sheep_small.png AssetGenImage get sheepSmall => const AssetGenImage('assets/background/sheep_small.png'); /// File path: assets/background/short_tree.png AssetGenImage get shortTree => const AssetGenImage('assets/background/short_tree.png'); /// File path: assets/background/tall_tree.png AssetGenImage get tallTree => const AssetGenImage('assets/background/tall_tree.png'); } class $AssetsFoodGen { const $AssetsFoodGen(); /// File path: assets/food/cake.png AssetGenImage get cake => const AssetGenImage('assets/food/cake.png'); /// File path: assets/food/donut.png AssetGenImage get donut => const AssetGenImage('assets/food/donut.png'); /// File path: assets/food/icecream.png AssetGenImage get icecream => const AssetGenImage('assets/food/icecream.png'); /// File path: assets/food/lollipop.png AssetGenImage get lollipop => const AssetGenImage('assets/food/lollipop.png'); /// File path: assets/food/pancakes.png AssetGenImage get pancakes => const AssetGenImage('assets/food/pancakes.png'); } class Assets { Assets._(); static const $AssetsAnimationsGen animations = $AssetsAnimationsGen(); static const $AssetsBackgroundGen background = $AssetsBackgroundGen(); static const $AssetsFoodGen food = $AssetsFoodGen(); } 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 = 'ranch_components', 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, ); } String get path => _assetName; String get keyName => 'packages/ranch_components/$_assetName'; }
very_good_ranch/packages/ranch_components/lib/gen/assets.gen.dart/0
{'file_path': 'very_good_ranch/packages/ranch_components/lib/gen/assets.gen.dart', 'repo_id': 'very_good_ranch', 'token_count': 2328}
name: ranch_components description: Package with the game components for the Very Good Ranch game. version: 1.0.0+1 publish_to: none environment: sdk: ">=2.18.0 <3.0.0" dependencies: flame: 1.3.0 flutter: sdk: flutter dev_dependencies: flame_test: ^1.7.0 flutter_test: sdk: flutter mocktail: ^0.3.0 very_good_analysis: ^3.1.0 flutter: generate: true assets: - assets/background/ - assets/food/ - assets/animations/ flutter_gen: line_length: 80 assets: package_parameter_enabled: true
very_good_ranch/packages/ranch_components/pubspec.yaml/0
{'file_path': 'very_good_ranch/packages/ranch_components/pubspec.yaml', 'repo_id': 'very_good_ranch', 'token_count': 223}
import 'package:dashbook/dashbook.dart'; import 'package:flame/game.dart'; import 'package:ranch_components/ranch_components.dart'; import 'package:sandbox/common/common.dart'; void addBackgroundComponentStories(Dashbook dashbook) { dashbook.storiesOf('BackgroundComponent').add( 'type', (context) { final unicornX = context.numberProperty('unicorn x', 350); final unicornY = context.numberProperty('unicorn y', 120); final unicorn = AdultUnicornComponent() ..position = Vector2(unicornX, unicornY); return GameWidget( game: StoryGame( center: false, BackgroundComponent( children: [unicorn], ), ), ); }, info: ''' The BackgroundComponent is a component that render the general background of a farm and defines a pasture field - It can accommodate unicorns ''', ); }
very_good_ranch/packages/ranch_components/sandbox/lib/stories/ranch_background_component/stories.dart/0
{'file_path': 'very_good_ranch/packages/ranch_components/sandbox/lib/stories/ranch_background_component/stories.dart', 'repo_id': 'very_good_ranch', 'token_count': 340}
import 'dart:math'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:ranch_flame/ranch_flame.dart'; class MockRandom extends Mock implements Random {} const epsilon = 1e-15; void main() { group('exponentialDecay', () { test('decay values', () { expect(exponentialDecay(100, 0.1, 0), closeTo(100, epsilon)); expect(exponentialDecay(100, 0.1, 1), closeTo(90, epsilon)); expect(exponentialDecay(100, 0.1, 2), closeTo(81, epsilon)); }); test('validates rate', () { expect(() => exponentialDecay(100, 1.1, 0), throwsAssertionError); }); }); }
very_good_ranch/packages/ranch_flame/test/src/exponential_decay_test.dart/0
{'file_path': 'very_good_ranch/packages/ranch_flame/test/src/exponential_decay_test.dart', 'repo_id': 'very_good_ranch', 'token_count': 255}
import 'package:audioplayers/audioplayers.dart'; import 'package:flutter/foundation.dart'; /// {@template unprefixed_images} /// A variant of [AudioCache] that is guaranteed to not have prefix. Ever. /// {@endtemplate} class UnprefixedAudioCache extends AudioCache { @override String get prefix => ''; @override @protected set prefix(String value) { super.prefix = ''; } }
very_good_ranch/packages/ranch_sounds/lib/src/unprefixed_audiocache.dart/0
{'file_path': 'very_good_ranch/packages/ranch_sounds/lib/src/unprefixed_audiocache.dart', 'repo_id': 'very_good_ranch', 'token_count': 125}
import 'package:flutter/material.dart'; import 'package:ranch_ui/src/widgets/progress_bar/theme.dart'; /// {@template animated_progress_bar} /// A [Widget] that renders a intrinsically animated progress bar. /// /// [progress] should be between 0 and 1; /// {@endtemplate} class AnimatedProgressBar extends StatelessWidget { /// {@macro animated_progress_bar} const AnimatedProgressBar({super.key, required this.progress}) : assert( progress >= 0.0 && progress <= 1.0, 'Progress should be set between 0.0 and 1.0', ); /// The current progress for the bar. final double progress; /// The duration of the animation on [AnimatedProgressBar] static const Duration intrinsicAnimationDuration = Duration(milliseconds: 300); @override Widget build(BuildContext context) { final theme = AnimatedProgressBarTheme.of(context); // Outer bar return ClipRRect( borderRadius: BorderRadius.circular(2), child: SizedBox( height: 16, width: 200, child: ColoredBox( color: theme.backgroundColor, child: Padding( padding: const EdgeInsets.all(2), // Animate the progress bar child: TweenAnimationBuilder( tween: Tween<double>(begin: 0, end: progress), duration: intrinsicAnimationDuration, builder: (BuildContext context, double progress, _) { // Inner bar return FractionallySizedBox( alignment: Alignment.centerLeft, widthFactor: progress, child: ClipRRect( borderRadius: BorderRadius.circular(1), child: ColoredBox( color: theme.foregroundColor, ), ), ); }, ), ), ), ), ); } }
very_good_ranch/packages/ranch_ui/lib/src/widgets/progress_bar/widget.dart/0
{'file_path': 'very_good_ranch/packages/ranch_ui/lib/src/widgets/progress_bar/widget.dart', 'repo_id': 'very_good_ranch', 'token_count': 853}
import 'package:dashbook/dashbook.dart'; import 'package:flutter/widgets.dart'; import 'package:ranch_ui/ranch_ui.dart'; void addUnicornCounterStories(Dashbook dashbook) { dashbook.storiesOf('UnicornCounter').add('Playground', (context) { return Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, children: [ UnicornCounterTheme( data: UnicornCounterTheme.defaultTheme, child: const UnicornCounter( isActive: true, type: UnicornType.baby, child: Text('1'), ), ), const SizedBox(height: 16), UnicornCounterTheme( data: UnicornCounterTheme.defaultTheme, child: const UnicornCounter( isActive: true, type: UnicornType.child, child: Text('1'), ), ), const SizedBox(height: 16), UnicornCounterTheme( data: UnicornCounterTheme.defaultTheme, child: const UnicornCounter( isActive: true, type: UnicornType.teen, child: Text('1'), ), ), const SizedBox(height: 16), UnicornCounterTheme( data: UnicornCounterTheme.defaultTheme, child: const UnicornCounter( isActive: true, type: UnicornType.adult, child: Text('0'), ), ), ], ); }); }
very_good_ranch/packages/ranch_ui/sandbox/lib/stories/unicorn_counter/stories.dart/0
{'file_path': 'very_good_ranch/packages/ranch_ui/sandbox/lib/stories/unicorn_counter/stories.dart', 'repo_id': 'very_good_ranch', 'token_count': 689}
// ignore_for_file: cascade_invocations import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:very_good_ranch/game/entities/food/behaviors/behaviors.dart'; import 'package:very_good_ranch/game/entities/food/food.dart'; import '../../../../helpers/helpers.dart'; void main() { final flameTester = FlameTester(TestGame.new); group('DespawningBehavior', () { flameTester.testGameWidget( 'removes parent after given despawn time', setUp: (game, tester) async { await game.ensureAdd( Food.test( behaviors: [ DraggingBehavior(), DespawningBehavior(despawnTime: 1), ], ), ); await game.ready(); }, verify: (game, tester) async { final food = game.descendants().whereType<Food>().first; game.update(0.5); expect(food.isRemoving, isFalse); game.update(0.5); expect(food.isRemoving, isTrue); }, ); flameTester.testGameWidget( 'should not remove when we are dragging the parent', setUp: (game, tester) async { await game.ensureAdd( Food.test( behaviors: [ DraggingBehavior(), DespawningBehavior(despawnTime: 1), ], ), ); await game.ready(); }, verify: (game, tester) async { final food = game.descendants().whereType<Food>().first; game.update(0.5); expect(food.isRemoving, isFalse); final gesture = await tester.createGesture(); await gesture.down(Offset.zero); await gesture.moveTo(const Offset(100, 100)); await tester.pump(); game.update(0.5); expect(food.isRemoving, isFalse); await gesture.up(); await tester.pump(); await tester.pump(); game.update(1); expect(food.isRemoving, isTrue); game.pauseEngine(); await tester.pumpAndSettle(); }, ); }); }
very_good_ranch/test/game/entities/food/behaviors/despawning_behavior_test.dart/0
{'file_path': 'very_good_ranch/test/game/entities/food/behaviors/despawning_behavior_test.dart', 'repo_id': 'very_good_ranch', 'token_count': 960}
import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockingjay/mockingjay.dart'; import 'package:very_good_ranch/game_menu/game_menu.dart'; import 'package:very_good_ranch/game_menu/view/credits_dialog_page.dart'; import 'package:very_good_ranch/l10n/l10n.dart'; import '../../helpers/helpers.dart'; void main() { group('CreditsDialogPage', () { testWidgets('renders correctly', (tester) async { final l10n = await AppLocalizations.delegate.load(const Locale('en')); await tester.pumpApp( const CreditsDialogPage(), ); expect(find.text(l10n.credits), findsOneWidget); expect(find.byType(ElevatedButton), findsOneWidget); expect(find.text(l10n.ok), findsOneWidget); // credits content expect(find.text(l10n.gameTitle), findsOneWidget); expect(find.text(l10n.byVGV), findsOneWidget); expect(find.text(l10n.programming), findsOneWidget); expect(find.text(l10n.music), findsOneWidget); expect(find.text(l10n.artCredits), findsOneWidget); expect(find.text(l10n.uIDesign), findsOneWidget); expect(find.text(l10n.librariesCredits), findsOneWidget); expect(find.text(l10n.showLicensesPage), findsOneWidget); expect(find.text(l10n.noCrueltyDisclaimer), findsOneWidget); }); group('Action button', () { testWidgets('Pressing ok goes back to settings', (tester) async { final l10n = await AppLocalizations.delegate.load(const Locale('en')); final navigator = MockNavigator(); when(() => navigator.pushReplacementNamed<void, void>(any())) .thenAnswer((_) async {}); await tester.pumpApp( const CreditsDialogPage(), navigator: navigator, ); await Scrollable.ensureVisible(find.text(l10n.ok).evaluate().first); await tester.tap(find.text(l10n.ok)); verify( () => navigator.pushReplacementNamed<void, void>( GameMenuRoute.settings.name, ), ).called(1); }); }); group('Licenses button', () { testWidgets('Pressing "show licenses" shows licenses', (tester) async { final l10n = await AppLocalizations.delegate.load(const Locale('en')); final navigator = MockNavigator(); when(() => navigator.push<void>(any())).thenAnswer((_) async {}); await tester.pumpApp( const CreditsDialogPage(), rootNavigator: navigator, ); await Scrollable.ensureVisible( find.text(l10n.showLicensesPage).evaluate().first, ); await tester.tap(find.text(l10n.showLicensesPage)); final captured = verify( () => navigator.push<void>( captureAny( that: isA<MaterialPageRoute<void>>(), ), ), ).captured; expect(captured.length, 1); final licensesRoute = captured.first as MaterialPageRoute<void>; await tester.pumpApp( Builder( builder: licensesRoute.builder, ), ); await tester.pumpAndSettle(); expect(find.byType(LicensePage), findsOneWidget); }); }); }); }
very_good_ranch/test/game_menu/view/credits_dialog_page_test.dart/0
{'file_path': 'very_good_ranch/test/game_menu/view/credits_dialog_page_test.dart', 'repo_id': 'very_good_ranch', 'token_count': 1384}
name: very_good_wear_app_hooks on: pull_request: paths: - ".github/workflows/very_good_wear_app_hooks.yaml" - "brick/hooks/**" push: branches: - main paths: - ".github/workflows/very_good_wear_app_hooks.yaml" - "brick/hooks/**" jobs: build: uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/dart_package.yml@v1 with: working_directory: "brick/hooks" analyze_directories: "test" report_on: "pre_gen.dart"
very_good_wear_app/.github/workflows/very_good_wear_app_hooks.yaml/0
{'file_path': 'very_good_wear_app/.github/workflows/very_good_wear_app_hooks.yaml', 'repo_id': 'very_good_wear_app', 'token_count': 233}
name: very_good_wear_app_hooks environment: sdk: ">=3.0.0 <4.0.0" dependencies: mason: ^0.1.0-dev.50 dev_dependencies: mocktail: ^1.0.0 test: ^1.25.0 very_good_analysis: ^5.1.0
very_good_wear_app/brick/hooks/pubspec.yaml/0
{'file_path': 'very_good_wear_app/brick/hooks/pubspec.yaml', 'repo_id': 'very_good_wear_app', 'token_count': 99}
name: dart_package description: An example Dart package created with very_good_cli version: 1.0.0+1 publish_to: none environment: sdk: ">=2.19.0 <3.0.0" dev_dependencies: test: ^1.19.2 very_good_analysis: ^4.0.0
very_good_workflows/examples/dart_package/pubspec.yaml/0
{'file_path': 'very_good_workflows/examples/dart_package/pubspec.yaml', 'repo_id': 'very_good_workflows', 'token_count': 92}
import 'package:flutter/material.dart'; import 'transparent_route.dart'; void popToFirst(BuildContext context) => Navigator.of(context).popUntil( (route) => route.isFirst, ); void popView(BuildContext context) => Navigator.pop(context); void animatedNavigation( Widget screen, BuildContext context, ) { Navigator.pushReplacement( context, PageRouteBuilder( pageBuilder: (_, __, ___) => screen, transitionsBuilder: (_, animation, __, child) => FadeTransition(opacity: animation, child: child), transitionDuration: const Duration( seconds: 4, ), ), ); } Future<void> navigateReplace( BuildContext context, Widget route, { bool isDialog = false, }) => Navigator.pushReplacement( context, MaterialPageRoute( fullscreenDialog: isDialog, builder: (context) => route, ), ); Future<void> navigate( BuildContext context, Widget route, { bool isDialog = false, }) => Navigator.push( context, // ignore: always_specify_types MaterialPageRoute( fullscreenDialog: isDialog, // ignore: always_specify_types builder: (context) => route, ), ); Future<void> pushAndRemoveUntil(BuildContext context, Widget newRoute) => Navigator.of(context).pushAndRemoveUntil( // ignore: always_specify_types MaterialPageRoute( // ignore: always_specify_types builder: (context) => newRoute, ), // ignore: always_specify_types (route) => false, ); Future<void> navigateTransparentRoute(BuildContext context, Widget route) { return Navigator.push( context, TransparentRoute( // ignore: always_specify_types builder: (context) => route, ), ); }
vigo-interview/lib/src/utils/navigation/src/navigation.dart/0
{'file_path': 'vigo-interview/lib/src/utils/navigation/src/navigation.dart', 'repo_id': 'vigo-interview', 'token_count': 686}
class MkRoutes { static const String dashboard = '/dashboard'; static const String start = '/start'; static const String verify = '/verify'; }
voute/lib/constants/mk_routes.dart/0
{'file_path': 'voute/lib/constants/mk_routes.dart', 'repo_id': 'voute', 'token_count': 41}
import 'dart:async'; import 'dart:math'; import 'package:voute/models/config.dart'; import 'package:voute/models/mock.dart'; import 'package:voute/services/config.dart'; class ConfigMockImpl extends Config { @override Future<ConfigModel> fetch() async { await Future<dynamic>.delayed(const Duration(seconds: 5)); final _int = Random().nextInt(1); if (_int > .9) { throw Exception("Please try again. $_int"); } return MockModel.config; } }
voute/lib/services/_mocks/config.dart/0
{'file_path': 'voute/lib/services/_mocks/config.dart', 'repo_id': 'voute', 'token_count': 173}
import 'dart:async' show Future; import 'dart:convert' show json; import 'package:shared_preferences/shared_preferences.dart'; class MkPrefs { static Future<SharedPreferences> _prefs; static Future<SharedPreferences> _getInstance() { _prefs ??= SharedPreferences.getInstance(); return _prefs; } static Future<String> getString(String key) async => (await _getInstance()).getString(key) ?? ''; static Future<String> setString(String key, String value) async { await (await _getInstance()).setString(key, value); return value; } static Future<Map<String, dynamic>> getMap(String key) async { try { final _map = await getString(key); return _map.isEmpty ? null : json.decode(_map); } catch (e) { return null; } } static Future<Map<String, dynamic>> setMap(String key, Map<String, dynamic> value) async { await setString(key, json.encode(value)); return value; } static Future<int> getInt(String key) async => (await _getInstance()).getInt(key); static Future<int> setInt(String key, int value) async { await (await _getInstance()).setInt(key, value); return value; } static Future<bool> getBool(String key) async => (await _getInstance()).getBool(key); static Future<bool> setBool(String key, bool value) async { await (await _getInstance()).setBool(key, value); return value; } static Future<bool> contains(String key) async => (await _getInstance()).containsKey(key); static Future<bool> remove(String key) async => (await _getInstance()).remove(key); }
voute/lib/utils/mk_prefs.dart/0
{'file_path': 'voute/lib/utils/mk_prefs.dart', 'repo_id': 'voute', 'token_count': 544}
import 'package:flutter/material.dart'; import 'package:voute/utils/mk_screen_util.dart'; import 'package:voute/utils/mk_theme.dart'; class SuccessMessageDialog extends StatelessWidget { const SuccessMessageDialog({Key key, @required this.message}) : super(key: key); final String message; @override Widget build(BuildContext context) { final MkTheme theme = MkTheme.of(context); return Padding( padding: EdgeInsets.symmetric(horizontal: sw(64)), child: Center( child: Material( borderRadius: BorderRadius.circular(4), color: Colors.white, child: Padding( padding: EdgeInsets.symmetric(horizontal: sw(32), vertical: sh(36)), child: Opacity( opacity: .75, child: Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ SizedBox.fromSize(size: Size.square(sf(100.0)), child: Icon(Icons.check)), if (message != null) ...[ SizedBox(height: sh(16.0)), Text( message, style: theme.small.copyWith(fontWeight: FontWeight.w600), textAlign: TextAlign.center, ) ] ], ), ), ), ), ), ); } }
voute/lib/widgets/_dialogs/success_message_dialog.dart/0
{'file_path': 'voute/lib/widgets/_dialogs/success_message_dialog.dart', 'repo_id': 'voute', 'token_count': 771}
import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; import 'package:injector/injector.dart'; import 'package:voute/environments/environment.dart'; import 'package:voute/models/user/user.dart'; import 'package:voute/services/_api/config.dart'; import 'package:voute/services/_api/users.dart'; import 'package:voute/services/_mocks/config.dart'; import 'package:voute/services/_mocks/users.dart'; import 'package:voute/services/config.dart'; import 'package:voute/services/users.dart'; import 'package:voute/utils/mk_first_time_check.dart'; import 'package:voute/utils/mk_logger.dart'; import 'package:voute/utils/mk_remember_me_provider.dart'; import 'package:voute/utils/mk_version_check.dart'; Future<BootstrapModel> bootstrap(Env env, [bool isTestMode = false]) async { final _env = Environment(env); MkLogger.init(_env.isDev); Injector.appInstance ..registerSingleton<Environment>((_) => Environment(env)) ..registerSingleton<Users>((_) => _env.isMock ? UsersMockImpl() : UsersImpl()) ..registerSingleton<Config>((_) => _env.isMock ? ConfigMockImpl() : ConfigImpl()); final isFirstTime = await MkFirstTimeCheck.init(_env); try { await MkVersionCheck.init(_env); if (_env.isMock) { return BootstrapModel(isFirstTime: true, isTestMode: isTestMode, user: null); } UserModel user; final model = await MkRememberMeProvider.get(); if (model != null) { user = await Users.di().fetch(model.id); } return BootstrapModel(user: user, isTestMode: isTestMode, isFirstTime: isFirstTime); } catch (e) { MkLogger.d('$e'); } return BootstrapModel(user: null, isFirstTime: false); } class BootstrapModel { const BootstrapModel({@required this.user, @required this.isFirstTime, this.isTestMode = false}) : isRemembered = user != null; final UserModel user; final bool isFirstTime; final bool isRemembered; final bool isTestMode; }
voute/lib/widgets/bootstrap.dart/0
{'file_path': 'voute/lib/widgets/bootstrap.dart', 'repo_id': 'voute', 'token_count': 691}
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; import 'package:string_scanner/string_scanner.dart'; class SyntaxHighlighterStyle { SyntaxHighlighterStyle( {this.baseStyle, this.numberStyle, this.commentStyle, this.keywordStyle, this.stringStyle, this.punctuationStyle, this.classStyle, this.constantStyle}); static SyntaxHighlighterStyle lightThemeStyle() { return SyntaxHighlighterStyle( baseStyle: const TextStyle(color: Color(0xFF000000)), numberStyle: const TextStyle(color: Color(0xFF1565C0)), commentStyle: const TextStyle(color: Color(0xFF9E9E9E)), keywordStyle: const TextStyle(color: Color(0xFF9C27B0)), stringStyle: const TextStyle(color: Color(0xFF43A047)), punctuationStyle: const TextStyle(color: Color(0xFF000000)), classStyle: const TextStyle(color: Color(0xFF512DA8)), constantStyle: const TextStyle(color: Color(0xFF795548))); } static SyntaxHighlighterStyle darkThemeStyle() { return SyntaxHighlighterStyle( baseStyle: const TextStyle(color: Color(0xFFFFFFFF)), numberStyle: const TextStyle(color: Color(0xFF1565C0)), commentStyle: const TextStyle(color: Color(0xFF9E9E9E)), keywordStyle: const TextStyle(color: Color(0xFF80CBC4)), stringStyle: const TextStyle(color: Color(0xFF009688)), punctuationStyle: const TextStyle(color: Color(0xFFFFFFFF)), classStyle: const TextStyle(color: Color(0xFF009688)), constantStyle: const TextStyle(color: Color(0xFF795548))); } final TextStyle baseStyle; final TextStyle numberStyle; final TextStyle commentStyle; final TextStyle keywordStyle; final TextStyle stringStyle; final TextStyle punctuationStyle; final TextStyle classStyle; final TextStyle constantStyle; } abstract class SyntaxHighlighter { TextSpan format(String src); } class DartSyntaxHighlighter extends SyntaxHighlighter { DartSyntaxHighlighter([this._style]) { _spans = <_HighlightSpan>[]; _style ??= SyntaxHighlighterStyle.darkThemeStyle(); } SyntaxHighlighterStyle _style; static const List<String> _keywords = <String>[ 'abstract', 'as', 'assert', 'async', 'await', 'break', 'case', 'catch', 'class', 'const', 'continue', 'default', 'deferred', 'do', 'dynamic', 'else', 'enum', 'export', 'external', 'extends', 'factory', 'false', 'final', 'finally', 'for', 'get', 'if', 'implements', 'import', 'in', 'is', 'library', 'new', 'null', 'operator', 'part', 'rethrow', 'return', 'set', 'static', 'super', 'switch', 'sync', 'this', 'throw', 'true', 'try', 'typedef', 'var', 'void', 'while', 'with', 'yield' ]; static const List<String> _builtInTypes = <String>[ 'int', 'double', 'num', 'bool' ]; String _src; StringScanner _scanner; List<_HighlightSpan> _spans; @override TextSpan format(String src) { _src = src; _scanner = StringScanner(_src); if (_generateSpans()) { // Successfully parsed the code final List<TextSpan> formattedText = <TextSpan>[]; int currentPosition = 0; for (_HighlightSpan span in _spans) { if (currentPosition != span.start) formattedText .add(TextSpan(text: _src.substring(currentPosition, span.start))); formattedText.add(TextSpan( style: span.textStyle(_style), text: span.textForSpan(_src))); currentPosition = span.end; } if (currentPosition != _src.length) formattedText .add(TextSpan(text: _src.substring(currentPosition, _src.length))); return TextSpan(style: _style.baseStyle, children: formattedText); } else { // Parsing failed, return with only basic formatting return TextSpan(style: _style.baseStyle, text: src); } } bool _generateSpans() { int lastLoopPosition = _scanner.position; while (!_scanner.isDone) { // Skip White space _scanner.scan(RegExp(r'\s+')); // Block comments if (_scanner.scan(RegExp(r'/\*(.|\n)*\*/'))) { _spans.add(_HighlightSpan(_HighlightType.comment, _scanner.lastMatch.start, _scanner.lastMatch.end)); continue; } // Line comments if (_scanner.scan('//')) { final int startComment = _scanner.lastMatch.start; bool eof = false; int endComment; if (_scanner.scan(RegExp(r'.*\n'))) { endComment = _scanner.lastMatch.end - 1; } else { eof = true; endComment = _src.length; } _spans.add( _HighlightSpan(_HighlightType.comment, startComment, endComment)); if (eof) break; continue; } // Raw r"String" if (_scanner.scan(RegExp(r'r".*"'))) { _spans.add(_HighlightSpan(_HighlightType.string, _scanner.lastMatch.start, _scanner.lastMatch.end)); continue; } // Raw r'String' if (_scanner.scan(RegExp(r"r'.*'"))) { _spans.add(_HighlightSpan(_HighlightType.string, _scanner.lastMatch.start, _scanner.lastMatch.end)); continue; } // Multiline """String""" if (_scanner.scan(RegExp(r'"""(?:[^"\\]|\\(.|\n))*"""'))) { _spans.add(_HighlightSpan(_HighlightType.string, _scanner.lastMatch.start, _scanner.lastMatch.end)); continue; } // Multiline '''String''' if (_scanner.scan(RegExp(r"'''(?:[^'\\]|\\(.|\n))*'''"))) { _spans.add(_HighlightSpan(_HighlightType.string, _scanner.lastMatch.start, _scanner.lastMatch.end)); continue; } // "String" if (_scanner.scan(RegExp(r'"(?:[^"\\]|\\.)*"'))) { _spans.add(_HighlightSpan(_HighlightType.string, _scanner.lastMatch.start, _scanner.lastMatch.end)); continue; } // 'String' if (_scanner.scan(RegExp(r"'(?:[^'\\]|\\.)*'"))) { _spans.add(_HighlightSpan(_HighlightType.string, _scanner.lastMatch.start, _scanner.lastMatch.end)); continue; } // Double if (_scanner.scan(RegExp(r'\d+\.\d+'))) { _spans.add(_HighlightSpan(_HighlightType.number, _scanner.lastMatch.start, _scanner.lastMatch.end)); continue; } // Integer if (_scanner.scan(RegExp(r'\d+'))) { _spans.add(_HighlightSpan(_HighlightType.number, _scanner.lastMatch.start, _scanner.lastMatch.end)); continue; } // Punctuation if (_scanner.scan(RegExp(r'[\[\]{}().!=<>&\|\?\+\-\*/%\^~;:,]'))) { _spans.add(_HighlightSpan(_HighlightType.punctuation, _scanner.lastMatch.start, _scanner.lastMatch.end)); continue; } // Meta data if (_scanner.scan(RegExp(r'@\w+'))) { _spans.add(_HighlightSpan(_HighlightType.keyword, _scanner.lastMatch.start, _scanner.lastMatch.end)); continue; } // Words if (_scanner.scan(RegExp(r'\w+'))) { _HighlightType type; String word = _scanner.lastMatch[0]; if (word.startsWith('_')) word = word.substring(1); if (_keywords.contains(word)) type = _HighlightType.keyword; else if (_builtInTypes.contains(word)) type = _HighlightType.keyword; else if (_firstLetterIsUpperCase(word)) type = _HighlightType.klass; else if (word.length >= 2 && word.startsWith('k') && _firstLetterIsUpperCase(word.substring(1))) type = _HighlightType.constant; if (type != null) { _spans.add(_HighlightSpan( type, _scanner.lastMatch.start, _scanner.lastMatch.end)); } } // Check if this loop did anything if (lastLoopPosition == _scanner.position) { // Failed to parse this file, abort gracefully return false; } lastLoopPosition = _scanner.position; } _simplify(); return true; } void _simplify() { for (int i = _spans.length - 2; i >= 0; i -= 1) { if (_spans[i].type == _spans[i + 1].type && _spans[i].end == _spans[i + 1].start) { _spans[i] = _HighlightSpan(_spans[i].type, _spans[i].start, _spans[i + 1].end); _spans.removeAt(i + 1); } } } bool _firstLetterIsUpperCase(String str) { if (str.isNotEmpty) { final String first = str.substring(0, 1); return first == first.toUpperCase(); } return false; } } enum _HighlightType { number, comment, keyword, string, punctuation, klass, constant } class _HighlightSpan { _HighlightSpan(this.type, this.start, this.end); final _HighlightType type; final int start; final int end; String textForSpan(String src) { return src.substring(start, end); } TextStyle textStyle(SyntaxHighlighterStyle style) { if (type == _HighlightType.number) return style.numberStyle; else if (type == _HighlightType.comment) return style.commentStyle; else if (type == _HighlightType.keyword) return style.keywordStyle; else if (type == _HighlightType.string) return style.stringStyle; else if (type == _HighlightType.punctuation) return style.punctuationStyle; else if (type == _HighlightType.klass) return style.classStyle; else if (type == _HighlightType.constant) return style.constantStyle; else return style.baseStyle; } }
vscode_ipad/lib/utils/highlighter.dart/0
{'file_path': 'vscode_ipad/lib/utils/highlighter.dart', 'repo_id': 'vscode_ipad', 'token_count': 4400}
import 'dart:math'; import 'package:flutter/material.dart'; import 'package:wallet_app_workshop/core/data.dart'; import 'package:wallet_app_workshop/core/utils.dart'; import 'package:wallet_app_workshop/credit-cards/credit_card.dart'; import 'package:wallet_app_workshop/credit-cards/credit_card_page.dart'; const dragSnapDuration = Duration(milliseconds: 200); const pageTransitionDuration = Duration(milliseconds: 800); const dragThreshold = Offset(70, 70); const minCardScale = 0.6; const maxCardScale = 1.0; const cardsOffset = 12.0; const minThrowDistance = 300.0; class CreditCardsPage extends StatefulWidget { const CreditCardsPage({ super.key, this.onCardPagePush, this.onCardPagePop, }); final VoidCallback? onCardPagePush; final VoidCallback? onCardPagePop; @override State<CreditCardsPage> createState() => _CreditCardsPageState(); } class _CreditCardsPageState extends State<CreditCardsPage> { int activeCard = 0; @override Widget build(BuildContext context) { final screenSize = MediaQuery.of(context).size; final cardHeight = screenSize.width * 0.75; final cardWidth = cardHeight * creditCardAspectRatio; return Center( child: SizedBox( width: cardHeight, height: cardWidth + (cardsOffset * (cards.length - 1)), child: CreditCardsStack( itemCount: cards.length, initialActiveCard: activeCard, onCardTap: (index) { pushFadeInRoute( context, pageBuilder: (context, animation, __) => CreditCardPage( initialIndex: index, pageTransitionAnimation: animation, ), ).then((value) { if (value != null && value is int) { setState(() { activeCard = value; }); } }); }, itemBuilder: (context, index) { return Align( widthFactor: cardHeight / cardWidth, heightFactor: cardWidth / cardHeight, child: Hero( tag: 'card_${cards[index].id}', flightShuttleBuilder: ( BuildContext context, Animation<double> animation, _, __, ___, ) { final rotationAnimation = Tween<double>(begin: -pi / 2, end: pi).animate( CurvedAnimation( parent: animation, curve: Curves.easeOut, ), ); final flipAnimation = Tween<double>(begin: 0, end: pi).animate( CurvedAnimation( parent: animation, curve: const Interval( 0.3, 1, curve: Curves.easeOut, ), ), ); return Material( color: Colors.transparent, child: AnimatedBuilder( animation: animation, builder: (context, child) { return Transform( transform: Matrix4.identity() ..setEntry(3, 2, 0.001) ..rotateZ(rotationAnimation.value) ..rotateX(flipAnimation.value), alignment: Alignment.center, child: Transform.flip( flipX: animation.value > 0.5, child: CreditCard( width: cardWidth, data: cards[index], isFront: animation.value > 0.5, ), ), ); }, ), ); }, child: Transform.rotate( angle: -pi / 2, child: CreditCard( width: cardWidth, data: cards[index], ), ), ), ); }, ), ), ); } } class CreditCardsStack extends StatefulWidget { const CreditCardsStack({ required this.itemCount, required this.itemBuilder, super.key, this.onCardTap, this.initialActiveCard = 0, }); final int itemCount; final Widget Function(BuildContext, int) itemBuilder; final ValueChanged<int>? onCardTap; final int initialActiveCard; @override State<CreditCardsStack> createState() => _CreditCardsStackState(); } class _CreditCardsStackState extends State<CreditCardsStack> with SingleTickerProviderStateMixin { late final AnimationController animationController; late final Animation<double> curvedAnimation; late final Animation<Offset> throwAnimation; late final Tween<Offset> throwAnimationTween; late int activeIndex; Offset dragOffset = Offset.zero; Duration dragDuration = Duration.zero; double get scaleDifference => (maxCardScale - minCardScale) / (widget.itemCount - 1); Future<void> _handleDismiss() async { throwAnimationTween.end = getThrowOffsetFromDragLocation( dragOffset, minThrowDistance, ); await animationController.forward(); setState(() { activeIndex++; }); animationController.reset(); } void _onPanStart(DragStartDetails details) { if (dragDuration > Duration.zero) { dragDuration = Duration.zero; } } void _onPanUpdate(DragUpdateDetails details) { setState(() { dragOffset += details.delta; }); } void _onPanEnd(DragEndDetails details) { if (dragOffset.dx.abs() > dragThreshold.dx || dragOffset.dy.abs() > dragThreshold.dy) { _handleDismiss().then((value) { setState(() { dragOffset = Offset.zero; }); }); } else { dragDuration = dragSnapDuration; setState(() { dragOffset = Offset.zero; }); } } @override void initState() { super.initState(); activeIndex = widget.initialActiveCard; animationController = AnimationController( vsync: this, duration: const Duration(milliseconds: 200), ); curvedAnimation = CurvedAnimation( parent: animationController, curve: Curves.easeOut, ); throwAnimationTween = Tween<Offset>( begin: Offset.zero, end: const Offset(minThrowDistance, minThrowDistance), ); throwAnimation = throwAnimationTween.animate(curvedAnimation); } @override void didUpdateWidget(covariant CreditCardsStack oldWidget) { super.didUpdateWidget(oldWidget); if (widget.initialActiveCard != oldWidget.initialActiveCard) { setState(() { activeIndex = widget.initialActiveCard; }); } } @override void dispose() { animationController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return AnimatedBuilder( animation: animationController, builder: (context, child) { return Stack( clipBehavior: Clip.none, children: List.generate( widget.itemCount + 1, (stackIndexWithPlaceholder) { final index = stackIndexWithPlaceholder - 1; final modIndex = getModIndexFromActiveIndex( index, activeIndex, widget.itemCount, ); final child = widget.itemBuilder(context, modIndex); if (stackIndexWithPlaceholder == 0) { return Positioned( top: 0, left: 0, child: Transform.scale( scale: minCardScale, alignment: Alignment.topCenter, child: HeroMode( enabled: false, child: child, ), ), ); } // Build the last, draggable card if (index == widget.itemCount - 1) { return AnimatedPositioned( duration: dragDuration, left: dragOffset.dx, bottom: -dragOffset.dy, child: Transform.translate( offset: throwAnimation.value, child: GestureDetector( onPanStart: _onPanStart, onPanUpdate: _onPanUpdate, onPanEnd: _onPanEnd, onTap: dragOffset == Offset.zero ? () => widget.onCardTap?.call(modIndex) : null, behavior: HitTestBehavior.opaque, child: Opacity( opacity: 1 - curvedAnimation.value, child: child, ), ), ), ); } // Build the cards in between (remaining cards) /// To gradually scale down widgets, limited by min and max scales final scaleByIndex = minCardScale + ((maxCardScale - minCardScale) / (widget.itemCount - 1)) * index; // Slide cards up gradually final bottomOffsetByIndex = -cardsOffset * (widget.itemCount - 1 - index); return Positioned( left: 0, bottom: 0, child: Transform.translate( offset: Offset( 0, bottomOffsetByIndex + cardsOffset * curvedAnimation.value, ), child: Transform.scale( scale: scaleByIndex + scaleDifference * curvedAnimation.value, alignment: Alignment.topCenter, child: child, ), ), ); }, ), ); }, ); } } Future<dynamic> pushFadeInRoute( BuildContext context, { required RoutePageBuilder pageBuilder, }) { return Navigator.of(context).push( PageRouteBuilder( pageBuilder: pageBuilder, transitionDuration: pageTransitionDuration, reverseTransitionDuration: pageTransitionDuration, transitionsBuilder: ( BuildContext context, Animation<double> animation, _, Widget child, ) { return FadeTransition( opacity: CurvedAnimation( parent: animation, curve: Curves.easeOut, ), child: child, ); }, ), ); }
wallet_app_workshop/lib/credit-cards/credit_cards_page.dart/0
{'file_path': 'wallet_app_workshop/lib/credit-cards/credit_cards_page.dart', 'repo_id': 'wallet_app_workshop', 'token_count': 5573}
const String _svgDir = 'assets/svgs'; const String _homeSvgDir = '$_svgDir/home'; const String _watchesSvgDir = '$_svgDir/watches'; /// [Home] /// const String kHomeMenuSvg = '$_homeSvgDir/menu.svg'; const String kHomeSearchSvg = '$_homeSvgDir/search.svg'; /// [Watches] /// const String kWatchesLikeSvg = '$_watchesSvgDir/like.svg'; const String kWatchesBackArrowSvg = '$_watchesSvgDir/back_arrow.svg';
watch-store/lib/src/assets/svgs.dart/0
{'file_path': 'watch-store/lib/src/assets/svgs.dart', 'repo_id': 'watch-store', 'token_count': 163}
// Copyright 2020 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io' as io; import 'package:test/test.dart'; import 'package:web_driver_installer/chrome_driver_installer.dart'; void main() async { void deleteInstallationIfExists() { final io.Directory driverInstallationDir = io.Directory('chromedriver'); if (driverInstallationDir.existsSync()) { driverInstallationDir.deleteSync(recursive: true); } } setUpAll(() { deleteInstallationIfExists(); }); tearDown(() { deleteInstallationIfExists(); }); test('installs chrome driver', () async { ChromeDriverInstaller command = ChromeDriverInstaller(); expect(command.isInstalled, isFalse); await command.install(); expectLater(command.isInstalled, isTrue); }); test('get chrome version on MacOS', () async { String executable = await ChromeDriverInstaller().findChromeExecutableOnMac(); final io.ProcessResult processResult = await io.Process.run(executable, <String>['--version']); expect(processResult.exitCode, 0); expect(processResult.stdout.toString().startsWith('Google Chrome'), isTrue); }, skip: !io.Platform.isMacOS); }
web_installers/packages/web_drivers/test/chrome_driver_installer_test.dart/0
{'file_path': 'web_installers/packages/web_drivers/test/chrome_driver_installer_test.dart', 'repo_id': 'web_installers', 'token_count': 413}
// ignore_for_file: avoid_print import 'package:web_socket_client/web_socket_client.dart'; void main() async { // Create a WebSocket client. final uri = Uri.parse('ws://localhost:8080'); const backoff = ConstantBackoff(Duration(seconds: 1)); final socket = WebSocket(uri, backoff: backoff); // Listen for changes in the connection state. socket.connection.listen((state) => print('state: "$state"')); // Listen for incoming messages. socket.messages.listen((message) { print('message: "$message"'); // Send a message to the server. socket.send('ping'); }); await Future<void>.delayed(const Duration(seconds: 3)); // Close the connection. socket.close(); }
web_socket_client/example/main.dart/0
{'file_path': 'web_socket_client/example/main.dart', 'repo_id': 'web_socket_client', 'token_count': 218}
import 'package:test/test.dart'; import 'package:web_socket_client/web_socket_client.dart'; void main() { group('BinaryExponentialBackoff', () { test('next() returns a binary exponentially increasing duration.', () { const initial = Duration(seconds: 1); const maximumStep = 3; final backoff = BinaryExponentialBackoff( initial: initial, maximumStep: maximumStep, ); const expected = [ Duration(seconds: 1), Duration(seconds: 2), Duration(seconds: 4), ]; final actual = List.generate(expected.length, (_) => backoff.next()); expect(actual, equals(expected)); }); test('next() does not exceed maximum duration.', () { const initial = Duration(seconds: 1); const maximumStep = 5; final backoff = BinaryExponentialBackoff( initial: initial, maximumStep: maximumStep, ); const expected = [ Duration(seconds: 1), Duration(seconds: 2), Duration(seconds: 4), Duration(seconds: 8), Duration(seconds: 16), Duration(seconds: 16), Duration(seconds: 16), Duration(seconds: 16), Duration(seconds: 16), Duration(seconds: 16), ]; final actual = List.generate(expected.length, (_) => backoff.next()); expect(actual, equals(expected)); }); test('reset() resets the backoff.', () { const initial = Duration(seconds: 1); const maximumStep = 5; final backoff = BinaryExponentialBackoff( initial: initial, maximumStep: maximumStep, ); expect(backoff.next(), equals(initial)); expect(backoff.next(), equals(initial * 2)); expect(backoff.reset, returnsNormally); expect(backoff.next(), equals(initial)); }); }); }
web_socket_client/test/src/backoff/binary_exponential_backoff_test.dart/0
{'file_path': 'web_socket_client/test/src/backoff/binary_exponential_backoff_test.dart', 'repo_id': 'web_socket_client', 'token_count': 716}
import 'package:flutter/material.dart'; void main() => runApp(const SnackBarDemo()); class SnackBarDemo extends StatelessWidget { const SnackBarDemo({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'SnackBar Demo', // #docregion Scaffold home: Scaffold( appBar: AppBar( title: const Text('SnackBar Demo'), ), body: const SnackBarPage(), ), // #enddocregion Scaffold ); } } class SnackBarPage extends StatelessWidget { const SnackBarPage({super.key}); @override Widget build(BuildContext context) { return Center( child: ElevatedButton( onPressed: () { // #docregion SnackBarAction final snackBar = SnackBar( content: const Text('Yay! A SnackBar!'), action: SnackBarAction( label: 'Undo', onPressed: () { // Some code to undo the change. }, ), ); // #enddocregion SnackBarAction // Find the ScaffoldMessenger in the widget tree // and use it to show a SnackBar. ScaffoldMessenger.of(context).showSnackBar(snackBar); }, child: const Text('Show SnackBar'), ), ); } }
website/examples/cookbook/design/snackbars/lib/main.dart/0
{'file_path': 'website/examples/cookbook/design/snackbars/lib/main.dart', 'repo_id': 'website', 'token_count': 600}
import 'package:flutter/material.dart'; // #docregion LocationListItem @immutable class LocationListItem extends StatelessWidget { const LocationListItem({ super.key, required this.imageUrl, required this.name, required this.country, }); final String imageUrl; final String name; final String country; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16), child: AspectRatio( aspectRatio: 16 / 9, child: ClipRRect( borderRadius: BorderRadius.circular(16), child: Stack( children: [ _buildParallaxBackground(context), _buildGradient(), _buildTitleAndSubtitle(), ], ), ), ), ); } Widget _buildParallaxBackground(BuildContext context) { return Positioned.fill( child: Image.network( imageUrl, fit: BoxFit.cover, ), ); } Widget _buildGradient() { return Positioned.fill( child: DecoratedBox( decoration: BoxDecoration( gradient: LinearGradient( colors: [Colors.transparent, Colors.black.withOpacity(0.7)], begin: Alignment.topCenter, end: Alignment.bottomCenter, stops: const [0.6, 0.95], ), ), ), ); } Widget _buildTitleAndSubtitle() { return Positioned( left: 20, bottom: 20, child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( name, style: const TextStyle( color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold, ), ), Text( country, style: const TextStyle( color: Colors.white, fontSize: 14, ), ), ], ), ); } } // #enddocregion LocationListItem
website/examples/cookbook/effects/parallax_scrolling/lib/excerpt2.dart/0
{'file_path': 'website/examples/cookbook/effects/parallax_scrolling/lib/excerpt2.dart', 'repo_id': 'website', 'token_count': 1006}
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; // #docregion TypingIndicator class TypingIndicator extends StatefulWidget { const TypingIndicator({ super.key, this.showIndicator = false, this.bubbleColor = const Color(0xFF646b7f), this.flashingCircleDarkColor = const Color(0xFF333333), this.flashingCircleBrightColor = const Color(0xFFaec1dd), }); final bool showIndicator; final Color bubbleColor; final Color flashingCircleDarkColor; final Color flashingCircleBrightColor; @override State<TypingIndicator> createState() => _TypingIndicatorState(); } class _TypingIndicatorState extends State<TypingIndicator> { @override Widget build(BuildContext context) { // TODO: return const SizedBox(); } } // #enddocregion TypingIndicator
website/examples/cookbook/effects/typing_indicator/lib/excerpt1.dart/0
{'file_path': 'website/examples/cookbook/effects/typing_indicator/lib/excerpt1.dart', 'repo_id': 'website', 'token_count': 276}
name: games_services_example description: Games services environment: sdk: ^3.2.0 dependencies: flutter: sdk: flutter games_services: ^4.0.0 logging: ^1.2.0 dev_dependencies: example_utils: path: ../../../example_utils flutter: uses-material-design: true
website/examples/cookbook/games/achievements_leaderboards/pubspec.yaml/0
{'file_path': 'website/examples/cookbook/games/achievements_leaderboards/pubspec.yaml', 'repo_id': 'website', 'token_count': 109}
import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { var title = 'Web Images'; return MaterialApp( title: title, home: Scaffold( appBar: AppBar( title: Text(title), ), // #docregion ImageNetwork body: Image.network('https://picsum.photos/250?image=9'), // #enddocregion ImageNetwork ), ); } }
website/examples/cookbook/images/network_image/lib/main.dart/0
{'file_path': 'website/examples/cookbook/images/network_image/lib/main.dart', 'repo_id': 'website', 'token_count': 216}
name: hero_animations description: Hero animations environment: sdk: ^3.2.0 dependencies: flutter: sdk: flutter dev_dependencies: example_utils: path: ../../../example_utils flutter: uses-material-design: true
website/examples/cookbook/navigation/hero_animations/pubspec.yaml/0
{'file_path': 'website/examples/cookbook/navigation/hero_animations/pubspec.yaml', 'repo_id': 'website', 'token_count': 86}
import 'package:flutter/material.dart'; class Todo { final String title; final String description; const Todo(this.title, this.description); } void main() { runApp( MaterialApp( title: 'Passing Data', home: TodosScreen( todos: List.generate( 20, (i) => Todo( 'Todo $i', 'A description of what needs to be done for Todo $i', ), ), ), ), ); } class TodosScreen extends StatelessWidget { const TodosScreen({super.key, required this.todos}); final List<Todo> todos; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Todos'), ), // #docregion builder body: ListView.builder( itemCount: todos.length, itemBuilder: (context, index) { return ListTile( title: Text(todos[index].title), // When a user taps the ListTile, navigate to the DetailScreen. // Notice that you're not only creating a DetailScreen, you're // also passing the current todo through to it. onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => const DetailScreen(), // Pass the arguments as part of the RouteSettings. The // DetailScreen reads the arguments from these settings. settings: RouteSettings( arguments: todos[index], ), ), ); }, ); }, ), // #enddocregion builder ); } } // #docregion DetailScreen class DetailScreen extends StatelessWidget { const DetailScreen({super.key}); @override Widget build(BuildContext context) { final todo = ModalRoute.of(context)!.settings.arguments as Todo; // Use the Todo to create the UI. return Scaffold( appBar: AppBar( title: Text(todo.title), ), body: Padding( padding: const EdgeInsets.all(16), child: Text(todo.description), ), ); } } // #enddocregion DetailScreen
website/examples/cookbook/navigation/passing_data/lib/main_routesettings.dart/0
{'file_path': 'website/examples/cookbook/navigation/passing_data/lib/main_routesettings.dart', 'repo_id': 'website', 'token_count': 1014}
import 'dart:async'; import 'dart:convert'; import 'package:flutter/material.dart'; // #docregion Http import 'package:http/http.dart' as http; // #enddocregion Http Future<Album> fetchAlbum() async { final response = await http.get( Uri.parse('https://jsonplaceholder.typicode.com/albums/1'), ); if (response.statusCode == 200) { // If the server did return a 200 OK response, then parse the JSON. return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>); } else { // If the server did not return a 200 OK response, then throw an exception. throw Exception('Failed to load album'); } } // #docregion deleteAlbum Future<Album> deleteAlbum(String id) async { final http.Response response = await http.delete( Uri.parse('https://jsonplaceholder.typicode.com/albums/$id'), headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8', }, ); if (response.statusCode == 200) { // If the server did return a 200 OK response, // then parse the JSON. After deleting, // you'll get an empty JSON `{}` response. // Don't return `null`, otherwise `snapshot.hasData` // will always return false on `FutureBuilder`. return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>); } else { // If the server did not return a "200 OK response", // then throw an exception. throw Exception('Failed to delete album.'); } } // #enddocregion deleteAlbum class Album { final int id; final String title; const Album({required this.id, required this.title}); factory Album.fromJson(Map<String, dynamic> json) { return switch (json) { { 'id': int id, 'title': String title, } => Album( id: id, title: title, ), _ => throw const FormatException('Failed to load album.'), }; } } void main() { runApp(const MyApp()); } class MyApp extends StatefulWidget { const MyApp({super.key}); @override State<MyApp> createState() { return _MyAppState(); } } class _MyAppState extends State<MyApp> { late Future<Album> _futureAlbum; @override void initState() { super.initState(); _futureAlbum = fetchAlbum(); } @override Widget build(BuildContext context) { return MaterialApp( title: 'Delete Data Example', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), ), home: Scaffold( appBar: AppBar( title: const Text('Delete Data Example'), ), body: Center( child: FutureBuilder<Album>( future: _futureAlbum, builder: (context, snapshot) { // If the connection is done, // check for response data or an error. if (snapshot.connectionState == ConnectionState.done) { if (snapshot.hasData) { // #docregion Column return Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text(snapshot.data?.title ?? 'Deleted'), ElevatedButton( child: const Text('Delete Data'), onPressed: () { setState(() { _futureAlbum = deleteAlbum(snapshot.data!.id.toString()); }); }, ), ], ); // #enddocregion Column } else if (snapshot.hasError) { return Text('${snapshot.error}'); } } // By default, show a loading spinner. return const CircularProgressIndicator(); }, ), ), ), ); } }
website/examples/cookbook/networking/delete_data/lib/main.dart/0
{'file_path': 'website/examples/cookbook/networking/delete_data/lib/main.dart', 'repo_id': 'website', 'token_count': 1773}
name: sqlite description: SQLITE environment: sdk: ^3.2.0 dependencies: flutter: sdk: flutter sqflite: ^2.3.0 path: ^1.8.3 dev_dependencies: example_utils: path: ../../../example_utils flutter_test: sdk: flutter flutter: uses-material-design: true
website/examples/cookbook/persistence/sqlite/pubspec.yaml/0
{'file_path': 'website/examples/cookbook/persistence/sqlite/pubspec.yaml', 'repo_id': 'website', 'token_count': 122}
import 'dart:async'; import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; // #docregion fetchAlbum Future<Album> fetchAlbum(http.Client client) async { final response = await client .get(Uri.parse('https://jsonplaceholder.typicode.com/albums/1')); if (response.statusCode == 200) { // If the server did return a 200 OK response, // then parse the JSON. return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>); } else { // If the server did not return a 200 OK response, // then throw an exception. throw Exception('Failed to load album'); } } // #enddocregion fetchAlbum class Album { final int userId; final int id; final String title; const Album({required this.userId, required this.id, required this.title}); factory Album.fromJson(Map<String, dynamic> json) { return Album( userId: json['userId'] as int, id: json['id'] as int, title: json['title'] as String, ); } } void main() => runApp(const MyApp()); class MyApp extends StatefulWidget { const MyApp({super.key}); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { late final Future<Album> futureAlbum; @override void initState() { super.initState(); futureAlbum = fetchAlbum(http.Client()); } @override Widget build(BuildContext context) { return MaterialApp( title: 'Fetch Data Example', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), ), home: Scaffold( appBar: AppBar( title: const Text('Fetch Data Example'), ), body: Center( child: FutureBuilder<Album>( future: futureAlbum, builder: (context, snapshot) { if (snapshot.hasData) { return Text(snapshot.data!.title); } else if (snapshot.hasError) { return Text('${snapshot.error}'); } // By default, show a loading spinner. return const CircularProgressIndicator(); }, ), ), ), ); } }
website/examples/cookbook/testing/unit/mocking/lib/main.dart/0
{'file_path': 'website/examples/cookbook/testing/unit/mocking/lib/main.dart', 'repo_id': 'website', 'token_count': 903}
name: scrolling description: A new Flutter project. environment: sdk: ^3.2.0 dependencies: flutter: sdk: flutter path_provider: ^2.0.15 path: ^1.8.3 flutter_test: sdk: flutter dev_dependencies: example_utils: path: ../../../../example_utils flutter: uses-material-design: true
website/examples/cookbook/testing/widget/scrolling/pubspec.yaml/0
{'file_path': 'website/examples/cookbook/testing/widget/scrolling/pubspec.yaml', 'repo_id': 'website', 'token_count': 127}
import 'dart:convert'; import 'user.dart'; // #docregion JSON const jsonString = ''' { "name": "John Smith", "email": "john@example.com" } '''; // #enddocregion JSON void example() { // #docregion manual final user = jsonDecode(jsonString) as Map<String, dynamic>; print('Howdy, ${user['name']}!'); print('We sent the verification link to ${user['email']}.'); // #enddocregion manual } void exampleJson() { // #docregion fromJson final userMap = jsonDecode(jsonString) as Map<String, dynamic>; final user = User.fromJson(userMap); print('Howdy, ${user.name}!'); print('We sent the verification link to ${user.email}.'); // #enddocregion fromJson // #docregion jsonEncode // ignore: unused_local_variable String json = jsonEncode(user); // #enddocregion jsonEncode }
website/examples/development/data-and-backend/json/lib/manual/main.dart/0
{'file_path': 'website/examples/development/data-and-backend/json/lib/manual/main.dart', 'repo_id': 'website', 'token_count': 278}
// #docregion Import import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; // #enddocregion Import class HybridCompositionWidget extends StatelessWidget { const HybridCompositionWidget({super.key}); @override // #docregion HybridCompositionWidget Widget build(BuildContext context) { // This is used in the platform side to register the view. const String viewType = '<platform-view-type>'; // Pass parameters to the platform side. const Map<String, dynamic> creationParams = <String, dynamic>{}; return PlatformViewLink( viewType: viewType, surfaceFactory: (context, controller) { return AndroidViewSurface( controller: controller as AndroidViewController, gestureRecognizers: const <Factory<OneSequenceGestureRecognizer>>{}, hitTestBehavior: PlatformViewHitTestBehavior.opaque, ); }, onCreatePlatformView: (params) { return PlatformViewsService.initSurfaceAndroidView( id: params.id, viewType: viewType, layoutDirection: TextDirection.ltr, creationParams: creationParams, creationParamsCodec: const StandardMessageCodec(), onFocus: () { params.onFocusChanged(true); }, ) ..addOnPlatformViewCreatedListener(params.onPlatformViewCreated) ..create(); }, ); } // #enddocregion HybridCompositionWidget }
website/examples/development/platform_integration/lib/platform_views/native_view_example_1.dart/0
{'file_path': 'website/examples/development/platform_integration/lib/platform_views/native_view_example_1.dart', 'repo_id': 'website', 'token_count': 588}
import 'package:flutter/material.dart'; void main() { runApp(const FadeAppTest()); } class FadeAppTest extends StatelessWidget { const FadeAppTest({super.key}); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Fade Demo', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), ), home: const MyFadeTest(title: 'Fade Demo'), ); } } class MyFadeTest extends StatefulWidget { const MyFadeTest({super.key, required this.title}); final String title; @override State<MyFadeTest> createState() => _MyFadeTest(); } class _MyFadeTest extends State<MyFadeTest> with TickerProviderStateMixin { late AnimationController controller; late CurvedAnimation curve; @override void initState() { super.initState(); controller = AnimationController( duration: const Duration(milliseconds: 2000), vsync: this, ); curve = CurvedAnimation( parent: controller, curve: Curves.easeIn, ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: FadeTransition( opacity: curve, child: const FlutterLogo( size: 100, ), ), ), floatingActionButton: FloatingActionButton( tooltip: 'Fade', onPressed: () { controller.forward(); }, child: const Icon(Icons.brush), ), ); } }
website/examples/get-started/flutter-for/android_devs/lib/animation.dart/0
{'file_path': 'website/examples/get-started/flutter-for/android_devs/lib/animation.dart', 'repo_id': 'website', 'token_count': 649}
import 'package:flutter/material.dart'; void main() => runApp(const MaterialApp(home: DemoApp())); class DemoApp extends StatelessWidget { const DemoApp({super.key}); @override Widget build(BuildContext context) => const Scaffold(body: Signature()); } class Signature extends StatefulWidget { const Signature({super.key}); @override State<Signature> createState() => SignatureState(); } class SignatureState extends State<Signature> { List<Offset?> _points = <Offset?>[]; @override Widget build(BuildContext context) { return GestureDetector( onPanUpdate: (details) { setState(() { RenderBox? referenceBox = context.findRenderObject() as RenderBox; Offset localPosition = referenceBox.globalToLocal(details.globalPosition); _points = List.from(_points)..add(localPosition); }); }, onPanEnd: (details) => _points.add(null), child: // #docregion CustomPaint CustomPaint( painter: SignaturePainter(_points), size: Size.infinite, ), // #enddocregion CustomPaint ); } } // #docregion CustomPainter class SignaturePainter extends CustomPainter { SignaturePainter(this.points); final List<Offset?> points; @override void paint(Canvas canvas, Size size) { final Paint paint = Paint() ..color = Colors.black ..strokeCap = StrokeCap.round ..strokeWidth = 5; for (int i = 0; i < points.length - 1; i++) { if (points[i] != null && points[i + 1] != null) { canvas.drawLine(points[i]!, points[i + 1]!, paint); } } } @override bool shouldRepaint(SignaturePainter oldDelegate) => oldDelegate.points != points; } // #enddocregion CustomPainter
website/examples/get-started/flutter-for/ios_devs/lib/canvas.dart/0
{'file_path': 'website/examples/get-started/flutter-for/ios_devs/lib/canvas.dart', 'repo_id': 'website', 'token_count': 669}
// ignore_for_file: avoid_print, unused_local_variable, prefer_typing_uninitialized_variables // #docregion Main /// Dart void main() {} // #enddocregion Main void printCode() { // #docregion Print /// Dart print('Hello world!'); // #enddocregion Print } void variableCode() { // #docregion Variables /// Dart /// Both variables are acceptable. String name = 'dart'; // Explicitly typed as a [String]. var otherName = 'Dart'; // Inferred [String] type. // #enddocregion Variables } void nullCode() { // #docregion Null // Dart var name; // == null; raises a linter warning int? x; // == null // #enddocregion Null } void trueExample() { // #docregion True /// Dart var myNull; var zero = 0; if (zero == 0) { print('use "== 0" to check zero'); } // #enddocregion True } // #docregion Function /// Dart /// You can explicitly define the return type. bool fn() { return true; } // #enddocregion Function
website/examples/get-started/flutter-for/react_native_devs/lib/main.dart/0
{'file_path': 'website/examples/get-started/flutter-for/react_native_devs/lib/main.dart', 'repo_id': 'website', 'token_count': 318}
import 'package:flutter/material.dart'; void main() { runApp(const MaterialApp(home: DemoApp())); } class DemoApp extends StatelessWidget { const DemoApp({super.key}); @override Widget build(BuildContext context) => const Scaffold(body: Signature()); } class Signature extends StatefulWidget { const Signature({super.key}); @override SignatureState createState() => SignatureState(); } class SignatureState extends State<Signature> { List<Offset?> _points = <Offset?>[]; void _onPanUpdate(DragUpdateDetails details) { setState(() { final RenderBox referenceBox = context.findRenderObject() as RenderBox; final Offset localPosition = referenceBox.globalToLocal( details.globalPosition, ); _points = List.from(_points)..add(localPosition); }); } @override Widget build(BuildContext context) { return GestureDetector( onPanUpdate: _onPanUpdate, onPanEnd: (details) => _points.add(null), child: CustomPaint( painter: SignaturePainter(_points), size: Size.infinite, ), ); } } class SignaturePainter extends CustomPainter { const SignaturePainter(this.points); final List<Offset?> points; @override void paint(Canvas canvas, Size size) { final Paint paint = Paint() ..color = Colors.black ..strokeCap = StrokeCap.round ..strokeWidth = 5; for (int i = 0; i < points.length - 1; i++) { if (points[i] != null && points[i + 1] != null) { canvas.drawLine(points[i]!, points[i + 1]!, paint); } } } @override bool shouldRepaint(SignaturePainter oldDelegate) => oldDelegate.points != points; }
website/examples/get-started/flutter-for/xamarin_devs/lib/draw.dart/0
{'file_path': 'website/examples/get-started/flutter-for/xamarin_devs/lib/draw.dart', 'repo_id': 'website', 'token_count': 606}
import 'package:flutter/material.dart'; // #docregion Localization import 'package:flutter_localizations/flutter_localizations.dart'; class MyWidget extends StatelessWidget { const MyWidget({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( localizationsDelegates: <LocalizationsDelegate<dynamic>>[ // Add app-specific localization delegate[s] here GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, ], supportedLocales: <Locale>[ Locale('en', 'US'), // English Locale('he', 'IL'), // Hebrew // ... other locales the app supports ], ); } } // #enddocregion Localization class TextWidget extends StatelessWidget { const TextWidget({super.key}); @override Widget build(BuildContext context) { // #docregion AccessString return const Text(Strings.welcomeMessage); // #enddocregion AccessString } } // #docregion StringsClass class Strings { static const String welcomeMessage = 'Welcome To Flutter'; } // #enddocregion StringsClass class CustomFontExample extends StatelessWidget { const CustomFontExample({super.key}); // #docregion CustomFont @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Sample App')), body: const Center( child: Text( 'This is a custom font text', style: TextStyle(fontFamily: 'MyCustomFont'), ), ), ); } // #enddocregion CustomFont }
website/examples/get-started/flutter-for/xamarin_devs/lib/strings.dart/0
{'file_path': 'website/examples/get-started/flutter-for/xamarin_devs/lib/strings.dart', 'repo_id': 'website', 'token_count': 548}
// ignore_for_file: unused_local_variable import 'package:flutter/material.dart'; import 'package:flutter_gen/gen_l10n/app_localizations.dart'; void examples(BuildContext context) { // #docregion MaterialAppExample const MaterialApp( title: 'Localizations Sample App', localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, ); // #enddocregion MaterialAppExample // #docregion LocaleResolution MaterialApp( localeResolutionCallback: ( locale, supportedLocales, ) { return locale; }, ); // #enddocregion LocaleResolution // #docregion MyLocale Locale myLocale = Localizations.localeOf(context); // #enddocregion MyLocale const MaterialApp( // #docregion SupportedLocales supportedLocales: [ Locale.fromSubtags(languageCode: 'zh'), // generic Chinese 'zh' Locale.fromSubtags( languageCode: 'zh', scriptCode: 'Hans'), // generic simplified Chinese 'zh_Hans' Locale.fromSubtags( languageCode: 'zh', scriptCode: 'Hant'), // generic traditional Chinese 'zh_Hant' Locale.fromSubtags( languageCode: 'zh', scriptCode: 'Hans', countryCode: 'CN'), // 'zh_Hans_CN' Locale.fromSubtags( languageCode: 'zh', scriptCode: 'Hant', countryCode: 'TW'), // 'zh_Hant_TW' Locale.fromSubtags( languageCode: 'zh', scriptCode: 'Hant', countryCode: 'HK'), // 'zh_Hant_HK' ], // #enddocregion SupportedLocales ); } class PageWithDatePicker extends StatefulWidget { const PageWithDatePicker({super.key}); final String title = 'Localizations Sample App'; @override State<PageWithDatePicker> createState() => _PageWithDatePickerState(); } class _PageWithDatePickerState extends State<PageWithDatePicker> { @override // #docregion CalendarDatePicker Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ // Add the following code Localizations.override( context: context, locale: const Locale('es'), // Using a Builder to get the correct BuildContext. // Alternatively, you can create a new widget and Localizations.override // will pass the updated BuildContext to the new widget. child: Builder( builder: (context) { // A toy example for an internationalized Material widget. return CalendarDatePicker( initialDate: DateTime.now(), firstDate: DateTime(1900), lastDate: DateTime(2100), onDateChanged: (value) {}, ); }, ), ), ], ), ), ); } // #enddocregion CalendarDatePicker }
website/examples/internationalization/gen_l10n_example/lib/examples.dart/0
{'file_path': 'website/examples/internationalization/gen_l10n_example/lib/examples.dart', 'repo_id': 'website', 'token_count': 1338}
import 'package:flutter_test/flutter_test.dart'; import 'package:intl_example/main.dart'; void main() { testWidgets('Test localized strings in demo app', (tester) async { // Build our app and trigger a frame. await tester.pumpWidget(const Demo()); // // Set the app's locale to English await tester.binding.setLocale('en', ''); await tester.pumpAndSettle(); // Verify that our text is English expect(find.text('Hello World'), findsWidgets); expect(find.text('Hola Mundo'), findsNothing); // Set the app's locale to Spanish await tester.binding.setLocale('es', ''); await tester.pumpAndSettle(); // Verify that our text is Spanish expect(find.text('Hola Mundo'), findsWidgets); expect(find.text('Hello World'), findsNothing); }); }
website/examples/internationalization/intl_example/test/widget_test.dart/0
{'file_path': 'website/examples/internationalization/intl_example/test/widget_test.dart', 'repo_id': 'website', 'token_count': 276}
name: deferred_components description: Samples to showcase deferred component imports/loading. publish_to: none environment: sdk: ^3.2.0 dependencies: flutter: sdk: flutter provider: ^6.0.5 dev_dependencies: example_utils: path: ../../example_utils flutter_test: sdk: flutter test: ^1.24.6 flutter: uses-material-design: true
website/examples/perf/deferred_components/pubspec.yaml/0
{'file_path': 'website/examples/perf/deferred_components/pubspec.yaml', 'repo_id': 'website', 'token_count': 136}
import 'package:flutter/material.dart'; /// This is here so we don't need to show Scaffold and AppBar in the snippet. /// We need Scaffold+AppBar so that the smoke test can get out of this page. class HelperScaffoldWrapper extends StatelessWidget { const HelperScaffoldWrapper({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: const MyHomepage(), ); } } // #docregion Ephemeral class MyHomepage extends StatefulWidget { const MyHomepage({super.key}); @override State<MyHomepage> createState() => _MyHomepageState(); } class _MyHomepageState extends State<MyHomepage> { int _index = 0; @override Widget build(BuildContext context) { return BottomNavigationBar( currentIndex: _index, onTap: (newIndex) { setState(() { _index = newIndex; }); }, // #enddocregion Ephemeral items: const [ BottomNavigationBarItem(label: 'abc', icon: Icon(Icons.title)), BottomNavigationBarItem(label: 'def', icon: Icon(Icons.map)), ], // #docregion Ephemeral ); } } // #enddocregion Ephemeral
website/examples/state_mgmt/simple/lib/src/set_state.dart/0
{'file_path': 'website/examples/state_mgmt/simple/lib/src/set_state.dart', 'repo_id': 'website', 'token_count': 442}
// ignore_for_file: directives_ordering import 'dart:io'; // #docregion log import 'dart:developer' as developer; void main() { developer.log('log me', name: 'my.app.category'); developer.log('log me 1', name: 'my.other.category'); developer.log('log me 2', name: 'my.other.category'); } // #enddocregion log void output() { // #docregion stderr stderr.writeln('print me'); // #enddocregion stderr }
website/examples/testing/code_debugging/lib/main.dart/0
{'file_path': 'website/examples/testing/code_debugging/lib/main.dart', 'repo_id': 'website', 'token_count': 148}
import 'package:flutter/material.dart'; class ProblemWidget extends StatelessWidget { const ProblemWidget({super.key}); @override // #docregion Problem Widget build(BuildContext context) { return Row( children: [ const Icon(Icons.message), Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text('Title', style: Theme.of(context).textTheme.headlineMedium), const Text( 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed ' 'do eiusmod tempor incididunt ut labore et dolore magna ' 'aliqua. Ut enim ad minim veniam, quis nostrud ' 'exercitation ullamco laboris nisi ut aliquip ex ea ' 'commodo consequat.', ), ], ), ], ); } // #enddocregion Problem } class SolutionWidget extends StatelessWidget { const SolutionWidget({super.key}); @override Widget build(BuildContext context) { // #docregion Fix return const Row( children: [ Icon(Icons.message), Expanded( child: Column( // code omitted ), ), ], ); // #enddocregion Fix } }
website/examples/testing/common_errors/lib/renderflex_overflow.dart/0
{'file_path': 'website/examples/testing/common_errors/lib/renderflex_overflow.dart', 'repo_id': 'website', 'token_count': 592}
name: errors description: An error handling example. publish_to: none environment: sdk: ^3.2.0 dependencies: flutter: sdk: flutter firebase_core: ^2.0.0 dev_dependencies: example_utils: path: ../../example_utils integration_test: sdk: flutter flutter_test: sdk: flutter flutter: uses-material-design: true
website/examples/testing/errors/pubspec.yaml/0
{'file_path': 'website/examples/testing/errors/pubspec.yaml', 'repo_id': 'website', 'token_count': 136}
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; class ShortcutsExample extends StatelessWidget { const ShortcutsExample({super.key}); // #docregion ShortcutsExample @override Widget build(BuildContext context) { return Shortcuts( shortcuts: <LogicalKeySet, Intent>{ LogicalKeySet(LogicalKeyboardKey.control, LogicalKeyboardKey.keyA): const SelectAllIntent(), }, child: Actions( dispatcher: LoggingActionDispatcher(), actions: <Type, Action<Intent>>{ SelectAllIntent: SelectAllAction(model), }, child: Builder( builder: (context) => TextButton( onPressed: Actions.handler<SelectAllIntent>( context, const SelectAllIntent(), ), child: const Text('SELECT ALL'), ), ), ), ); } // #enddocregion ShortcutsExample } // #docregion LoggingShortcutManager class LoggingShortcutManager extends ShortcutManager { @override KeyEventResult handleKeypress(BuildContext context, RawKeyEvent event) { final KeyEventResult result = super.handleKeypress(context, event); if (result == KeyEventResult.handled) { print('Handled shortcut $event in $context'); } return result; } } // #enddocregion LoggingShortcutManager class SelectAllIntent extends Intent { const SelectAllIntent({this.controller}); final TextEditingController? controller; } class Model { void selectAll() {} } Model model = Model(); // #docregion SelectAllAction class SelectAllAction extends Action<SelectAllIntent> { SelectAllAction(this.model); final Model model; @override void invoke(covariant SelectAllIntent intent) => model.selectAll(); } // #enddocregion SelectAllAction void callbackActionSample() { // #docregion CallbackAction CallbackAction(onInvoke: (intent) => model.selectAll()); // #enddocregion CallbackAction } class SelectAllExample extends StatelessWidget { const SelectAllExample({super.key, required this.child}); final Widget child; // #docregion SelectAllExample @override Widget build(BuildContext context) { return Actions( actions: <Type, Action<Intent>>{ SelectAllIntent: SelectAllAction(model), }, child: child, ); } // #enddocregion SelectAllExample } late BuildContext context; void findAndInvokeExample() { // #docregion MaybeFindExample Action<SelectAllIntent>? selectAll = Actions.maybeFind<SelectAllIntent>(context); // #enddocregion MaybeFindExample // #docregion InvokeActionExample Object? result; if (selectAll != null) { result = Actions.of(context).invokeAction(selectAll, const SelectAllIntent()); } // #enddocregion InvokeActionExample print('$result'); } void maybeInvokeExample() { // #docregion MaybeInvokeExample Object? result = Actions.maybeInvoke<SelectAllIntent>(context, const SelectAllIntent()); // #enddocregion MaybeInvokeExample print('$result'); } class HandlerExample extends StatelessWidget { const HandlerExample(this.controller, {super.key}); final TextEditingController controller; // #docregion HandlerExample @override Widget build(BuildContext context) { return Actions( actions: <Type, Action<Intent>>{ SelectAllIntent: SelectAllAction(model), }, child: Builder( builder: (context) => TextButton( onPressed: Actions.handler<SelectAllIntent>( context, SelectAllIntent(controller: controller), ), child: const Text('SELECT ALL'), ), ), ); } // #enddocregion HandlerExample } // #docregion LoggingActionDispatcher class LoggingActionDispatcher extends ActionDispatcher { @override Object? invokeAction( covariant Action<Intent> action, covariant Intent intent, [ BuildContext? context, ]) { print('Action invoked: $action($intent) from $context'); super.invokeAction(action, intent, context); return null; } } // #enddocregion LoggingActionDispatcher class LoggingActionDispatcherExample extends StatelessWidget { const LoggingActionDispatcherExample({super.key}); // #docregion LoggingActionDispatcherExample @override Widget build(BuildContext context) { return Actions( dispatcher: LoggingActionDispatcher(), actions: <Type, Action<Intent>>{ SelectAllIntent: SelectAllAction(model), }, child: Builder( builder: (context) => TextButton( onPressed: Actions.handler<SelectAllIntent>( context, const SelectAllIntent(), ), child: const Text('SELECT ALL'), ), ), ); } // #enddocregion LoggingActionDispatcherExample } class CallbackShortcutsExample extends StatefulWidget { const CallbackShortcutsExample({super.key}); @override State<CallbackShortcutsExample> createState() => _CallbackShortcutsExampleState(); } class _CallbackShortcutsExampleState extends State<CallbackShortcutsExample> { int count = 0; // #docregion CallbackShortcuts @override Widget build(BuildContext context) { return CallbackShortcuts( bindings: <ShortcutActivator, VoidCallback>{ const SingleActivator(LogicalKeyboardKey.arrowUp): () { setState(() => count = count + 1); }, const SingleActivator(LogicalKeyboardKey.arrowDown): () { setState(() => count = count - 1); }, }, child: Focus( autofocus: true, child: Column( children: <Widget>[ const Text('Press the up arrow key to add to the counter'), const Text('Press the down arrow key to subtract from the counter'), Text('count: $count'), ], ), ), ); } // #enddocregion CallbackShortcuts }
website/examples/ui/advanced/actions_and_shortcuts/lib/samples.dart/0
{'file_path': 'website/examples/ui/advanced/actions_and_shortcuts/lib/samples.dart', 'repo_id': 'website', 'token_count': 2140}
import 'package:flutter/widgets.dart'; import 'package:provider/provider.dart'; /// Provides a top level scope for targeted actions. /// /// Targeted actions are useful for making actions that are bound to children or /// siblings of the focused widget available for invocation that wouldn't /// normally be visible to a Shortcuts widget ancestor of the focused widget. /// TargetedActionScope is used in place or in addition to the Shortcuts widget /// that defines the key bindings for a subtree. /// /// To use a targeted action, define this scope with a set of shortcuts that /// should be active in this scope. Then, in a child widget of this one, define /// a [TargetedActionBinding] with the actions that you wish to execute when the /// binding is activated with the intent. If no action is defined for a scope /// for that intent, then nothing happens. class TargetedActionScope extends StatefulWidget { const TargetedActionScope({ super.key, required this.child, required this.shortcuts, }); final Widget child; final Map<LogicalKeySet, Intent> shortcuts; @override State<TargetedActionScope> createState() => _TargetedActionScopeState(); } class _TargetedActionScopeState extends State<TargetedActionScope> { late _TargetedActionRegistry registry; Map<LogicalKeySet, Intent> mappedShortcuts = <LogicalKeySet, Intent>{}; @override void initState() { super.initState(); registry = _TargetedActionRegistry(); mappedShortcuts = _buildShortcuts(); } @override void didUpdateWidget(TargetedActionScope oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.shortcuts != widget.shortcuts) { mappedShortcuts = _buildShortcuts(); } } Map<LogicalKeySet, Intent> _buildShortcuts() { Map<LogicalKeySet, Intent> mapped = <LogicalKeySet, Intent>{}; for (final LogicalKeySet activator in widget.shortcuts.keys) { mapped[activator] = _TargetedIntent(widget.shortcuts[activator]!); } return mapped; } @override Widget build(BuildContext context) { return Provider<_TargetedActionRegistry>.value( value: registry, child: Shortcuts( shortcuts: mappedShortcuts, child: Actions( actions: <Type, Action<Intent>>{ _TargetedIntent: _TargetedAction(registry), }, child: widget.child, ), ), ); } } /// A binding for use within a [TargetedActionScope]. /// /// Place an instance of this widget as a descendant of a [TargetedActionScope], /// and optionally define any actions that should handle the intents with /// bindings in the scope. Any actions defined in parents of this widget will /// also be in the scope. /// /// If more than one of these exists in the same [TargetedActionScope], then /// each of the corresponding contexts will be searched for an action to fulfill /// the intent. The first one to be found that fulfills the intent will have its /// action invoked. The order duplicate bindings are searched in is stable with /// respect to build order, but arbitrary. // This is a stateful widget because we need to be able to implement deactivate. class TargetedActionBinding extends StatefulWidget { const TargetedActionBinding({super.key, required this.child, this.actions}); final Widget child; final Map<Type, Action<Intent>>? actions; @override State<TargetedActionBinding> createState() => _TargetedActionBindingState(); } class _TargetedActionBindingState extends State<TargetedActionBinding> { final GlobalKey _subtreeKey = GlobalKey(debugLabel: 'Targeted Action Binding'); @override Widget build(BuildContext context) { Provider.of<_TargetedActionRegistry>(context).addTarget(_subtreeKey); Widget result = KeyedSubtree( key: _subtreeKey, child: widget.child, ); if (widget.actions != null) { result = Actions(actions: widget.actions!, child: result); } return result; } @override void deactivate() { Provider.of<_TargetedActionRegistry>(context, listen: false) .targetKeys .remove(_subtreeKey); super.deactivate(); } } // This is a registry that keeps track of the set of targets in the scope, and // handles invoking them. // // It is found through a provider. class _TargetedActionRegistry { _TargetedActionRegistry() : targetKeys = <GlobalKey>{}; Set<GlobalKey> targetKeys; // Adds the given target key to the set of keys to check. void addTarget(GlobalKey target) { targetKeys.add(target); } bool isEnabled(Intent intent) { // Check each of the target keys to see if there's an action registered in // that context for the intent. If so, find out if it is enabled. It is // build-order dependent which action gets invoked if there are two contexts // tha support the action. for (GlobalKey key in targetKeys) { if (key.currentContext != null) { Action? foundAction = Actions.maybeFind<Intent>(key.currentContext!, intent: intent); if (foundAction != null && foundAction.isEnabled(intent)) { return true; } } } return false; } Object? invoke(Intent intent) { // Check each of the target keys to see if there's an action registered in // that context for the intent. If so, execute it and return the result. It // is build-order dependent which action gets invoked if there are two // contexts tha support the action. for (GlobalKey key in targetKeys) { if (key.currentContext != null) { if (Actions.maybeFind<Intent>(key.currentContext!, intent: intent) != null) { return Actions.invoke(key.currentContext!, intent); } } } return null; } } // A wrapper intent class so that it can hold the "real" intent, and serve as a // mapping type for the _TargetedAction. class _TargetedIntent extends Intent { const _TargetedIntent(this.intent); final Intent intent; } // A special action class that invokes the intent tunneled into it via the // _TargetedIntent. class _TargetedAction extends Action<_TargetedIntent> { _TargetedAction(this.registry); final _TargetedActionRegistry registry; @override bool isEnabled(_TargetedIntent intent) { return registry.isEnabled(intent.intent); } @override Object? invoke(covariant _TargetedIntent intent) { registry.invoke(intent.intent); return null; } }
website/examples/ui/layout/adaptive_app_demos/lib/global/targeted_actions.dart/0
{'file_path': 'website/examples/ui/layout/adaptive_app_demos/lib/global/targeted_actions.dart', 'repo_id': 'website', 'token_count': 2032}
import 'package:flutter/material.dart'; class Counter extends StatefulWidget { // This class is the configuration for the state. // It holds the values (in this case nothing) provided // by the parent and used by the build method of the // State. Fields in a Widget subclass are always marked // "final". const Counter({super.key}); @override State<Counter> createState() => _CounterState(); } class _CounterState extends State<Counter> { int _counter = 0; void _increment() { setState(() { // This call to setState tells the Flutter framework // that something has changed in this State, which // causes it to rerun the build method below so that // the display can reflect the updated values. If you // change _counter without calling setState(), then // the build method won't be called again, and so // nothing would appear to happen. _counter++; }); } @override Widget build(BuildContext context) { // This method is rerun every time setState is called, // for instance, as done by the _increment method above. // The Flutter framework has been optimized to make // rerunning build methods fast, so that you can just // rebuild anything that needs updating rather than // having to individually changes instances of widgets. return Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ElevatedButton( onPressed: _increment, child: const Text('Increment'), ), const SizedBox(width: 16), Text('Count: $_counter'), ], ); } } void main() { runApp( const MaterialApp( home: Scaffold( body: Center( child: Counter(), ), ), ), ); }
website/examples/ui/widgets_intro/lib/main_counter.dart/0
{'file_path': 'website/examples/ui/widgets_intro/lib/main_counter.dart', 'repo_id': 'website', 'token_count': 615}
name: ci on: push: branches: - main jobs: build: runs-on: ubuntu-latest steps: - name: noop run: echo 'noop'
widgetbook/.github/workflows/ci.yaml/0
{'file_path': 'widgetbook/.github/workflows/ci.yaml', 'repo_id': 'widgetbook', 'token_count': 79}
import 'dart:async'; import 'package:bloc/bloc.dart'; import 'package:meta/meta.dart'; import 'package:widgetbook_example/models/meal.dart'; import 'package:widgetbook_example/repositories/meal_repository.dart'; part 'meal_event.dart'; part 'meal_state.dart'; class MealBloc extends Bloc<MealEvent, MealState> { final MealRepository mealRepository; MealBloc({ required this.mealRepository, }) : super( MealState(), ); @override Stream<MealState> mapEventToState( MealEvent event, ) async* { if (event is LoadMeals) { yield MealState( meals: this.mealRepository.loadMeals(), ); } } }
widgetbook/examples/widgetbook_example/lib/blocs/meal/meal_bloc.dart/0
{'file_path': 'widgetbook/examples/widgetbook_example/lib/blocs/meal/meal_bloc.dart', 'repo_id': 'widgetbook', 'token_count': 263}
class Constants { static const double controlBarHeight = 40; }
widgetbook/packages/widgetbook/lib/src/constants/constants.dart/0
{'file_path': 'widgetbook/packages/widgetbook/lib/src/constants/constants.dart', 'repo_id': 'widgetbook', 'token_count': 18}
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:widgetbook/src/knobs/knobs.dart'; import 'package:widgetbook/src/knobs/nullable_checkbox.dart'; class TextKnob extends Knob<String> { TextKnob({ required String label, String? description, required String value, }) : super( label: label, description: description, value: value, ); @override Widget build() => TextKnobWidget( label: label, description: description, value: value, key: ValueKey(this), ); } class NullableTextKnob extends Knob<String?> { NullableTextKnob({ required String label, String? description, required String? value, }) : super( label: label, description: description, value: value, ); @override Widget build() => TextKnobWidget( label: label, description: description, value: value, nullable: true, key: ValueKey(this), ); } class TextKnobWidget extends StatefulWidget { const TextKnobWidget({ Key? key, required this.label, required this.description, required this.value, this.nullable = false, }) : super(key: key); final String label; final String? description; final String? value; final bool nullable; @override State<TextKnobWidget> createState() => _TextKnobWidgetState(); } class _TextKnobWidgetState extends State<TextKnobWidget> { String value = ''; final controller = TextEditingController(); @override void initState() { super.initState(); if (widget.value != null) { controller.text = widget.value!; value = widget.value!; } } @override Widget build(BuildContext context) { return KnobWrapper( description: widget.description, title: widget.label, nullableCheckbox: widget.nullable ? NullableCheckbox<String?>( cachedValue: value, value: widget.value, label: widget.label, ) : null, child: TextField( key: Key('${widget.label}-textKnob'), controller: controller, onChanged: (v) { setState(() { value = v; }); context.read<KnobsNotifier>().update(widget.label, v); }, ), ); } }
widgetbook/packages/widgetbook/lib/src/knobs/text_knob.dart/0
{'file_path': 'widgetbook/packages/widgetbook/lib/src/knobs/text_knob.dart', 'repo_id': 'widgetbook', 'token_count': 1001}
import 'package:flutter/material.dart'; import 'package:widgetbook/src/models/model.dart'; import 'package:widgetbook/src/models/organizers/organizer.dart'; /// UseCases represent a specific configuration of a widget and can be used /// to check edge cases of a Widget. class WidgetbookUseCase extends Organizer implements Model { WidgetbookUseCase({required String name, required this.builder}) : super(name); factory WidgetbookUseCase.center({ required String name, required Widget child, }) { return WidgetbookUseCase( name: name, builder: (_) => Center(child: child), ); } factory WidgetbookUseCase.child({ required String name, required Widget child, }) { return WidgetbookUseCase( name: name, builder: (_) => child, ); } final Widget Function(BuildContext) builder; @override String get id => path; @override bool operator ==(Object other) { if (identical(this, other)) return true; return other is WidgetbookUseCase && other.builder == builder; } @override int get hashCode => builder.hashCode; @override String toString() => 'WidgetbookUseCase(name: $name, builder: $builder)'; }
widgetbook/packages/widgetbook/lib/src/models/organizers/widgetbook_use_case.dart/0
{'file_path': 'widgetbook/packages/widgetbook/lib/src/models/organizers/widgetbook_use_case.dart', 'repo_id': 'widgetbook', 'token_count': 399}
import 'package:flutter/material.dart'; import 'package:widgetbook/widgetbook.dart'; DeviceInfo mapDeviceToDeviceInfo(Device device) { final map = { Apple.iPhone12Mini: Devices.ios.iPhone12Mini, Apple.iPhone12: Devices.ios.iPhone12, Apple.iPhone12ProMax: Devices.ios.iPhone12ProMax, Apple.iPhone13Mini: Devices.ios.iPhone13Mini, Apple.iPhone13: Devices.ios.iPhone13, Apple.iPhone13ProMax: Devices.ios.iPhone13ProMax, Apple.iPhoneSE2020: Devices.ios.iPhoneSE, // not sure what to map this device to // Apple.iPadAir9Inch: Devices.ios.iPadAir4, Apple.iPad10Inch: Devices.ios.iPad, Apple.iPadPro11Inch: Devices.ios.iPadPro11Inches, }; final mappedDevice = map[device] ?? DeviceInfo.genericPhone( platform: TargetPlatform.iOS, id: 'custom', name: 'custom', screenSize: Size( device.resolution.logicalSize.width, device.resolution.logicalSize.height, ), pixelRatio: device.resolution.scaleFactor, ); return mappedDevice; } DeviceFrameBuilderFunction get defaultDeviceFrameBuilder => ( BuildContext context, Device device, WidgetbookFrame frame, Orientation orientation, Widget child, ) { if (frame == WidgetbookFrame.defaultFrame()) { return WidgetbookDeviceFrame( orientation: orientation, device: device, child: child, ); } if (frame == WidgetbookFrame.deviceFrame()) { final deviceInfo = mapDeviceToDeviceInfo(device); return DeviceFrame( orientation: orientation, device: deviceInfo, screen: child, ); } return child; }; typedef DeviceFrameBuilderFunction = Widget Function( BuildContext context, Device device, WidgetbookFrame frame, Orientation orientation, Widget child, );
widgetbook/packages/widgetbook/lib/src/rendering/builders/device_builder.dart/0
{'file_path': 'widgetbook/packages/widgetbook/lib/src/rendering/builders/device_builder.dart', 'repo_id': 'widgetbook', 'token_count': 747}
import 'package:widgetbook/src/models/models.dart'; class FilterService { const FilterService(); List<WidgetbookCategory> filter( String searchTerm, List<WidgetbookCategory> categories, ) { return _filterCategories( RegExp( searchTerm, caseSensitive: false, ), categories, ); } List<WidgetbookCategory> _filterCategories( RegExp regExp, List<WidgetbookCategory> categories, ) { final matchingOrganizers = <WidgetbookCategory>[]; for (final category in categories) { final result = _filterOrganizer(regExp, category) as WidgetbookCategory?; if (_isMatch(result)) { matchingOrganizers.add(result!); } } return matchingOrganizers; } ExpandableOrganizer? _filterOrganizer( RegExp regExp, ExpandableOrganizer organizer) { if (organizer.name.contains(regExp)) { return organizer; } final matchingFolders = <WidgetbookFolder>[]; for (final subOrganizer in organizer.folders) { final result = _filterOrganizer(regExp, subOrganizer); if (_isMatch(result)) { matchingFolders.add(result! as WidgetbookFolder); } } final matchingWidgets = <WidgetbookComponent>[]; for (final subOrganizer in organizer.widgets) { final result = _filterOrganizer(regExp, subOrganizer); if (_isMatch(result)) { matchingWidgets.add(result! as WidgetbookComponent); } } if (matchingFolders.isNotEmpty || matchingWidgets.isNotEmpty) { return _createFilteredSubtree( organizer, matchingFolders, matchingWidgets, ); } return null; } ExpandableOrganizer _createFilteredSubtree( ExpandableOrganizer organizer, List<WidgetbookFolder> folders, List<WidgetbookComponent> widgets, ) { if (organizer is WidgetbookCategory) { return WidgetbookCategory( name: organizer.name, widgets: widgets, folders: folders, ); } // otherwise it can only be a folder return WidgetbookFolder( name: organizer.name, widgets: widgets, folders: folders, isExpanded: organizer.isExpanded, ); } bool _isMatch(ExpandableOrganizer? organizer) { return organizer != null; } }
widgetbook/packages/widgetbook/lib/src/services/filter_service.dart/0
{'file_path': 'widgetbook/packages/widgetbook/lib/src/services/filter_service.dart', 'repo_id': 'widgetbook', 'token_count': 878}
import 'package:flutter/material.dart'; class Typography { static const TextStyle subtitle2 = TextStyle( fontWeight: FontWeight.bold, ); static const TextStyle subtitle1 = TextStyle( fontWeight: FontWeight.bold, ); static TextTheme textTheme = const TextTheme( subtitle1: subtitle1, subtitle2: subtitle2, ); }
widgetbook/packages/widgetbook/lib/src/utils/typography.dart/0
{'file_path': 'widgetbook/packages/widgetbook/lib/src/utils/typography.dart', 'repo_id': 'widgetbook', 'token_count': 110}
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:widgetbook/src/models/organizers/organizers.dart'; import 'package:widgetbook/src/navigation/organizer_provider.dart'; import 'package:widgetbook/src/utils/utils.dart'; import 'package:widgetbook/src/widgets/tiles/spaced_tile.dart'; import 'package:widgetbook/src/widgets/tiles/story_tile.dart'; class WidgetTile extends StatefulWidget { const WidgetTile({ Key? key, required this.widgetElement, required this.level, }) : super(key: key); final WidgetbookComponent widgetElement; final int level; @override _WidgetTileState createState() => _WidgetTileState(); } class _WidgetTileState extends State<WidgetTile> { bool expanded = false; bool hover = false; List<Widget> _buildStories(int level) { final stories = widget.widgetElement.useCases; return stories .map( (WidgetbookUseCase story) => StoryTile( useCase: story, level: level, ), ) .toList(); } @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SpacedTile( level: widget.level, organizer: widget.widgetElement, iconData: Icons.style, iconColor: context.colorScheme.secondary, onClicked: () { context .read<OrganizerProvider>() .toggleExpander(widget.widgetElement); }, ), if (widget.widgetElement.isExpanded) ..._buildStories(widget.level + 1), ], ); } }
widgetbook/packages/widgetbook/lib/src/widgets/tiles/widget_tile.dart/0
{'file_path': 'widgetbook/packages/widgetbook/lib/src/widgets/tiles/widget_tile.dart', 'repo_id': 'widgetbook', 'token_count': 675}
import 'package:flutter/material.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:widgetbook/src/workbench/comparison_setting.dart'; import 'package:widgetbook/widgetbook.dart'; part 'workbench_state.freezed.dart'; @freezed class WorkbenchState<CustomTheme> with _$WorkbenchState<CustomTheme> { factory WorkbenchState({ @Default(ComparisonSetting.none) ComparisonSetting comparisonSetting, WidgetbookTheme<CustomTheme>? theme, Locale? locale, Device? device, required double? textScaleFactor, required WidgetbookFrame frame, @Default(Orientation.portrait) Orientation orientation, required List<WidgetbookTheme<CustomTheme>> themes, required List<Locale> locales, required List<Device> devices, required List<WidgetbookFrame> frames, required List<double> textScaleFactors, }) = _WorkbenchState; WorkbenchState._(); bool get hasSelectedTheme => theme != null; bool get hasSelectedLocale => locale != null; bool get hasSelectedDevice => device != null; bool get hasSelectedTextScaleFactor => textScaleFactor != null; }
widgetbook/packages/widgetbook/lib/src/workbench/workbench_state.dart/0
{'file_path': 'widgetbook/packages/widgetbook/lib/src/workbench/workbench_state.dart', 'repo_id': 'widgetbook', 'token_count': 348}
import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:widgetbook/src/knobs/bool_knob.dart'; import 'package:widgetbook/src/knobs/knobs.dart'; import '../../helper/widget_test_helper.dart'; import 'knobs_test.dart'; void main() { testWidgets( 'Equality operator works correctly', (WidgetTester tester) async { final first = NullableBoolKnob(label: 'first', value: null); final second = NullableBoolKnob(label: 'second', value: null); expect(first, equals(NullableBoolKnob(label: 'first', value: null))); expect(first, isNot(equals(second))); }, ); testWidgets( 'Nullable Bool knob functions', (WidgetTester tester) async { await tester.pumpWidgetWithMaterialApp( renderWithKnobs(build: (context) { final value = context.knobs.nullableBoolean( label: 'label', initialValue: null, ); String text; switch (value) { case null: text = 'idk'; break; case true: text = 'hi'; break; case false: text = 'bye'; break; default: text = 'wont happen'; } return [Text(text)]; }), ); expect(find.text('idk'), findsOneWidget); await tester.tap(find.byKey(const Key('label-nullableCheckbox'))); await tester.pumpAndSettle(); expect(find.text('bye'), findsOneWidget); await tester.tap(find.byKey(const Key('label-switchTileKnob'))); await tester.pumpAndSettle(); expect(find.text('hi'), findsOneWidget); await tester.tap(find.byKey(const Key('label-nullableCheckbox'))); await tester.pumpAndSettle(); expect(find.text('idk'), findsOneWidget); expect(find.text('idk'), findsOneWidget); await tester.pumpAndSettle(); }, ); testWidgets( 'Nullable Bool knob remembers previous value before null', (WidgetTester tester) async { await tester.pumpWidgetWithMaterialApp( renderWithKnobs(build: (context) { final value = context.knobs.nullableBoolean( label: 'label', initialValue: null, ); String text; switch (value) { case null: text = 'idk'; break; case true: text = 'hi'; break; case false: text = 'bye'; break; default: text = 'wont happen'; } return [Text(text)]; }), ); expect(find.text('idk'), findsOneWidget); await tester.tap(find.byKey(const Key('label-nullableCheckbox'))); await tester.pumpAndSettle(); expect(find.text('bye'), findsOneWidget); await tester.tap(find.byKey(const Key('label-switchTileKnob'))); await tester.pumpAndSettle(); expect(find.text('hi'), findsOneWidget); await tester.tap(find.byKey(const Key('label-nullableCheckbox'))); await tester.pumpAndSettle(); expect(find.text('idk'), findsOneWidget); await tester.tap(find.byKey(const Key('label-nullableCheckbox'))); await tester.pumpAndSettle(); expect(find.text('hi'), findsOneWidget); }, ); }
widgetbook/packages/widgetbook/test/src/knobs/nullable_bool_knob_test.dart/0
{'file_path': 'widgetbook/packages/widgetbook/test/src/knobs/nullable_bool_knob_test.dart', 'repo_id': 'widgetbook', 'token_count': 1572}
import 'package:flutter_test/flutter_test.dart'; import 'package:widgetbook/src/translate/translate_provider.dart'; import 'package:widgetbook/src/translate/translate_state.dart'; void main() { const offset = Offset(1, 1); group( '$TranslateProvider', () { test( 'defaults to $Offset.zero', () { final provider = TranslateProvider(); expect( provider.state, equals( TranslateState( offset: Offset.zero, ), ), ); }, ); test( 'updateOffset sets value', () { final provider = TranslateProvider()..updateOffset(offset); expect( provider.state, equals( TranslateState( offset: offset, ), ), ); }, ); test( 'updateRelativeOffset adds $offset', () { final provider = TranslateProvider( state: TranslateState( offset: offset, ), )..updateRelativeOffset(offset); expect( provider.state, equals( TranslateState( offset: const Offset(2, 2), ), ), ); }, ); test( 'resetOffset resets $Offset to $Offset.zero', () { final provider = TranslateProvider( state: TranslateState( offset: offset, ), )..resetOffset(); expect( provider.state, equals( TranslateState( offset: Offset.zero, ), ), ); }, ); }, ); }
widgetbook/packages/widgetbook/test/src/translate/translate_provider_test.dart/0
{'file_path': 'widgetbook/packages/widgetbook/test/src/translate/translate_provider_test.dart', 'repo_id': 'widgetbook', 'token_count': 1008}
/// Annotates a list of `Locale`s to support the app's localization in /// Widgetbook class WidgetbookLocales { /// Creates a new instance of [WidgetbookLocales]. const WidgetbookLocales(); }
widgetbook/packages/widgetbook_annotation/lib/src/widgetbook_locales.dart/0
{'file_path': 'widgetbook/packages/widgetbook_annotation/lib/src/widgetbook_locales.dart', 'repo_id': 'widgetbook', 'token_count': 59}
part of 'device.dart'; // Generated manually with https://fluttershapemaker.com/ final _screenPath = Path() ..moveTo(7.99023, 65.9178) ..cubicTo(7.99023, 45.2018, 7.99023, 34.8439, 14.4259, 28.4083) ..cubicTo(20.8615, 21.9727, 31.2194, 21.9727, 51.9354, 21.9727) ..lineTo(743.073, 21.9727) ..cubicTo(763.789, 21.9727, 774.146, 21.9727, 780.582, 28.4083) ..cubicTo(787.018, 34.8439, 787.018, 45.2019, 787.018, 65.9178) ..lineTo(787.018, 1635.96) ..cubicTo(787.018, 1656.67, 787.018, 1667.03, 780.582, 1673.47) ..cubicTo(774.147, 1679.9, 763.789, 1679.9, 743.074, 1679.9) ..lineTo(51.9342, 1679.9) ..cubicTo(31.219, 1679.9, 20.8613, 1679.9, 14.4259, 1673.47) ..cubicTo(7.99023, 1667.03, 7.99023, 1656.67, 7.99023, 1635.96) ..lineTo(7.99023, 65.9178) ..close() ..moveTo(416.955, 53.9776) ..cubicTo(416.955, 63.9063, 408.906, 71.9551, 398.978, 71.9551) ..cubicTo(389.049, 71.9551, 381, 63.9063, 381, 53.9776) ..cubicTo(381, 44.0488, 389.049, 36, 398.978, 36) ..cubicTo(408.906, 36, 416.955, 44.0488, 416.955, 53.9776) ..close() ..fillType = PathFillType.evenOdd;
widgetbook/packages/widgetbook_device_frame/lib/src/devices/android/samsung_galaxy_note20_ultra/screen.g.dart/0
{'file_path': 'widgetbook/packages/widgetbook_device_frame/lib/src/devices/android/samsung_galaxy_note20_ultra/screen.g.dart', 'repo_id': 'widgetbook', 'token_count': 585}
part of 'device.dart'; // Generated manually with https://fluttershapemaker.com/ final _screenPath = Path() ..moveTo(203.851, 63.8789) ..cubicTo(203.851, 88.9158, 224.074, 109.212, 249.151, 109.212) ..lineTo(621.848, 109.212) ..cubicTo(646.925, 109.212, 667.148, 88.9158, 667.148, 63.8789) ..lineTo(667.148, 51.5152) ..cubicTo(667.148, 44.687, 672.664, 39.1516, 679.503, 39.1516) ..lineTo(683.436, 39.1516) ..cubicTo(725.805, 39.1516, 746.989, 39.1516, 763.84, 45.6754) ..cubicTo(789.255, 55.5151, 809.348, 75.622, 819.18, 101.056) ..cubicTo(825.699, 117.919, 825.699, 139.119, 825.699, 181.519) ..lineTo(825.699, 1586.48) ..cubicTo(825.699, 1628.88, 825.699, 1650.08, 819.18, 1666.94) ..cubicTo(809.348, 1692.38, 789.255, 1712.49, 763.84, 1722.32) ..cubicTo(747.437, 1728.68, 726.927, 1728.84, 686.766, 1728.85) ..cubicTo(685.671, 1728.85, 684.561, 1728.85, 683.436, 1728.85) ..lineTo(187.563, 1728.85) ..cubicTo(186.438, 1728.85, 185.328, 1728.85, 184.233, 1728.85) ..cubicTo(144.072, 1728.84, 123.562, 1728.68, 107.159, 1722.32) ..cubicTo(81.7436, 1712.49, 61.6514, 1692.38, 51.8189, 1666.94) ..cubicTo(45.2998, 1650.08, 45.2998, 1628.88, 45.2998, 1586.48) ..lineTo(45.2998, 181.519) ..cubicTo(45.2998, 139.119, 45.2998, 117.919, 51.8189, 101.056) ..cubicTo(61.6514, 75.622, 81.7436, 55.5151, 107.159, 45.6754) ..cubicTo(124.01, 39.1516, 145.194, 39.1516, 187.563, 39.1516) ..lineTo(191.496, 39.1516) ..cubicTo(198.335, 39.1516, 203.851, 44.687, 203.851, 51.5152) ..lineTo(203.851, 63.8789) ..close() ..fillType = PathFillType.evenOdd;
widgetbook/packages/widgetbook_device_frame/lib/src/devices/ios/iphone_12_mini/screen.g.dart/0
{'file_path': 'widgetbook/packages/widgetbook_device_frame/lib/src/devices/ios/iphone_12_mini/screen.g.dart', 'repo_id': 'widgetbook', 'token_count': 849}
name: widgetbook_device_frame description: Mockups for common devices. version: 1.0.1 homepage: https://github.com/aloisdeniel/flutter_device_preview/device_frame environment: sdk: ">=2.12.0 <3.0.0" dependencies: freezed_annotation: ^2.0.3 flutter: sdk: flutter dev_dependencies: flutter_test: sdk: flutter build_runner: ^2.1.4 json_serializable: ^6.0.1 freezed: ^2.0.3 flutter_lints: ^1.0.4 xml: ^5.3.1 recase: ^4.0.0
widgetbook/packages/widgetbook_device_frame/pubspec.yaml/0
{'file_path': 'widgetbook/packages/widgetbook_device_frame/pubspec.yaml', 'repo_id': 'widgetbook', 'token_count': 203}
import 'package:meta/meta.dart'; import 'package:widgetbook_generator/code_generators/instances/base_instance.dart'; import 'package:widgetbook_generator/code_generators/parameters/parameter_list.dart'; @immutable /// Calls a function. /// /// Example: /// for a lambda function defined as `() => getTheme()` /// would call it as `getTheme()` class FunctionCallInstance extends BaseInstance { /// Create a new instace of [FunctionCallInstance] const FunctionCallInstance({ required this.name, this.parameters = const ParameterList(), }); /// The name of the function final String name; final ParameterList parameters; @override String toCode() { return '$name${parameters.toCode()}'; } }
widgetbook/packages/widgetbook_generator/lib/code_generators/instances/function_call_instance.dart/0
{'file_path': 'widgetbook/packages/widgetbook_generator/lib/code_generators/instances/function_call_instance.dart', 'repo_id': 'widgetbook', 'token_count': 221}
import 'package:widgetbook_generator/code_generators/instances/base_instance.dart'; import 'package:widgetbook_generator/code_generators/parameters/parameter.dart'; class ParameterList extends BaseInstance { /// Creates a new instance of [ParameterList]. const ParameterList({ this.parameters = const <Parameter>[], this.trailingComma = true, }); /// Specifies the instances injected into the list. final List<Parameter> parameters; /// Specifies if a trailing comma should be inserted into the code. /// This leads to better code formatting. final bool trailingComma; @override String toCode() { final codeOfValues = parameters .map( (instance) => instance.toCode(), ) .toList(); final stringBuffer = StringBuffer() ..write('(') ..write( codeOfValues.join(', '), ); if (trailingComma && parameters.isNotEmpty) { stringBuffer.write(','); } stringBuffer.write(')'); return stringBuffer.toString(); } }
widgetbook/packages/widgetbook_generator/lib/code_generators/parameters/parameter_list.dart/0
{'file_path': 'widgetbook/packages/widgetbook_generator/lib/code_generators/parameters/parameter_list.dart', 'repo_id': 'widgetbook', 'token_count': 357}
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'widgetbook_locales_data.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** _$_WidgetbookLocalesData _$$_WidgetbookLocalesDataFromJson( Map<String, dynamic> json) => _$_WidgetbookLocalesData( name: json['name'] as String, importStatement: json['importStatement'] as String, dependencies: (json['dependencies'] as List<dynamic>) .map((e) => e as String) .toList(), ); Map<String, dynamic> _$$_WidgetbookLocalesDataToJson( _$_WidgetbookLocalesData instance) => <String, dynamic>{ 'name': instance.name, 'importStatement': instance.importStatement, 'dependencies': instance.dependencies, };
widgetbook/packages/widgetbook_generator/lib/models/widgetbook_locales_data.g.dart/0
{'file_path': 'widgetbook/packages/widgetbook_generator/lib/models/widgetbook_locales_data.g.dart', 'repo_id': 'widgetbook', 'token_count': 292}
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'widgetbook_theme_data.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** _$_WidgetbookThemeData _$$_WidgetbookThemeDataFromJson( Map<String, dynamic> json) => _$_WidgetbookThemeData( name: json['name'] as String, importStatement: json['importStatement'] as String, dependencies: (json['dependencies'] as List<dynamic>) .map((e) => e as String) .toList(), isDefault: json['isDefault'] as bool, themeName: json['themeName'] as String, ); Map<String, dynamic> _$$_WidgetbookThemeDataToJson( _$_WidgetbookThemeData instance) => <String, dynamic>{ 'name': instance.name, 'importStatement': instance.importStatement, 'dependencies': instance.dependencies, 'isDefault': instance.isDefault, 'themeName': instance.themeName, };
widgetbook/packages/widgetbook_generator/lib/models/widgetbook_theme_data.g.dart/0
{'file_path': 'widgetbook/packages/widgetbook_generator/lib/models/widgetbook_theme_data.g.dart', 'repo_id': 'widgetbook', 'token_count': 350}
import 'package:analyzer/dart/element/element.dart'; import 'package:build/build.dart'; import 'package:source_gen/source_gen.dart'; import 'package:widgetbook_annotation/widgetbook_annotation.dart'; import 'package:widgetbook_generator/extensions/element_extensions.dart'; import 'package:widgetbook_generator/json_formatter.dart'; import 'package:widgetbook_generator/models/widgetbook_localization_builder_data.dart'; class LocalizationDelegatesResolver extends GeneratorForAnnotation<WidgetbookLocalizationDelegates> { @override String generateForAnnotatedElement( Element element, ConstantReader annotation, BuildStep buildStep, ) { if (element.isPrivate) { throw InvalidGenerationSourceError( 'Widgetbook annotations cannot be applied to private elements', element: element, ); } final data = WidgetbookLocalizationBuilderData( name: element.name!, importStatement: element.importStatement, dependencies: element.dependencies, ); return [data].toJson(); } }
widgetbook/packages/widgetbook_generator/lib/resolvers/localization_delegates_resolver.dart/0
{'file_path': 'widgetbook/packages/widgetbook_generator/lib/resolvers/localization_delegates_resolver.dart', 'repo_id': 'widgetbook', 'token_count': 347}
import 'package:test/test.dart'; import 'package:widgetbook_annotation/widgetbook_annotation.dart'; import 'package:widgetbook_generator/code_generators/instances/device_type_instance.dart'; import 'package:widgetbook_generator/code_generators/instances/primary_instance.dart'; void main() { group( '$DeviceTypeInstance', () { const value = DeviceType.mobile; const instance = DeviceTypeInstance(deviceType: value); test('is of type $PrimaryInstance', () { expect(instance, isA<PrimaryInstance<DeviceType>>()); }); test( ".toCode returns 'DeviceType.mobile'", () { expect( instance.toCode(), equals('DeviceType.mobile'), ); }, ); }, ); }
widgetbook/packages/widgetbook_generator/test/src/code_generators/instances/device_type_instance_test.dart/0
{'file_path': 'widgetbook/packages/widgetbook_generator/test/src/code_generators/instances/device_type_instance_test.dart', 'repo_id': 'widgetbook', 'token_count': 312}
import 'package:test/test.dart'; import 'package:widgetbook_generator/code_generators/instances/list_instance.dart'; import 'package:widgetbook_generator/code_generators/instances/widgetbook_use_case_instance.dart'; import 'package:widgetbook_generator/code_generators/instances/widgetbook_widget_instance.dart'; import 'package:widgetbook_generator/code_generators/properties/property.dart'; import 'package:widgetbook_generator/models/widgetbook_story_data.dart'; import '../instance_helper.dart'; void main() { group( '$WidgetbookComponentInstance', () { const widgetName = 'CustomWidget'; final instance = WidgetbookComponentInstance( name: widgetName, stories: [ WidgetbookStoryData( name: 'story1', importStatement: '', typeDefinition: '', dependencies: [], storyName: 'Story1', widgetName: widgetName, ), WidgetbookStoryData( name: 'story2', importStatement: '', typeDefinition: '', dependencies: [], storyName: 'Story2', widgetName: widgetName, ), ], ); testName('WidgetbookComponent', instance: instance); test( '.properties returns a StringProperty and Property containing a list', () { expect( instance.properties, equals( [ Property.string( key: 'name', value: widgetName, ), Property( key: 'useCases', instance: ListInstance(instances: [ WidgetbookUseCaseInstance( useCaseName: 'Story1', functionName: 'story1'), WidgetbookUseCaseInstance( useCaseName: 'Story2', functionName: 'story2'), ]), ), ], ), ); }, ); }, ); }
widgetbook/packages/widgetbook_generator/test/src/code_generators/instances/widgetbook_widget_instance_test.dart/0
{'file_path': 'widgetbook/packages/widgetbook_generator/test/src/code_generators/instances/widgetbook_widget_instance_test.dart', 'repo_id': 'widgetbook', 'token_count': 1016}
import 'package:flutter_hello_world_bazel/main.dart' as hello_world; import 'package:flutter_test/flutter_test.dart'; // This comment is extracted by the test and compared to a text representation // built from the tree provider in the test. It must be maintained to match // the results from the tests below. // == EXPECTED RESULTS == // test/widget_test.dart Passed // Hello world test Passed // == /EXPECTED RESULTS == void main() { testWidgets('Hello world test', (WidgetTester tester) async { hello_world.main(); // BREAKPOINT1 await tester.pump(); expect(find.text('Hello, world!'), findsOneWidget); }); }
Dart-Code/src/test/test_projects/bazel_workspace/flutter_hello_world_bazel/test/widget_test.dart/0
{'file_path': 'Dart-Code/src/test/test_projects/bazel_workspace/flutter_hello_world_bazel/test/widget_test.dart', 'repo_id': 'Dart-Code', 'token_count': 202}
name: nested1 publish_to: none environment: sdk: '>=2.12.0 <3.0.0' # test # test # test # test # test # test # test # test # test # test # test # test # test # test # test # test # test # test # test # test
Dart-Code/src/test/test_projects/dart_nested/nested1/pubspec.yaml/0
{'file_path': 'Dart-Code/src/test/test_projects/dart_nested/nested1/pubspec.yaml', 'repo_id': 'Dart-Code', 'token_count': 96}
import 'package:flutter/material.dart'; import 'package:my_package/my_thing.dart'; main() { throwAnError(); runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData(primarySwatch: Colors.blue), home: MyHomePage(), ); } } class MyHomePage extends StatelessWidget { MyHomePage({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Text( 'Hello, world!', textDirection: TextDirection.ltr, ); } }
Dart-Code/src/test/test_projects/flutter_hello_world/lib/throw_in_local_package.dart/0
{'file_path': 'Dart-Code/src/test/test_projects/flutter_hello_world/lib/throw_in_local_package.dart', 'repo_id': 'Dart-Code', 'token_count': 228}