code
stringlengths
8
3.25M
repository
stringlengths
15
175
metadata
stringlengths
66
249
include: package:very_good_analysis/analysis_options.2.4.0.yaml analyzer: exclude: - "**/version.dart"
very_good_cli/analysis_options.yaml/0
{'file_path': 'very_good_cli/analysis_options.yaml', 'repo_id': 'very_good_cli', 'token_count': 44}
import 'package:mason/mason.dart'; import 'package:universal_io/io.dart'; import 'package:very_good_cli/src/cli/cli.dart'; /// Runs `flutter pub get` in the [outputDir]. Future<void> installDartPackages( Logger logger, Directory outputDir, ) async { final isFlutterInstalled = await Flutter.installed(logger: logger); if (isFlutterInstalled) { final installDependenciesProgress = logger.progress( 'Running "flutter pub get" in ${outputDir.path}', ); await Flutter.pubGet(cwd: outputDir.path, logger: logger); installDependenciesProgress.complete(); } } /// Runs `flutter packages get` in the [outputDir]. Future<void> installFlutterPackages( Logger logger, Directory outputDir, { bool recursive = false, }) async { final isFlutterInstalled = await Flutter.installed(logger: logger); if (isFlutterInstalled) { await Flutter.packagesGet( cwd: outputDir.path, recursive: recursive, logger: logger, ); } } /// Runs `dart fix --apply` in the [outputDir]. Future<void> applyDartFixes( Logger logger, Directory outputDir, { bool recursive = false, }) async { final isDartInstalled = await Dart.installed(logger: logger); if (isDartInstalled) { final applyFixesProgress = logger.progress( 'Running "dart fix --apply" in ${outputDir.path}', ); await Dart.applyFixes( cwd: outputDir.path, recursive: recursive, logger: logger, ); applyFixesProgress.complete(); } }
very_good_cli/lib/src/commands/create/templates/post_generate_actions.dart/0
{'file_path': 'very_good_cli/lib/src/commands/create/templates/post_generate_actions.dart', 'repo_id': 'very_good_cli', 'token_count': 531}
name: very_good_cli description: A Very Good Command-Line Interface for Dart created by Very Good Ventures. version: 0.9.0 repository: https://github.com/VeryGoodOpenSource/very_good_cli environment: sdk: ">=2.13.0 <3.0.0" dependencies: args: ^2.1.0 cli_completion: 0.1.0 glob: ^2.0.2 lcov_parser: ^0.1.2 mason: ">=0.1.0-dev.39 <0.1.0-dev.40" mason_logger: ^0.2.2 meta: ^1.3.0 path: ^1.8.0 pub_updater: ^0.2.1 pubspec_parse: ^1.2.0 stack_trace: ^1.10.0 universal_io: ^2.0.4 usage: ^4.0.2 very_good_analysis: ^3.0.0 very_good_test_runner: ^0.1.2 dev_dependencies: build_runner: ^2.0.0 build_verify: ^3.0.0 build_version: ^2.0.0 mocktail: ^0.3.0 test: ^1.17.0 executables: very_good:
very_good_cli/pubspec.yaml/0
{'file_path': 'very_good_cli/pubspec.yaml', 'repo_id': 'very_good_cli', 'token_count': 361}
@Tags(['e2e']) import 'package:mason/mason.dart'; import 'package:mocktail/mocktail.dart'; import 'package:path/path.dart' as path; import 'package:test/test.dart'; import 'package:universal_io/io.dart'; import 'package:usage/usage.dart'; import 'package:very_good_cli/src/command_runner.dart'; class _MockAnalytics extends Mock implements Analytics {} class _MockLogger extends Mock implements Logger {} class _MockProgress extends Mock implements Progress {} void main() { group( 'E2E', () { late Analytics analytics; late Logger logger; late Progress progress; late VeryGoodCommandRunner commandRunner; void _removeTemporaryFiles() { try { Directory('.tmp').deleteSync(recursive: true); } catch (_) {} } setUpAll(_removeTemporaryFiles); tearDownAll(_removeTemporaryFiles); setUp(() { analytics = _MockAnalytics(); logger = _MockLogger(); when(() => analytics.firstRun).thenReturn(false); when(() => analytics.enabled).thenReturn(false); when( () => analytics.sendEvent(any(), any(), label: any(named: 'label')), ).thenAnswer((_) async {}); when( () => analytics.waitForLastPing(timeout: any(named: 'timeout')), ).thenAnswer((_) async {}); logger = _MockLogger(); progress = _MockProgress(); when(() => logger.progress(any())).thenReturn(progress); commandRunner = VeryGoodCommandRunner( analytics: analytics, logger: logger, ); }); test('create -t dart_pkg', () async { final directory = Directory(path.join('.tmp', 'very_good_dart')); final result = await commandRunner.run( ['create', 'very_good_dart', '-t', 'dart_pkg', '-o', '.tmp'], ); expect(result, equals(ExitCode.success.code)); final formatResult = await Process.run( 'flutter', ['format', '--set-exit-if-changed', '.'], workingDirectory: directory.path, runInShell: true, ); expect(formatResult.exitCode, equals(ExitCode.success.code)); expect(formatResult.stderr, isEmpty); final analyzeResult = await Process.run( 'flutter', ['analyze', '.'], workingDirectory: directory.path, runInShell: true, ); expect(analyzeResult.exitCode, equals(ExitCode.success.code)); expect(analyzeResult.stderr, isEmpty); expect(analyzeResult.stdout, contains('No issues found!')); final testResult = await Process.run( 'flutter', ['test', '--no-pub', '--coverage'], workingDirectory: directory.path, runInShell: true, ); expect(testResult.exitCode, equals(ExitCode.success.code)); expect(testResult.stderr, isEmpty); expect(testResult.stdout, contains('All tests passed!')); final testCoverageResult = await Process.run( 'genhtml', ['coverage/lcov.info', '-o', 'coverage'], workingDirectory: directory.path, runInShell: true, ); expect(testCoverageResult.exitCode, equals(ExitCode.success.code)); expect(testCoverageResult.stderr, isEmpty); expect(testCoverageResult.stdout, contains('lines......: 100.0%')); }); test('create -t flutter_pkg', () async { final directory = Directory(path.join('.tmp', 'very_good_flutter')); final result = await commandRunner.run( ['create', 'very_good_flutter', '-t', 'flutter_pkg', '-o', '.tmp'], ); expect(result, equals(ExitCode.success.code)); final formatResult = await Process.run( 'flutter', ['format', '--set-exit-if-changed', '.'], workingDirectory: directory.path, runInShell: true, ); expect(formatResult.exitCode, equals(ExitCode.success.code)); expect(formatResult.stderr, isEmpty); final analyzeResult = await Process.run( 'flutter', ['analyze', '.'], workingDirectory: directory.path, runInShell: true, ); expect(analyzeResult.exitCode, equals(ExitCode.success.code)); expect(analyzeResult.stderr, isEmpty); expect(analyzeResult.stdout, contains('No issues found!')); final testResult = await Process.run( 'flutter', ['test', '--no-pub', '--coverage'], workingDirectory: directory.path, runInShell: true, ); expect(testResult.exitCode, equals(ExitCode.success.code)); expect(testResult.stderr, isEmpty); expect(testResult.stdout, contains('All tests passed!')); final testCoverageResult = await Process.run( 'genhtml', ['coverage/lcov.info', '-o', 'coverage'], workingDirectory: directory.path, runInShell: true, ); expect(testCoverageResult.exitCode, equals(ExitCode.success.code)); expect(testCoverageResult.stderr, isEmpty); expect(testCoverageResult.stdout, contains('lines......: 100.0%')); }); test('create -t dart_cli', () async { final directory = Directory(path.join('.tmp', 'very_good_dart_cli')); final result = await commandRunner.run( ['create', 'very_good_dart_cli', '-t', 'dart_cli', '-o', '.tmp'], ); expect(result, equals(ExitCode.success.code)); final formatResult = await Process.run( 'flutter', ['format', '--set-exit-if-changed', '.'], workingDirectory: directory.path, runInShell: true, ); expect(formatResult.exitCode, equals(ExitCode.success.code)); expect(formatResult.stderr, isEmpty); final analyzeResult = await Process.run( 'flutter', ['analyze', '.'], workingDirectory: directory.path, runInShell: true, ); expect(analyzeResult.exitCode, equals(ExitCode.success.code)); expect(analyzeResult.stderr, isEmpty); expect(analyzeResult.stdout, contains('No issues found!')); final testResult = await Process.run( 'flutter', ['test', '--no-pub', '--coverage'], workingDirectory: directory.path, runInShell: true, ); expect(testResult.exitCode, equals(ExitCode.success.code)); expect(testResult.stderr, isEmpty); expect(testResult.stdout, contains('All tests passed!')); final testCoverageResult = await Process.run( 'genhtml', ['coverage/lcov.info', '-o', 'coverage'], workingDirectory: directory.path, runInShell: true, ); expect(testCoverageResult.exitCode, equals(ExitCode.success.code)); expect(testCoverageResult.stderr, isEmpty); expect(testCoverageResult.stdout, contains('lines......: 100.0%')); }); test('create -t docs_site', () async { final directory = Directory(path.join('.tmp', 'very_good_docs_site')); final result = await commandRunner.run( ['create', 'very_good_docs_site', '-t', 'docs_site', '-o', '.tmp'], ); expect(result, equals(ExitCode.success.code)); final installResult = await Process.run( 'npm', ['install'], workingDirectory: directory.path, runInShell: true, ); expect(installResult.exitCode, equals(ExitCode.success.code)); final formatResult = await Process.run( 'npm', ['run', 'format'], workingDirectory: directory.path, runInShell: true, ); expect(formatResult.exitCode, equals(ExitCode.success.code)); expect(formatResult.stderr, isEmpty); final lintResult = await Process.run( 'npm', ['run', 'lint'], workingDirectory: directory.path, runInShell: true, ); expect(lintResult.exitCode, equals(ExitCode.success.code)); expect(lintResult.stderr, isEmpty); final buildResult = await Process.run( 'npm', ['run', 'build'], workingDirectory: directory.path, runInShell: true, ); expect(buildResult.exitCode, equals(ExitCode.success.code)); expect(buildResult.stderr, isEmpty); }); test('create -t flame_game', () async { final directory = Directory(path.join('.tmp', 'very_good_flame_game')); final result = await commandRunner.run( ['create', 'very_good_flame_game', '-t', 'flame_game', '-o', '.tmp'], ); expect(result, equals(ExitCode.success.code)); final formatResult = await Process.run( 'flutter', ['format', '--set-exit-if-changed', '.'], workingDirectory: directory.path, runInShell: true, ); expect(formatResult.exitCode, equals(ExitCode.success.code)); expect(formatResult.stderr, isEmpty); final analyzeResult = await Process.run( 'flutter', ['analyze', '.'], workingDirectory: directory.path, runInShell: true, ); expect(analyzeResult.exitCode, equals(ExitCode.success.code)); expect(analyzeResult.stderr, isEmpty); expect(analyzeResult.stdout, contains('No issues found!')); final testResult = await Process.run( 'flutter', ['test', '--no-pub', '--coverage'], workingDirectory: directory.path, runInShell: true, ); expect(testResult.exitCode, equals(ExitCode.success.code)); expect(testResult.stderr, isEmpty); expect(testResult.stdout, contains('All tests passed!')); final testCoverageResult = await Process.run( 'genhtml', ['coverage/lcov.info', '-o', 'coverage'], workingDirectory: directory.path, runInShell: true, ); expect(testCoverageResult.exitCode, equals(ExitCode.success.code)); expect(testCoverageResult.stderr, isEmpty); expect(testCoverageResult.stdout, contains('lines......: 97.8%')); }); test('create -t core', () async { final directory = Directory(path.join('.tmp', 'very_good_core')); final result = await commandRunner.run( ['create', 'very_good_core', '-t', 'core', '-o', '.tmp'], ); expect(result, equals(ExitCode.success.code)); final formatResult = await Process.run( 'flutter', ['format', '--set-exit-if-changed', '.'], workingDirectory: directory.path, runInShell: true, ); expect(formatResult.exitCode, equals(ExitCode.success.code)); expect(formatResult.stderr, isEmpty); final analyzeResult = await Process.run( 'flutter', ['analyze', '.'], workingDirectory: directory.path, runInShell: true, ); expect(analyzeResult.exitCode, equals(ExitCode.success.code)); expect(analyzeResult.stderr, isEmpty); expect(analyzeResult.stdout, contains('No issues found!')); final testResult = await Process.run( 'flutter', ['test', '--no-pub', '--coverage'], workingDirectory: directory.path, runInShell: true, ); expect(testResult.exitCode, equals(ExitCode.success.code)); expect(testResult.stderr, isEmpty); expect(testResult.stdout, contains('All tests passed!')); final testCoverageResult = await Process.run( 'genhtml', ['coverage/lcov.info', '-o', 'coverage'], workingDirectory: directory.path, runInShell: true, ); expect(testCoverageResult.exitCode, equals(ExitCode.success.code)); expect(testCoverageResult.stderr, isEmpty); expect(testCoverageResult.stdout, contains('lines......: 100.0%')); }); }, timeout: const Timeout(Duration(minutes: 2)), ); }
very_good_cli/test/e2e_test.dart/0
{'file_path': 'very_good_cli/test/e2e_test.dart', 'repo_id': 'very_good_cli', 'token_count': 5292}
import 'package:mason/mason.dart' hide packageVersion; import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; import 'package:universal_io/io.dart'; import 'package:very_good_cli/src/command_runner.dart'; import 'package:very_good_cli/src/version.dart'; import '../../helpers/helpers.dart'; class FakeProcessResult extends Fake implements ProcessResult {} void main() { const latestVersion = '0.0.0'; group('update', () { test( 'handles pub latest version query errors', withRunner((commandRunner, logger, pubUpdater, printLogs) async { when( () => pubUpdater.getLatestVersion(any()), ).thenThrow(Exception('oops')); final result = await commandRunner.run(['update']); expect(result, equals(ExitCode.software.code)); verify(() => logger.progress('Checking for updates')).called(1); verify(() => logger.err('Exception: oops')); verifyNever( () => pubUpdater.update(packageName: any(named: 'packageName')), ); }), ); test( 'handles pub update errors', withRunner((commandRunner, logger, pubUpdater, printLogs) async { when( () => pubUpdater.getLatestVersion(any()), ).thenAnswer((_) async => latestVersion); when( () => pubUpdater.update(packageName: any(named: 'packageName')), ).thenThrow(Exception('oops')); final result = await commandRunner.run(['update']); expect(result, equals(ExitCode.software.code)); verify(() => logger.progress('Checking for updates')).called(1); verify(() => logger.err('Exception: oops')); verify( () => pubUpdater.update(packageName: any(named: 'packageName')), ).called(1); }), ); test( 'updates when newer version exists', withRunner((commandRunner, logger, pubUpdater, printLogs) async { when( () => pubUpdater.getLatestVersion(any()), ).thenAnswer((_) async => latestVersion); when( () => pubUpdater.update(packageName: packageName), ).thenAnswer((_) => Future.value(FakeProcessResult())); when(() => logger.progress(any())).thenReturn(MockProgress()); final result = await commandRunner.run(['update']); expect(result, equals(ExitCode.success.code)); verify(() => logger.progress('Checking for updates')).called(1); verify(() => logger.progress('Updating to $latestVersion')).called(1); verify(() => pubUpdater.update(packageName: packageName)).called(1); }), ); test( 'does not update when already on latest version', withRunner((commandRunner, logger, pubUpdater, printLogs) async { when( () => pubUpdater.getLatestVersion(any()), ).thenAnswer((_) async => packageVersion); when(() => logger.progress(any())).thenReturn(MockProgress()); final result = await commandRunner.run(['update']); expect(result, equals(ExitCode.success.code)); verify( () => logger.info('Very Good CLI is already at the latest version.'), ).called(1); verifyNever(() => logger.progress('Updating to $latestVersion')); verifyNever(() => pubUpdater.update(packageName: packageName)); }), ); }); }
very_good_cli/test/src/commands/update_test.dart/0
{'file_path': 'very_good_cli/test/src/commands/update_test.dart', 'repo_id': 'very_good_cli', 'token_count': 1323}
import 'package:mason/mason.dart'; import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; import '../pre_gen.dart' as pre_gen; class _MockHookContext extends Mock implements HookContext {} void main() { group('pre_gen', () { late HookContext context; setUp(() { context = _MockHookContext(); }); group('application_id_android', () { test('when specified is unmodified', () { final vars = <String, String>{ 'project_name': 'project_name', 'org_name': 'org_name', 'application_id': 'com.example.app', }; when(() => context.vars).thenReturn(vars); pre_gen.run(context); expect(context.vars['application_id_android'], 'com.example.app'); }); test( '''when not specified is set to `org_name + "." + project_name(snake_case)`''', () { final vars = <String, String>{ 'project_name': 'Project Name', 'org_name': 'org_name', }; when(() => context.vars).thenReturn(vars); pre_gen.run(context); expect( context.vars['application_id_android'], 'org_name.project_name', ); }, ); }); group('application_id', () { test('when specified is unmodified', () { final vars = <String, String>{ 'project_name': 'project_name', 'org_name': 'org_name', 'application_id': 'com.example.app', }; when(() => context.vars).thenReturn(vars); pre_gen.run(context); expect(context.vars['application_id'], 'com.example.app'); }); test( '''when not specified is set to `org_name + "." + project_name(param-case)`''', () { final vars = <String, String>{ 'project_name': 'Project Name', 'org_name': 'org_name', }; when(() => context.vars).thenReturn(vars); pre_gen.run(context); expect( context.vars['application_id'], 'org_name.project-name', ); }, ); }); }); }
very_good_core/brick/hooks/test/pre_gen_test.dart/0
{'file_path': 'very_good_core/brick/hooks/test/pre_gen_test.dart', 'repo_id': 'very_good_core', 'token_count': 1034}
name: my_cli on: pull_request: paths: - ".github/workflows/my_cli.yaml" - "src/my_cli/lib/**" - "src/my_cli/test/**" - "src/my_cli/pubspec.yaml" - "tool/generator/**" push: branches: - main paths: - ".github/workflows/my_cli.yaml" - "src/my_cli/lib/**" - "src/my_cli/test/**" - "src/my_cli/pubspec.yaml" - "tool/generator/**" jobs: build: uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/dart_package.yml@v1 with: working_directory: src/my_cli
very_good_dart_cli/.github/workflows/my_cli.yaml/0
{'file_path': 'very_good_dart_cli/.github/workflows/my_cli.yaml', 'repo_id': 'very_good_dart_cli', 'token_count': 284}
name: my_cli description: A Very Good CLI application version: 0.0.1 publish_to: none environment: sdk: ">=2.18.0 <3.0.0" dependencies: args: ^2.3.1 mason_logger: ^0.2.0 pub_updater: ^0.2.1 dev_dependencies: build_runner: ^2.0.0 build_verify: ^3.0.0 build_version: ^2.0.0 mocktail: ^0.3.0 test: ^1.19.2 very_good_analysis: ^3.1.0 executables: my_executable:
very_good_dart_cli/src/my_cli/pubspec.yaml/0
{'file_path': 'very_good_dart_cli/src/my_cli/pubspec.yaml', 'repo_id': 'very_good_dart_cli', 'token_count': 188}
bricks: very_good_docs_site: path: brick
very_good_docs_site/mason.yaml/0
{'file_path': 'very_good_docs_site/mason.yaml', 'repo_id': 'very_good_docs_site', 'token_count': 20}
blank_issues_enabled: false
very_good_flame_game/brick/__brick__/{{project_name.snakeCase()}}/.github/ISSUE_TEMPLATE/config.yml/0
{'file_path': 'very_good_flame_game/brick/__brick__/{{project_name.snakeCase()}}/.github/ISSUE_TEMPLATE/config.yml', 'repo_id': 'very_good_flame_game', 'token_count': 7}
blank_issues_enabled: false
very_good_flutter_package/.github/ISSUE_TEMPLATE/config.yml/0
{'file_path': 'very_good_flutter_package/.github/ISSUE_TEMPLATE/config.yml', 'repo_id': 'very_good_flutter_package', 'token_count': 7}
bricks: very_good_flutter_package: path: brick
very_good_flutter_package/mason.yaml/0
{'file_path': 'very_good_flutter_package/mason.yaml', 'repo_id': 'very_good_flutter_package', 'token_count': 21}
blank_issues_enabled: false
very_good_flutter_plugin/.github/ISSUE_TEMPLATE/config.yml/0
{'file_path': 'very_good_flutter_plugin/.github/ISSUE_TEMPLATE/config.yml', 'repo_id': 'very_good_flutter_plugin', 'token_count': 7}
name: my_plugin_linux concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true on: pull_request: paths: - ".github/workflows/my_plugin_linux.yaml" - "src/my_plugin/my_plugin_linux/**" push: branches: - main paths: - ".github/workflows/my_plugin_linux.yaml" - "src/my_plugin/my_plugin_linux/**" jobs: build: uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/flutter_package.yml@v1 with: flutter_channel: stable flutter_version: 3.13.2 working_directory: src/my_plugin/my_plugin_linux
very_good_flutter_plugin/.github/workflows/my_plugin_linux.yaml/0
{'file_path': 'very_good_flutter_plugin/.github/workflows/my_plugin_linux.yaml', 'repo_id': 'very_good_flutter_plugin', 'token_count': 261}
blank_issues_enabled: false
very_good_flutter_plugin/brick/__brick__/{{project_name.snakeCase()}}/.github/ISSUE_TEMPLATE/config.yml/0
{'file_path': 'very_good_flutter_plugin/brick/__brick__/{{project_name.snakeCase()}}/.github/ISSUE_TEMPLATE/config.yml', 'repo_id': 'very_good_flutter_plugin', 'token_count': 7}
include: package:very_good_analysis/analysis_options.5.1.0.yaml
very_good_flutter_plugin/brick/__brick__/{{project_name.snakeCase()}}/{{#web}}{{project_name.snakeCase()}}_web{{/web}}/analysis_options.yaml/0
{'file_path': 'very_good_flutter_plugin/brick/__brick__/{{project_name.snakeCase()}}/{{#web}}{{project_name.snakeCase()}}_web{{/web}}/analysis_options.yaml', 'repo_id': 'very_good_flutter_plugin', 'token_count': 23}
import 'dart:io'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:{{project_name.snakeCase()}}_example/main.dart' as app; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); group('E2E', () { testWidgets('getPlatformName', (tester) async { app.main(); await tester.pumpAndSettle(); await tester.tap(find.text('Get Platform Name')); await tester.pumpAndSettle(); final expected = expectedPlatformName(); await tester.ensureVisible(find.text('Platform Name: $expected')); }); }); } String expectedPlatformName() { {{#web}} if (isWeb) return 'Web'; {{/web}}{{#android}} if (Platform.isAndroid) return 'Android'; {{/android}}{{#ios}} if (Platform.isIOS) return 'iOS'; {{/ios}}{{#linux}} if (Platform.isLinux) return 'Linux'; {{/linux}}{{#macos}} if (Platform.isMacOS) return 'MacOS'; {{/macos}}{{#windows}} if (Platform.isWindows) return 'Windows'; {{/windows}} throw UnsupportedError('Unsupported platform ${Platform.operatingSystem}'); } {{#web}}bool get isWeb => identical(0, 0.0); {{/web}}
very_good_flutter_plugin/brick/__brick__/{{project_name.snakeCase()}}/{{project_name.snakeCase()}}/example/integration_test/app_test.dart/0
{'file_path': 'very_good_flutter_plugin/brick/__brick__/{{project_name.snakeCase()}}/{{project_name.snakeCase()}}/example/integration_test/app_test.dart', 'repo_id': 'very_good_flutter_plugin', 'token_count': 415}
name: my_plugin_linux description: Linux implementation of the my_plugin plugin version: 0.1.0+1 publish_to: none environment: sdk: ">=3.0.0 <4.0.0" flutter: plugin: implements: my_plugin platforms: linux: pluginClass: MyPluginPlugin dartPluginClass: MyPluginLinux dependencies: flutter: sdk: flutter my_plugin_platform_interface: path: ../my_plugin_platform_interface dev_dependencies: flutter_test: sdk: flutter very_good_analysis: ^5.1.0
very_good_flutter_plugin/src/my_plugin/my_plugin_linux/pubspec.yaml/0
{'file_path': 'very_good_flutter_plugin/src/my_plugin/my_plugin_linux/pubspec.yaml', 'repo_id': 'very_good_flutter_plugin', 'token_count': 202}
import 'package:my_plugin_platform_interface/src/method_channel_my_plugin.dart'; import 'package:plugin_platform_interface/plugin_platform_interface.dart'; /// The interface that implementations of my_plugin must implement. /// /// Platform implementations should extend this class /// rather than implement it as `MyPlugin`. /// Extending this class (using `extends`) ensures that the subclass will get /// the default implementation, while platform implementations that `implements` /// this interface will be broken by newly added [MyPluginPlatform] methods. abstract class MyPluginPlatform extends PlatformInterface { /// Constructs a MyPluginPlatform. MyPluginPlatform() : super(token: _token); static final Object _token = Object(); static MyPluginPlatform _instance = MethodChannelMyPlugin(); /// The default instance of [MyPluginPlatform] to use. /// /// Defaults to [MethodChannelMyPlugin]. static MyPluginPlatform get instance => _instance; /// Platform-specific plugins should set this with their own platform-specific /// class that extends [MyPluginPlatform] when they register themselves. static set instance(MyPluginPlatform instance) { PlatformInterface.verify(instance, _token); _instance = instance; } /// Return the current platform name. Future<String?> getPlatformName(); }
very_good_flutter_plugin/src/my_plugin/my_plugin_platform_interface/lib/my_plugin_platform_interface.dart/0
{'file_path': 'very_good_flutter_plugin/src/my_plugin/my_plugin_platform_interface/lib/my_plugin_platform_interface.dart', 'repo_id': 'very_good_flutter_plugin', 'token_count': 327}
import 'package:flutter_test/flutter_test.dart'; import 'package:very_good_infinite_list/src/callback_debouncer.dart'; void main() { group('CallbackDebouncer', () { test('calls callback after specified duration expires', () async { const duration = Duration(milliseconds: 250); var callCount = 0; CallbackDebouncer(duration)(() => callCount++); expect(callCount, equals(0)); await Future<void>.delayed(duration); expect(callCount, equals(1)); }); test('immediately calls callback if specified duration is zero', () async { var callCount = 0; CallbackDebouncer(Duration.zero)(() => callCount++); expect(callCount, equals(1)); }); }); }
very_good_infinite_list/test/callback_debouncer_test.dart/0
{'file_path': 'very_good_infinite_list/test/callback_debouncer_test.dart', 'repo_id': 'very_good_infinite_list', 'token_count': 255}
import 'dart:io'; import 'package:ansicolor/ansicolor.dart'; import 'package:barbecue/barbecue.dart'; import 'package:very_good_performance/src/models/models.dart'; class Printer { static void printScore( Report report, Score score, Configuration configuration, ) { final perfMetrics = configuration.performanceMetrics; final missedFrames = perfMetrics.missedFramesThreshold; final averageBuild = perfMetrics.averageFrameBuildRateThreshold; final worstBuild = perfMetrics.worstFrameBuildRateThreshold; stdout ..writeln( Table( tableStyle: const TableStyle(border: true), cellStyle: const CellStyle( borderBottom: true, borderRight: true, borderLeft: true, borderTop: true, alignment: TextAlignment.TopLeft, paddingRight: 1, paddingLeft: 2, ), header: const TableSection( rows: [ Row( cells: [ Cell(''), Cell('Missed Frames'), Cell('Average Frame Build Time ("ms")'), Cell('Worst Frame Build Time("ms")'), ], ), ], ), body: TableSection( rows: [ Row( cells: [ const Cell('Result'), Cell( score.missedFrames.colorize( '${report.missedFrameBuildBudgetCount}', ), ), Cell( score.averageBuildRate.colorize( '${report.averageFrameBuildTimeMillis}', ), ), Cell( score.worstFrameBuildRate.colorize( '${report.worstFrameBuildTimeMillis}', ), ), ], ), Row( cells: [ const Cell('Warning-Error Range'), Cell( '${missedFrames.warning} - ' '${missedFrames.error}', ), Cell( '${averageBuild.warningTimeInMilliseconds} - ' '${averageBuild.errorTimeInMilliseconds}', ), Cell( '${worstBuild.warningTimeInMilliseconds} - ' '${worstBuild.errorTimeInMilliseconds}', ), ], ), ], ), ).render(), ) ..writeln(score.overall.explanation); } static void printReportLocation(Configuration configuration, String name) { final current = Directory.current.path; final message = ''' Two performance reports have been generated. They can be located at: * $current/${configuration.performaceReport.directory}/$name.timeline.json * $current/${configuration.performaceReport.directory}/$name.timeline_summary.json '''; stdout.writeln(message); } } extension on Rating { String colorize(String message) { ansiColorDisabled = false; switch (this) { case Rating.success: final pen = AnsiPen()..green(bold: true); return pen(message); case Rating.warning: final pen = AnsiPen()..yellow(bold: true); return pen(message); case Rating.failure: final pen = AnsiPen()..red(bold: true); return pen(message); } } String get explanation { ansiColorDisabled = false; switch (this) { case Rating.success: final pen = AnsiPen()..green(bold: true); return pen('Very Good! Your application is performing well!'); case Rating.warning: final pen = AnsiPen()..yellow(bold: true); return pen( ''' Heads up! Your application might be starting to experience some degradation in its performance. You might want to consider launching an investigation to understand what components of your application are consuming more resources''', ); case Rating.failure: final pen = AnsiPen()..red(bold: true); return pen('Error! Your application is not performing well!'); } } }
very_good_performance/lib/src/printer.dart/0
{'file_path': 'very_good_performance/lib/src/printer.dart', 'repo_id': 'very_good_performance', 'token_count': 2111}
// Copyright (c) 2022, Very Good Ventures // https://verygood.ventures // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file or at // https://opensource.org/licenses/MIT. import 'dart:async'; import 'dart:developer'; import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'package:hydrated_bloc/hydrated_bloc.dart'; import 'package:path_provider/path_provider.dart'; import 'package:ranch_sounds/ranch_sounds.dart'; import 'package:ranch_ui/ranch_ui.dart'; class AppBlocObserver extends BlocObserver { @override void onChange(BlocBase<dynamic> bloc, Change<dynamic> change) { super.onChange(bloc, change); log('onChange(${bloc.runtimeType}, $change)'); } @override void onError(BlocBase<dynamic> bloc, Object error, StackTrace stackTrace) { log('onError(${bloc.runtimeType}, $error, $stackTrace)'); super.onError(bloc, error, stackTrace); } } Future<void> bootstrap(FutureOr<Widget> Function() builder) async { FlutterError.onError = (details) { log(details.exceptionAsString(), stackTrace: details.stack); }; RanchUITheme.setupFonts(); RanchSoundPlayer.setupMusicLicenses(); await runZonedGuarded( () async { WidgetsFlutterBinding.ensureInitialized(); HydratedBloc.storage = await HydratedStorage.build( storageDirectory: kIsWeb ? HydratedStorage.webStorageDirectory : await getTemporaryDirectory(), ); Bloc.observer = AppBlocObserver(); runApp(await builder()); }, (error, stackTrace) => log(error.toString(), stackTrace: stackTrace), ); }
very_good_ranch/lib/bootstrap.dart/0
{'file_path': 'very_good_ranch/lib/bootstrap.dart', 'repo_id': 'very_good_ranch', 'token_count': 599}
import 'dart:math'; import 'package:flame/components.dart'; import 'package:flame/effects.dart'; import 'package:flame_behaviors/flame_behaviors.dart'; import 'package:flutter/animation.dart'; import 'package:ranch_components/ranch_components.dart'; import 'package:very_good_ranch/game/behaviors/behaviors.dart'; import 'package:very_good_ranch/game/entities/entities.dart'; import 'package:very_good_ranch/game/very_good_ranch_game.dart'; class DraggingBehavior extends ThresholdDraggableBehavior<Unicorn, VeryGoodRanchGame> { DraggingBehavior(); @override double get threshold => 40; Vector2? positionBefore; Anchor? anchorBefore; bool? goingRight; RotateEffect? currentRotateEffect; double? currentDestination; void _addRotateEffect(double to) { currentRotateEffect?.pause(); currentRotateEffect?.removeFromParent(); parent.add( currentRotateEffect = RotateEffect.to( to * degrees2Radians, EffectController( duration: 0.1, ), )..onComplete = () => currentRotateEffect = null, ); } ScaleEffect? currentScaleEffect; void _addScaleEffect(Vector2 to, [VoidCallback? onComplete]) { currentScaleEffect?.pause(); currentScaleEffect?.removeFromParent(); parent.add( currentScaleEffect = ScaleEffect.to( to, EffectController( duration: 0.1, ), )..onComplete = () { currentScaleEffect = null; onComplete?.call(); }, ); } OpacityEffect? currentOpacityEffect; void _addOpacityEffect(double to) { currentOpacityEffect?.pause(); currentOpacityEffect?.removeFromParent(); parent.unicornComponent.add( currentOpacityEffect = OpacityEffect.to( to, EffectController( duration: 0.4, ), )..onComplete = () { currentOpacityEffect = null; }, ); } @override bool onReallyDragStart(DragStartInfo info) { anchorBefore = parent.anchor; parent ..setUnicornState(UnicornState.idle) ..beingDragged = true ..anchor = Anchor.center; final localEventPosition = parent.transform.globalToLocal(info.eventPosition.game); parent ..position = parent.positionOf(localEventPosition) ..isGaugeVisible = false ..overridePriority = 1000; _addScaleEffect(Vector2.all(0.7)); _addOpacityEffect(0.8); positionBefore = parent.position.clone(); return false; } @override bool onReallyDragUpdate(DragUpdateInfo info) { final delta = info.delta.game; if (delta.x < 0 && goingRight != true) { goingRight = true; _addRotateEffect(-15); } if (delta.x > 0 && goingRight != false) { goingRight = false; _addRotateEffect(15); } parent.position.add(delta); _clampUnicorn(); return false; } @override bool onDragEnd(DragEndInfo info) { super.onDragEnd(info); _finishDragging(); return false; } @override bool onDragCancel() { super.onDragCancel(); _finishDragging(); return false; } void _finishDragging() { goingRight = null; parent ..beingDragged = false ..isGaugeVisible = true ..overridePriority = null; _addScaleEffect(Vector2.all(1), () { final anchorBefore = this.anchorBefore; if (anchorBefore != null) { parent ..position = parent.positionOfAnchor(anchorBefore) ..anchor = anchorBefore; this.anchorBefore = null; } }); _addRotateEffect(0); _addOpacityEffect(1); _dropUnicorn(); positionBefore = null; } void _dropUnicorn() { final unicornBottom = parent.positionOfAnchor(Anchor.bottomCenter).y; final yDelta = (parent.position.y - positionBefore!.y).abs(); final dropTargetY = min<double>( 30, gameRef.background.pastureField.bottom - unicornBottom, ); if (dropTargetY > 10 && yDelta > 30) { parent.add( MoveByEffect( Vector2(0, dropTargetY), EffectController( duration: 0.3, curve: Curves.bounceOut, ), ), ); } else { parent.position.add(Vector2(0, dropTargetY)); } } void _clampUnicorn() { final pastureField = gameRef.background.pastureField; final unicornX = parent.position.x.clamp(pastureField.left, pastureField.right); final unicornY = parent.position.y.clamp(pastureField.top, pastureField.bottom); parent.position.x = unicornX; parent.position.y = unicornY; } }
very_good_ranch/lib/game/entities/unicorn/behaviors/dragging_behavior.dart/0
{'file_path': 'very_good_ranch/lib/game/entities/unicorn/behaviors/dragging_behavior.dart', 'repo_id': 'very_good_ranch', 'token_count': 1879}
import 'package:flame/game.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:ranch_ui/ranch_ui.dart'; import 'package:very_good_ranch/game/game.dart'; class FooterWidget extends StatelessWidget { const FooterWidget({ super.key, required this.game, }); final FlameGame game; @override Widget build(BuildContext context) { return Container( width: double.infinity, padding: const EdgeInsets.symmetric( horizontal: 28, vertical: 28, ).copyWith(top: 0), child: SafeArea( top: false, child: Row( mainAxisAlignment: MainAxisAlignment.center, children: const [ _UnicornCounter(type: UnicornType.baby), SizedBox(width: 16), _UnicornCounter(type: UnicornType.child), SizedBox(width: 16), _UnicornCounter(type: UnicornType.teen), SizedBox(width: 16), _UnicornCounter(type: UnicornType.adult), SizedBox(width: 16), ], ), ), ); } } class _UnicornCounter extends StatelessWidget { const _UnicornCounter({ required this.type, }); final UnicornType type; @override Widget build(BuildContext context) { return BlocBuilder<BlessingBloc, BlessingState>( builder: (context, state) { final count = state.getUnicornCountForType(type); return UnicornCounter( isActive: count > 0, type: type, child: Text(count.toString()), ); }, ); } } extension on BlessingState { int getUnicornCountForType(UnicornType type) { switch (type) { case UnicornType.baby: return babyUnicorns; case UnicornType.child: return childUnicorns; case UnicornType.teen: return teenUnicorns; case UnicornType.adult: return adultUnicorns; } } }
very_good_ranch/lib/game/widgets/footer_widget.dart/0
{'file_path': 'very_good_ranch/lib/game/widgets/footer_widget.dart', 'repo_id': 'very_good_ranch', 'token_count': 855}
export 'preload/preload_cubit.dart'; export 'preload/preload_state.dart';
very_good_ranch/lib/loading/cubit/cubit.dart/0
{'file_path': 'very_good_ranch/lib/loading/cubit/cubit.dart', 'repo_id': 'very_good_ranch', 'token_count': 30}
export 'confetti_component.dart'; export 'evolution_component.dart'; export 'rainbow_drop.dart'; export 'star_burst_component.dart';
very_good_ranch/packages/ranch_components/lib/src/components/fx/fx.dart/0
{'file_path': 'very_good_ranch/packages/ranch_components/lib/src/components/fx/fx.dart', 'repo_id': 'very_good_ranch', 'token_count': 45}
import 'dart:ui'; import 'package:dashbook/dashbook.dart'; import 'package:flame/game.dart'; import 'package:flame/input.dart'; import 'package:ranch_components/ranch_components.dart'; class ConfettiComponentExample extends FlameGame with TapDetector { ConfettiComponentExample({ required this.confettiSize, required this.lifespan, }); final double confettiSize; final double lifespan; @override void onTapUp(TapUpInfo info) { add( ConfettiComponent( position: info.eventPosition.game, confettiSize: confettiSize, maxLifespan: lifespan, ), ); } @override Color backgroundColor() => const Color(0xFF666666); } void addConfettiComponentStories(Dashbook dashbook) { dashbook.storiesOf('ConfettiComponent').add( 'basic', (context) { return GameWidget( game: ConfettiComponentExample( confettiSize: context.numberProperty('confettiSize', 10), lifespan: context.numberProperty('lifespan', 1), ), ); }, info: 'Tap on the screen to create confetti', ); }
very_good_ranch/packages/ranch_components/sandbox/lib/stories/confetti_component/stories.dart/0
{'file_path': 'very_good_ranch/packages/ranch_components/sandbox/lib/stories/confetti_component/stories.dart', 'repo_id': 'very_good_ranch', 'token_count': 407}
// ignore_for_file: cascade_invocations import 'dart:math'; import 'dart:ui'; import 'package:flame/cache.dart'; import 'package:flame/components.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:ranch_components/gen/assets.gen.dart'; import 'package:ranch_components/ranch_components.dart'; import '../../helpers/helpers.dart'; class MockRandom extends Mock implements Random {} class MockImages extends Mock implements Images {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); final flameTester = FlameTester( () => TestGame( backgroundColor: const Color(0xFF92DED3), ), gameSize: Vector2(900, 1600), ); group('BackgroundComponent', () { group('preloadAssets', () { testWidgets('preloads assets', (tester) async { final images = MockImages(); when( () => images.loadAll(any()), ).thenAnswer((Invocation invocation) => Future.value(<Image>[])); await BackgroundComponent.preloadAssets(images); verify( () => images.loadAll( [ Assets.background.barn.keyName, Assets.background.sheep.keyName, Assets.background.sheepSmall.keyName, Assets.background.cow.keyName, Assets.background.flowerDuo.keyName, Assets.background.flowerGroup.keyName, Assets.background.flowerSolo.keyName, Assets.background.grass.keyName, Assets.background.shortTree.keyName, Assets.background.tallTree.keyName, Assets.background.linedTree.keyName, Assets.background.linedTreeShort.keyName, ], ), ).called(1); }); }); flameTester.test('has a pasture field', (game) async { final backgroundComponent = BackgroundComponent(); await game.ensureAdd(backgroundComponent); final pastureField = backgroundComponent.pastureField; expect(pastureField, const Rect.fromLTRB(42, 220, 858, 1570)); }); flameTester.testGameWidget( 'renders all the elements', setUp: (game, tester) async { final seed = MockRandom(); when(seed.nextDouble).thenReturn(0.5); when(() => seed.nextInt(any())).thenReturn(0); final backgroundComponent = BackgroundComponent( getDelegate: (pastureField) => BackgroundPositionDelegate(seed, pastureField), ); await game.ensureAdd(backgroundComponent); }, verify: (game, tester) async { await expectLater( find.byGame<TestGame>(), matchesGoldenFile('golden/background/all_elements.png'), ); }, ); }); }
very_good_ranch/packages/ranch_components/test/components/background/background_component_test.dart/0
{'file_path': 'very_good_ranch/packages/ranch_components/test/components/background/background_component_test.dart', 'repo_id': 'very_good_ranch', 'token_count': 1167}
import 'package:flame/components.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:ranch_components/ranch_components.dart'; void main() { group('RainbowDrop', () { testWithFlameGame('adds the target in the game', (game) async { final component = CircleComponent(radius: 50); await game.ensureAdd( RainbowDrop( position: Vector2(0, 0), target: component, sprite: component, ), ); await Future<void>.delayed(const Duration(milliseconds: 600)); await game.ready(); expect( game.descendants().whereType<CircleComponent>().length, greaterThan(0), ); }); testWithFlameGame('adds a confetti in the game', (game) async { final component = CircleComponent(radius: 50); await game.ensureAdd( RainbowDrop( position: Vector2(0, 0), target: component, sprite: component, ), ); await Future<void>.delayed(const Duration(milliseconds: 600)); await game.ready(); expect( game.descendants().whereType<ConfettiComponent>().length, greaterThan(0), ); }); testWithFlameGame('is removed once finished', (game) async { final component = CircleComponent(radius: 50); await game.ensureAdd( RainbowDrop( position: Vector2(0, 0), target: component, sprite: component, ), ); await Future<void>.delayed(const Duration(milliseconds: 600)); await game.ready(); expect( game.descendants().whereType<RainbowDrop>().length, equals(0), ); }); }); }
very_good_ranch/packages/ranch_components/test/components/fx/rainbow_drop_test.dart/0
{'file_path': 'very_good_ranch/packages/ranch_components/test/components/fx/rainbow_drop_test.dart', 'repo_id': 'very_good_ranch', 'token_count': 733}
import 'dart:math'; /// Generates a random value between -1.0 and 1.0 in a exponential distribution. double exponentialDistribution(Random seed, [double exponent = 2]) { final randomDouble = seed.nextDouble(); final linearFactor = (randomDouble * 2) - 1; final isNegative = linearFactor < 0; final exponentialFactor = pow(linearFactor, exponent); return exponentialFactor * (isNegative ? -1 : 1); }
very_good_ranch/packages/ranch_flame/lib/src/exponential_distribution.dart/0
{'file_path': 'very_good_ranch/packages/ranch_flame/lib/src/exponential_distribution.dart', 'repo_id': 'very_good_ranch', 'token_count': 115}
export 'theme.dart'; export 'widget.dart';
very_good_ranch/packages/ranch_ui/lib/src/widgets/modal/modal.dart/0
{'file_path': 'very_good_ranch/packages/ranch_ui/lib/src/widgets/modal/modal.dart', 'repo_id': 'very_good_ranch', 'token_count': 16}
import 'package:dashbook/dashbook.dart'; import 'package:flutter/material.dart'; import 'package:sandbox/stories/modal/stories.dart'; import 'package:sandbox/stories/stories.dart'; void main() { final dashbook = Dashbook(theme: ThemeData.light()); addModalStories(dashbook); addUnicornCounterStories(dashbook); addBoardButtonStories(dashbook); addProgressBarStories(dashbook); runApp(dashbook); }
very_good_ranch/packages/ranch_ui/sandbox/lib/main.dart/0
{'file_path': 'very_good_ranch/packages/ranch_ui/sandbox/lib/main.dart', 'repo_id': 'very_good_ranch', 'token_count': 139}
// ignore_for_file: cascade_invocations import 'package:flame/components.dart'; import 'package:flame_behaviors/flame_behaviors.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:very_good_ranch/game/behaviors/behaviors.dart'; import '../../helpers/helpers.dart'; class _TestEntity extends Entity { _TestEntity({super.behaviors, super.position, super.size}); } void main() { final flameTester = FlameTester(TestGame.new); group('PositionalPriorityBehavior', () { flameTester.test('set priority on load', (game) async { final entity = _TestEntity( position: Vector2(0, 100), size: Vector2(50, 50), behaviors: [PositionalPriorityBehavior()], ); await game.ensureAdd(entity); expect(entity.priority, equals(100)); }); flameTester.test('update priority on position change', (game) async { final entity = _TestEntity( position: Vector2(0, 100), size: Vector2(50, 50), behaviors: [PositionalPriorityBehavior()], ); await game.ensureAdd(entity); entity.position.y += 100; expect(entity.priority, equals(200)); }); flameTester.test('does not update priority when the behavior is removed', (game) async { final behavior = PositionalPriorityBehavior(); final entity = _TestEntity( position: Vector2(0, 100), size: Vector2(50, 50), behaviors: [behavior], ); await game.ensureAdd(entity); entity.remove(behavior); await game.ready(); entity.position.y += 100; expect(entity.priority, equals(100)); }); flameTester.test('uses different anchor for the position', (game) async { final entity = _TestEntity( position: Vector2(0, 100), size: Vector2(50, 50), behaviors: [PositionalPriorityBehavior(anchor: Anchor.bottomRight)], ); await game.ensureAdd(entity); expect(entity.priority, equals(150)); }); }); }
very_good_ranch/test/game/behaviors/positional_priority_behavior_test.dart/0
{'file_path': 'very_good_ranch/test/game/behaviors/positional_priority_behavior_test.dart', 'repo_id': 'very_good_ranch', 'token_count': 792}
// ignore_for_file: cascade_invocations import 'package:flame/components.dart'; import 'package:flame_test/flame_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:ranch_components/ranch_components.dart'; import 'package:very_good_ranch/config.dart'; import 'package:very_good_ranch/game/entities/unicorn/behaviors/behaviors.dart'; import 'package:very_good_ranch/game/entities/unicorn/unicorn.dart'; import 'package:very_good_ranch/game/game.dart'; import '../../../../helpers/helpers.dart'; class _MockEnjoymentDecreasingBehavior extends Mock implements EnjoymentDecreasingBehavior {} class _MockFullnessDecreasingBehavior extends Mock implements FullnessDecreasingBehavior {} void main() { TestWidgetsFlutterBinding.ensureInitialized(); late BlessingBloc blessingBloc; setUpAll(() { registerFallbackValue(MockBlessingEvent()); }); setUp(() { blessingBloc = MockBlessingBloc(); }); final flameTester = FlameTester<VeryGoodRanchGame>( () => VeryGoodRanchGame(blessingBloc: blessingBloc), ); group('Evolution Behavior', () { group('evolves the unicorn', () { flameTester.test('from baby to kid', (game) async { final enjoymentDecreasingBehavior = _MockEnjoymentDecreasingBehavior(); final fullnessDecreasingBehavior = _MockFullnessDecreasingBehavior(); final evolvingBehavior = EvolvingBehavior(); final unicorn = Unicorn.test( position: Vector2.zero(), behaviors: [ enjoymentDecreasingBehavior, fullnessDecreasingBehavior, evolvingBehavior, ], ); await game.ready(); await game.background.ensureAdd(unicorn); expect(unicorn.evolutionStage, UnicornEvolutionStage.baby); unicorn.timesFed = Config.timesThatMustBeFedToEvolve; unicorn.enjoyment.value = 1; unicorn.fullness.value = 1; game.update(0); await game.ready(); game.update(4.2); await game.ready(); expect(unicorn.evolutionStage, UnicornEvolutionStage.child); expect(unicorn.timesFed, 0); await Future.microtask(() { verify( () => blessingBloc.add( const UnicornEvolved(to: UnicornEvolutionStage.child), ), ).called(1); }); }); flameTester.test('from kid to teen', (game) async { final enjoymentDecreasingBehavior = _MockEnjoymentDecreasingBehavior(); final fullnessDecreasingBehavior = _MockFullnessDecreasingBehavior(); final evolvingBehavior = EvolvingBehavior(); final unicorn = Unicorn.test( position: Vector2.zero(), unicornComponent: ChildUnicornComponent(), behaviors: [ evolvingBehavior, enjoymentDecreasingBehavior, fullnessDecreasingBehavior, ], ); await game.ready(); await game.background.ensureAdd(unicorn); await game.ready(); expect(unicorn.evolutionStage, UnicornEvolutionStage.child); unicorn.timesFed = Config.timesThatMustBeFedToEvolve; unicorn.enjoyment.value = 1; unicorn.fullness.value = 1; game.update(0); await game.ready(); game.update(4.2); await game.ready(); expect(unicorn.evolutionStage, UnicornEvolutionStage.teen); expect(unicorn.timesFed, 0); await Future.microtask(() { verify( () => blessingBloc.add( const UnicornEvolved(to: UnicornEvolutionStage.teen), ), ).called(1); }); }); flameTester.test('from teen to adult', (game) async { final enjoymentDecreasingBehavior = _MockEnjoymentDecreasingBehavior(); final fullnessDecreasingBehavior = _MockFullnessDecreasingBehavior(); final evolvingBehavior = EvolvingBehavior(); final unicorn = Unicorn.test( position: Vector2.zero(), unicornComponent: TeenUnicornComponent(), behaviors: [ evolvingBehavior, enjoymentDecreasingBehavior, fullnessDecreasingBehavior, ], ); await game.ready(); await game.background.ensureAdd(unicorn); game.update(5); expect(unicorn.evolutionStage, UnicornEvolutionStage.teen); unicorn.timesFed = Config.timesThatMustBeFedToEvolve; unicorn.enjoyment.value = 1; unicorn.fullness.value = 1; game.update(0); await game.ready(); game.update(4.2); await game.ready(); expect(unicorn.evolutionStage, UnicornEvolutionStage.adult); expect(unicorn.timesFed, 0); await Future.microtask(() { verify( () => blessingBloc.add( const UnicornEvolved(to: UnicornEvolutionStage.adult), ), ).called(1); }); }); flameTester.test( 'stops evolution when reaches the adult stage', (game) async { final enjoymentDecreasingBehavior = _MockEnjoymentDecreasingBehavior(); final fullnessDecreasingBehavior = _MockFullnessDecreasingBehavior(); final evolvingBehavior = EvolvingBehavior(); final unicorn = Unicorn.test( position: Vector2.zero(), unicornComponent: AdultUnicornComponent(), behaviors: [ evolvingBehavior, enjoymentDecreasingBehavior, fullnessDecreasingBehavior, ], ); await game.ready(); await game.background.ensureAdd(unicorn); expect(unicorn.evolutionStage, UnicornEvolutionStage.adult); unicorn.timesFed = Config.timesThatMustBeFedToEvolve; unicorn.enjoyment.value = 1; unicorn.fullness.value = 1; game.update(0); expect(unicorn.evolutionStage, UnicornEvolutionStage.adult); expect(unicorn.timesFed, Config.timesThatMustBeFedToEvolve); await Future.microtask(() { verifyNever( () => blessingBloc.add(any(that: isA<UnicornEvolved>())), ); }); }, ); flameTester.test( 'stops evolution when the unicorn is not fed enough', (game) async { final enjoymentDecreasingBehavior = _MockEnjoymentDecreasingBehavior(); final fullnessDecreasingBehavior = _MockFullnessDecreasingBehavior(); final evolvingBehavior = EvolvingBehavior(); final unicorn = Unicorn.test( position: Vector2.zero(), unicornComponent: ChildUnicornComponent(), behaviors: [ evolvingBehavior, enjoymentDecreasingBehavior, fullnessDecreasingBehavior, ], ); await game.ready(); await game.background.ensureAdd(unicorn); expect(unicorn.evolutionStage, UnicornEvolutionStage.child); unicorn.timesFed = 0; unicorn.enjoyment.value = 1; unicorn.fullness.value = 1; game.update(0); expect(unicorn.evolutionStage, UnicornEvolutionStage.child); expect(unicorn.timesFed, 0); await Future.microtask(() { verifyNever( () => blessingBloc.add(any(that: isA<UnicornEvolved>())), ); }); }, ); flameTester.test( 'stops evolution when the unicorn is not happy enough', (game) async { final enjoymentDecreasingBehavior = _MockEnjoymentDecreasingBehavior(); final fullnessDecreasingBehavior = _MockFullnessDecreasingBehavior(); final evolvingBehavior = EvolvingBehavior(); final unicorn = Unicorn.test( position: Vector2.zero(), unicornComponent: ChildUnicornComponent(), behaviors: [ evolvingBehavior, enjoymentDecreasingBehavior, fullnessDecreasingBehavior, ], ); await game.ready(); await game.background.ensureAdd(unicorn); expect(unicorn.evolutionStage, UnicornEvolutionStage.child); unicorn.timesFed = Config.timesThatMustBeFedToEvolve; unicorn.enjoyment.value = 0; unicorn.fullness.value = 0; game.update(0); expect(unicorn.evolutionStage, UnicornEvolutionStage.child); expect(unicorn.timesFed, Config.timesThatMustBeFedToEvolve); await Future.microtask(() { verifyNever( () => blessingBloc.add(any(that: isA<UnicornEvolved>())), ); }); }, ); flameTester.test( 'stops evolution when there is a evolution already scheduled', (game) async { final enjoymentDecreasingBehavior = _MockEnjoymentDecreasingBehavior(); final fullnessDecreasingBehavior = _MockFullnessDecreasingBehavior(); final evolvingBehavior = EvolvingBehavior(); final unicorn = Unicorn.test( position: Vector2.zero(), unicornComponent: ChildUnicornComponent(), behaviors: [ evolvingBehavior, enjoymentDecreasingBehavior, fullnessDecreasingBehavior, ], ); await game.ready(); await game.background.ensureAdd(unicorn); await game.ready(); expect(unicorn.evolutionStage, UnicornEvolutionStage.child); unicorn.timesFed = Config.timesThatMustBeFedToEvolve; unicorn.enjoyment.value = 1; unicorn.fullness.value = 1; unicorn.waitingCurrentAnimationToEvolve = true; game.update(0); expect(unicorn.evolutionStage, UnicornEvolutionStage.child); expect(unicorn.timesFed, 5); verifyNever(() => blessingBloc.add(any(that: isA<UnicornEvolved>()))); }, ); }); group('on evolution', () { flameTester.test( 'resets enjoyment and fullness factors to full', (game) async { final enjoymentDecreasingBehavior = _MockEnjoymentDecreasingBehavior(); final fullnessDecreasingBehavior = _MockFullnessDecreasingBehavior(); final evolvingBehavior = EvolvingBehavior(); final unicorn = Unicorn.test( position: Vector2.zero(), unicornComponent: ChildUnicornComponent(), behaviors: [ evolvingBehavior, enjoymentDecreasingBehavior, fullnessDecreasingBehavior, ], ); await game.ready(); await game.background.ensureAdd(unicorn); expect(unicorn.evolutionStage, UnicornEvolutionStage.child); unicorn.timesFed = Config.timesThatMustBeFedToEvolve; // Setting happiness to above the threshold, but not full unicorn.enjoyment.value = 0.95; unicorn.fullness.value = 0.95; game.update(0); await game.ready(); game.update(4.2); await game.ready(); expect(unicorn.evolutionStage, UnicornEvolutionStage.teen); expect(unicorn.timesFed, 0); expect(unicorn.fullness.value, 1); expect(unicorn.enjoyment.value, 1); }, ); }); }); }
very_good_ranch/test/game/entities/unicorn/behaviours/evolving_behavior_test.dart/0
{'file_path': 'very_good_ranch/test/game/entities/unicorn/behaviours/evolving_behavior_test.dart', 'repo_id': 'very_good_ranch', 'token_count': 5075}
import 'package:flame/game.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:ranch_ui/ranch_ui.dart'; import 'package:very_good_ranch/game/game.dart'; import '../../helpers/helpers.dart'; void main() { group('FooterWidget', () { late FlameGame game; late BlessingBloc blessingBloc; setUp(() { game = FlameGame(); blessingBloc = MockBlessingBloc(); when(() => blessingBloc.state).thenReturn( BlessingState.zero(babyUnicorns: 1), ); game.overlays.addEntry( 'settings', (context, game) => const SizedBox.shrink(), ); }); testWidgets('renders correctly', (tester) async { await tester.pumpApp( blessingBloc: blessingBloc, Scaffold( body: FooterWidget(game: game), ), ); UnicornCounter getUnicownCounter(int at) { return find.byType(UnicornCounter).evaluate().elementAt(at).widget as UnicornCounter; } expect(find.byType(UnicornCounter), findsNWidgets(4)); expect(getUnicownCounter(0).type, UnicornType.baby); expect(getUnicownCounter(0).isActive, true); expect(getUnicownCounter(1).type, UnicornType.child); expect(getUnicownCounter(1).isActive, false); expect(getUnicownCounter(2).type, UnicornType.teen); expect(getUnicownCounter(2).isActive, false); expect(getUnicownCounter(3).type, UnicornType.adult); expect(getUnicownCounter(3).isActive, false); }); }); }
very_good_ranch/test/game/widgets/footer_widget_test.dart/0
{'file_path': 'very_good_ranch/test/game/widgets/footer_widget_test.dart', 'repo_id': 'very_good_ranch', 'token_count': 665}
// Copyright (c) 2022, Very Good Ventures // https://verygood.ventures // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file or at // https://opensource.org/licenses/MIT. // ignore_for_file: prefer_const_constructors import 'dart:async'; import 'dart:ui'; import 'package:bloc_test/bloc_test.dart'; import 'package:flutter/widgets.dart' hide Image; import 'package:flutter_test/flutter_test.dart'; import 'package:mockingjay/mockingjay.dart'; import 'package:ranch_flame/ranch_flame.dart'; import 'package:ranch_sounds/ranch_sounds.dart'; import 'package:ranch_ui/ranch_ui.dart'; import 'package:very_good_ranch/game_menu/game_menu.dart'; import 'package:very_good_ranch/gen/assets.gen.dart'; import 'package:very_good_ranch/loading/loading.dart'; import '../../helpers/helpers.dart'; class MockUnprefixedImages extends Mock implements UnprefixedImages {} class MockRanchSoundPlayer extends Mock implements RanchSoundPlayer {} void main() { group('LoadingPage', () { late PreloadCubit preloadCubit; late SettingsBloc settingsBloc; late MockUnprefixedImages images; late MockRanchSoundPlayer sounds; setUp(() { preloadCubit = PreloadCubit( images = MockUnprefixedImages(), sounds = MockRanchSoundPlayer(), ); settingsBloc = MockSettingsBloc(); whenListen( settingsBloc, const Stream<SettingsState>.empty(), initialState: SettingsState(), ); when( () => images.loadAll(any()), ).thenAnswer((Invocation invocation) => Future.value(<Image>[])); when(() => sounds.preloadAssets([RanchSound.sunsetMemory])) .thenAnswer((Invocation invocation) async {}); when(() => sounds.play(RanchSound.sunsetMemory)) .thenAnswer((Invocation invocation) async {}); when(() => sounds.stop(RanchSound.sunsetMemory)) .thenAnswer((Invocation invocation) async {}); }); testWidgets('basic layout', (tester) async { await tester.pumpApp( LoadingPage(), preloadCubit: preloadCubit, settingsBloc: settingsBloc, ); expect( find.image(AssetImage(Assets.images.loading.keyName)), findsOneWidget, ); expect(find.byType(AnimatedProgressBar), findsOneWidget); expect(find.textContaining('Loading'), findsOneWidget); await tester.pumpAndSettle(Duration(seconds: 1)); }); testWidgets('loading text', (tester) async { Text textWidgetFinder() { return find.textContaining('Loading').evaluate().first.widget as Text; } await tester.pumpApp( LoadingPage(), preloadCubit: preloadCubit, settingsBloc: settingsBloc, ); expect(textWidgetFinder().data, 'Loading ...'); unawaited(preloadCubit.loadSequentially()); await tester.pump(); expect(textWidgetFinder().data, 'Loading Delightful music...'); await tester.pump(const Duration(milliseconds: 200)); expect(textWidgetFinder().data, 'Loading Farmhouse...'); await tester.pump(const Duration(milliseconds: 200)); expect(textWidgetFinder().data, 'Loading Snacks...'); await tester.pump(const Duration(milliseconds: 200)); expect(textWidgetFinder().data, 'Loading Baby unicorns...'); await tester.pump(const Duration(milliseconds: 200)); expect(textWidgetFinder().data, 'Loading Child unicorns...'); await tester.pump(const Duration(milliseconds: 200)); expect(textWidgetFinder().data, 'Loading Teen unicorns...'); await tester.pump(const Duration(milliseconds: 200)); expect(textWidgetFinder().data, 'Loading Handsome unicorns...'); await tester.pump(const Duration(milliseconds: 200)); /// flush animation timers await tester.pumpAndSettle(); }); testWidgets('redirects after loading', (tester) async { final navigator = MockNavigator(); when(() => navigator.pushReplacement<void, void>(any())) .thenAnswer((_) async {}); await tester.pumpApp( LoadingPage(), preloadCubit: preloadCubit, settingsBloc: settingsBloc, navigator: navigator, ); unawaited(preloadCubit.loadSequentially()); await tester.pump(const Duration(milliseconds: 800)); await tester.pumpAndSettle(); verify(() => navigator.pushReplacement<void, void>(any())).called(1); }); }); }
very_good_ranch/test/loading/view/loading_page_test.dart/0
{'file_path': 'very_good_ranch/test/loading/view/loading_page_test.dart', 'repo_id': 'very_good_ranch', 'token_count': 1688}
name: very_good_test_runner concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true on: pull_request: branches: - main push: branches: - main jobs: semantic-pull-request: uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/semantic_pull_request.yml@v1 spell-check: uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/spell_check.yml@v1 with: includes: "**/*.md" modified_files_only: false build: uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/flutter_package.yml@v1 with: flutter_version: 3.7.3 pana_score: uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/pana.yml@v1
very_good_test_runner/.github/workflows/main.yaml/0
{'file_path': 'very_good_test_runner/.github/workflows/main.yaml', 'repo_id': 'very_good_test_runner', 'token_count': 298}
name: very_good_test_runner description: A test runner for Flutter and Dart created by Very Good Ventures homepage: https://github.com/VeryGoodOpenSource/very_good_test_runner version: 0.1.2 environment: sdk: ">=2.18.0 <3.0.0" dependencies: json_annotation: ^4.4.0 universal_io: ^2.0.0 dev_dependencies: build_runner: ^2.0.0 build_verify: ^3.1.0 json_serializable: ^6.0.0 mocktail: ">=0.3.0 <2.0.0" test: ^1.19.2 very_good_analysis: ^4.0.0
very_good_test_runner/pubspec.yaml/0
{'file_path': 'very_good_test_runner/pubspec.yaml', 'repo_id': 'very_good_test_runner', 'token_count': 199}
import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; Future<void> simulatePlatformCall( String channel, String method, [ dynamic arguments, ]) async { const standardMethod = StandardMethodCodec(); await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .handlePlatformMessage( channel, standardMethod.encodeMethodCall(MethodCall(method, arguments)), null, ); }
very_good_wear_app/brick/__brick__/{{project_name.snakeCase()}}/test/helpers/simulate_platform_call.dart/0
{'file_path': 'very_good_wear_app/brick/__brick__/{{project_name.snakeCase()}}/test/helpers/simulate_platform_call.dart', 'repo_id': 'very_good_wear_app', 'token_count': 138}
name: Dart Pub Publish Workflow on: workflow_call: inputs: dart_sdk: required: false type: string default: "stable" working_directory: required: false type: string default: "." runs_on: required: false type: string default: "ubuntu-latest" pub_credentials: required: true type: string timeout_minutes: required: false type: number default: 5 jobs: publish: defaults: run: working-directory: ${{inputs.working_directory}} runs-on: ${{inputs.runs_on}} timeout-minutes: ${{inputs.timeout_minutes}} steps: - name: 📚 Git Checkout uses: actions/checkout@v4 - name: 🎯 Setup Dart uses: dart-lang/setup-dart@v1 with: sdk: ${{inputs.dart_sdk}} - name: 📦 Install Dependencies run: dart pub get - name: 🔐 Setup Pub Credentials run: | mkdir -p $XDG_CONFIG_HOME/dart echo '${{inputs.pub_credentials}}' > "$XDG_CONFIG_HOME/dart/pub-credentials.json" - name: 🌵 Dry Run run: dart pub publish --dry-run - name: 📢 Publish run: dart pub publish -f
very_good_workflows/.github/workflows/dart_pub_publish.yml/0
{'file_path': 'very_good_workflows/.github/workflows/dart_pub_publish.yml', 'repo_id': 'very_good_workflows', 'token_count': 619}
include: package:mfsao/analysis_options.yaml
voute/analysis_options.yaml/0
{'file_path': 'voute/analysis_options.yaml', 'repo_id': 'voute', 'token_count': 15}
import 'package:voute/models/config.dart'; import 'package:voute/models/user/user.dart'; class MockModel { static ConfigModel get config => ConfigModel(); static UserModel get user => UserModel((b) => b ..id = 1 ..email = "jeremiahogbomo@gmail.com" ..name = "Jon" ..phone = "123456789" ..createdAt = DateTime.now() ..updatedAt = DateTime.now()); }
voute/lib/models/mock.dart/0
{'file_path': 'voute/lib/models/mock.dart', 'repo_id': 'voute', 'token_count': 142}
import 'dart:async'; import 'package:rebloc/rebloc.dart'; import 'package:voute/constants/mk_strings.dart'; import 'package:voute/rebloc/actions/user.dart'; import 'package:voute/rebloc/states/app.dart'; import 'package:voute/rebloc/states/user.dart'; import 'package:voute/services/users.dart'; class UserBloc extends SimpleBloc<AppState> { @override Future<Action> middleware(DispatchFunction dispatcher, AppState state, Action action) async { if (action is UserAsyncInitAction) { return const UserAsyncLoadingAction(); } return action; } @override AppState reducer(AppState state, Action action) { if (action is UserAsyncLoadingAction) { return state.rebuild( (s) => s..user.update((b) => b..status = UserStatus.loading), ); } if (action is UserAsyncFailureAction) { return state.rebuild( (s) => s ..user.update((b) => b ..status = UserStatus.failure ..error = action.error), ); } if (action is UserUpdateAction) { return state.rebuild( (s) => s ..user.update((b) => b ..user = action.user.toBuilder() ..status = UserStatus.success), ); } return state; } @override Future<Action> afterware(DispatchFunction dispatcher, AppState state, Action action) async { if (action is UserAsyncLoadingAction) { try { final res = await Users.di().fetch(state.user.user.id); dispatcher(UserAsyncSuccessAction(res)); } catch (error) { dispatcher(UserAsyncFailureAction(MkStrings.genericError(error))); } } return action; } }
voute/lib/rebloc/blocs/user.dart/0
{'file_path': 'voute/lib/rebloc/blocs/user.dart', 'repo_id': 'voute', 'token_count': 673}
import 'package:feather_icons_flutter/feather_icons_flutter.dart'; import 'package:flutter/material.dart'; import 'package:voute/utils/mk_screen_util.dart'; import 'package:voute/utils/mk_theme.dart'; import 'package:voute/widgets/_partials/mk_icon_button.dart'; class PersonItem extends StatelessWidget { const PersonItem({Key key}) : super(key: key); @override Widget build(BuildContext context) { return Material( elevation: 4, shadowColor: Colors.black12, borderRadius: BorderRadius.circular(4), clipBehavior: Clip.hardEdge, child: InkWell( onTap: () {}, child: SizedBox( height: sh(48), child: Row( children: <Widget>[ SizedBox(width: sh(16)), CircleAvatar(child: Text("A")), SizedBox(width: sh(16)), Expanded(child: Text("Agbeke", style: MkTheme.of(context).subhead1Medium)), MkIconButton( icon: FeatherIcons.moreHorizontal, onPressed: () {}, ), ], ), ), ), ); } }
voute/lib/screens/people/_partials/person_item.dart/0
{'file_path': 'voute/lib/screens/people/_partials/person_item.dart', 'repo_id': 'voute', 'token_count': 533}
import 'package:flutter/services.dart'; class MkTextInputType { static const TextInputType number = TextInputType.numberWithOptions(decimal: true, signed: true); }
voute/lib/utils/mk_text_input_type.dart/0
{'file_path': 'voute/lib/utils/mk_text_input_type.dart', 'repo_id': 'voute', 'token_count': 49}
import 'package:flutter/widgets.dart'; class KeyboardWrapperView extends StatelessWidget { const KeyboardWrapperView({Key key, @required this.child}) : super(key: key); final Widget child; @override Widget build(BuildContext context) { return GestureDetector( behavior: HitTestBehavior.opaque, onTap: () => FocusScope.of(context).requestFocus(FocusNode()), child: child, ); } }
voute/lib/widgets/_views/keyboard_wrapper_view.dart/0
{'file_path': 'voute/lib/widgets/_views/keyboard_wrapper_view.dart', 'repo_id': 'voute', 'token_count': 144}
version: "2" checks: file-lines: enabled: false method-count: enabled: false method-complexity: enabled: false method-lines: enabled: false similar-code: enabled: false plugins: markdownlint: enabled: true checks: MD013: enabled: false MD036: enabled: false nodesecurity: enabled: true tslint: enabled: true exclude_patterns: - ".*" - ".*/" - "*.*" - "!*.md" - "!src/**/*.ts" - "!test/**/*.ts"
vscode-icons/.codeclimate.yml/0
{'file_path': 'vscode-icons/.codeclimate.yml', 'repo_id': 'vscode-icons', 'token_count': 220}
import 'package:flutter/material.dart'; class DebugConsole extends StatelessWidget { const DebugConsole({ Key key, }) : super(key: key); @override Widget build(BuildContext context) { return Container( // color: Colors.brown, ); } }
vscode_ipad/lib/ui/windows/debug_console.dart/0
{'file_path': 'vscode_ipad/lib/ui/windows/debug_console.dart', 'repo_id': 'vscode_ipad', 'token_count': 92}
import 'package:flutter/material.dart'; Offset getThrowOffsetFromDragLocation(Offset drag, double min) { return Offset( drag.dx.abs() / drag.dy.abs() < 0.2 ? 0 : min * drag.dx.sign, drag.dy.abs() / drag.dx.abs() < 0.2 ? 0 : min * drag.dy.sign, ); } /// To achieve infinite lists, we build each child widget of the list on demand /// and provide it with the index of the child that we want to see instead of /// the actual list index /// For the case of the stack of cards, we want to see the active card, /// and when that card is dismissed, the one before it is now the active card /// and should be built at the end of the list /// /// We have several inputs to consider: /// - The `index` which is the original index of the list /// - The `count` which is the number of items in the list /// - The `activeIndex` which is the index of the item to be shown /// - We want to reverse the list, such that when the stack is meant to display /// a list of widgets, the first provided widget should be on the surface /// and the first to be dismissed, hence it's at the end of the list /// /// This `activeIndex` value is incremented by 1 everytime a card is dismissed /// So to show the correct widget for every list item, we determine the distance /// between this item and the active item and use % to reset the index /// when it exceeds the length of the list /// Lastly, if `isReversed` is `true`, we subtract this value from the /// last index (count - 1), to display the list in reverse int getModIndexFromActiveIndex( int index, int activeIndex, int count, { bool isReversed = true, }) { final modIndex = (index - activeIndex) % count; return isReversed ? count - 1 - modIndex : modIndex; } /// To gradually scale down widgets, limited by min and max scales double getScaleByIndex(int index, double min, double max, int count) { return min + ((max - min) / count) * (index + 1); }
wallet_app_workshop/lib/core/utils.dart/0
{'file_path': 'wallet_app_workshop/lib/core/utils.dart', 'repo_id': 'wallet_app_workshop', 'token_count': 544}
// 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 'package:args/command_runner.dart'; import 'package:web_driver_installer/safari_driver_runner.dart'; /// Wrapper class on top of [SafariDriverRunner] to use it as a command. class SafariDriverCommand extends Command<bool> { @override String get description => 'Safari Driver runner.'; @override String get name => 'safaridriver'; /// If the version is provided as an argument, it is checked against the /// system version and an exception is thrown if they do not match. final String defaultDriverVersion = 'system'; SafariDriverCommand() { argParser ..addOption('driver-version', defaultsTo: defaultDriverVersion, help: 'Run the given version of the driver. If the given version ' 'does not exists throw an error.'); } final SafariDriverRunner safariDriverRunner = SafariDriverRunner(); @override Future<bool> run() async { final String driverVersion = argResults!['driver-version']; try { await safariDriverRunner.start(version: driverVersion); return true; } catch (e) { print('Exception during running the safari driver: $e'); return false; } } }
web_installers/packages/web_drivers/lib/safari_driver_command.dart/0
{'file_path': 'web_installers/packages/web_drivers/lib/safari_driver_command.dart', 'repo_id': 'web_installers', 'token_count': 418}
import 'dart:async'; import 'package:web_socket_client/web_socket_client.dart'; /// An object which contains information regarding the /// current WebSocket connection. abstract class Connection extends Stream<ConnectionState> { /// The current state of the WebSocket connection. ConnectionState get state; } /// {@template connection_controller} /// A WebSocket connection controller. /// {@endtemplate} class ConnectionController extends Connection { /// {@macro connection_controller} ConnectionController() : _state = const Connecting(), _controller = StreamController<ConnectionState>.broadcast(); ConnectionState _state; final StreamController<ConnectionState> _controller; @override ConnectionState get state => _state; @override StreamSubscription<ConnectionState> listen( void Function(ConnectionState event)? onData, { Function? onError, void Function()? onDone, bool? cancelOnError, }) { return _stream.distinct().listen( onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError, ); } Stream<ConnectionState> get _stream async* { yield _state; yield* _controller.stream; } /// Notifies listeners of a new connection [state]. void add(ConnectionState state) { _state = state; _controller.add(state); } /// Closes the controller's stream. void close() => _controller.close(); }
web_socket_client/lib/src/connection.dart/0
{'file_path': 'web_socket_client/lib/src/connection.dart', 'repo_id': 'web_socket_client', 'token_count': 454}
analyzer: exclude: [flutter, site-shared, src, tmp]
website/analysis_options.yaml/0
{'file_path': 'website/analysis_options.yaml', 'repo_id': 'website', 'token_count': 20}
version: "3.9" services: site: image: flt-dev build: context: . target: dev command: ["make", "serve"] env_file: .env environment: - NODE_ENV=development - JEKYLL_ENV=development ports: - "4002:4002" - "35730:35730" - "5502:5502" volumes: - ./:/app - site_bundle:/usr/local/bundle volumes: site_bundle:
website/docker-compose.yml/0
{'file_path': 'website/docker-compose.yml', 'repo_id': 'website', 'token_count': 202}
name: basic_staggered publish_to: none description: An introductory example to staggered animations. environment: sdk: ^3.2.0 dependencies: flutter: sdk: flutter dev_dependencies: example_utils: path: ../../example_utils flutter_test: sdk: flutter flutter: uses-material-design: true
website/examples/_animation/basic_staggered_animation/pubspec.yaml/0
{'file_path': 'website/examples/_animation/basic_staggered_animation/pubspec.yaml', 'repo_id': 'website', 'token_count': 114}
// Copyright 2017 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. /* This app arranges its photos (allPhotos) in a list of blocks, where each block contains an arrangement of a handful of photos defined by photoBlockFrames. */ import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart' show timeDilation; class Photo { const Photo(this.asset, this.id); final String asset; final int id; @override bool operator ==(Object other) => identical(this, other) || other is Photo && runtimeType == other.runtimeType && id == other.id; @override int get hashCode => id.hashCode; } final List<Photo> allPhotos = List<Photo>.generate(30, (index) { return Photo('images/pic${index + 1}.jpg', index); }); class PhotoFrame { const PhotoFrame(this.width, this.height); final double width; final double height; } // Defines the app's repeating photo layout "block" in terms of // photoBlockFrames.length rows of photos. // // Each photoBlockFrames[i] item defines the layout of one row of photos // in terms of their relative widgets and heights. In a row: widths must // sum to 1.0, heights must be the same. const List<List<PhotoFrame>> photoBlockFrames = [ [PhotoFrame(1.0, 0.4)], [PhotoFrame(0.25, 0.3), PhotoFrame(0.75, 0.3)], [PhotoFrame(0.75, 0.3), PhotoFrame(0.25, 0.3)], ]; class PhotoCheck extends StatelessWidget { const PhotoCheck({super.key}); @override Widget build(BuildContext context) { return DecoratedBox( decoration: BoxDecoration( color: Theme.of(context).primaryColor, borderRadius: const BorderRadius.all(Radius.circular(16)), ), child: const Icon( Icons.check, size: 32, color: Colors.white, ), ); } } class PhotoItem extends StatefulWidget { const PhotoItem({ super.key, required this.photo, this.color, this.onTap, required this.selected, }); final Photo photo; final Color? color; final VoidCallback? onTap; final bool selected; @override State<PhotoItem> createState() => _PhotoItemState(); } class _PhotoItemState extends State<PhotoItem> with TickerProviderStateMixin { late final AnimationController _selectController; late final Animation<double> _stackScaleAnimation; late final Animation<RelativeRect> _imagePositionAnimation; late final Animation<double> _checkScaleAnimation; late final Animation<double> _checkSelectedOpacityAnimation; late final AnimationController _replaceController; late final Animation<Offset> _replaceNewPhotoAnimation; late final Animation<Offset> _replaceOldPhotoAnimation; late final Animation<double> _removeCheckAnimation; late Photo _oldPhoto; Photo? _newPhoto; // non-null during a remove animation @override void initState() { super.initState(); _oldPhoto = widget.photo; _selectController = AnimationController( duration: const Duration(milliseconds: 300), vsync: this); final Animation<double> easeSelection = CurvedAnimation( parent: _selectController, curve: Curves.easeIn, ); _stackScaleAnimation = Tween<double>(begin: 1.0, end: 0.85).animate(easeSelection); _checkScaleAnimation = Tween<double>(begin: 0.0, end: 1.25).animate(easeSelection); _checkSelectedOpacityAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(easeSelection); _imagePositionAnimation = RelativeRectTween( begin: const RelativeRect.fromLTRB(0.0, 0.0, 0.0, 0.0), end: const RelativeRect.fromLTRB(12.0, 12.0, 12.0, 12.0), ).animate(easeSelection); _replaceController = AnimationController( duration: const Duration(milliseconds: 300), vsync: this); final Animation<double> easeInsert = CurvedAnimation( parent: _replaceController, curve: Curves.easeIn, ); _replaceNewPhotoAnimation = Tween<Offset>( begin: const Offset(1.0, 0.0), end: Offset.zero, ).animate(easeInsert); _replaceOldPhotoAnimation = Tween<Offset>( begin: const Offset(0.0, 0.0), end: const Offset(-1.0, 0.0), ).animate(easeInsert); _removeCheckAnimation = Tween<double>(begin: 1.0, end: 0.0).animate( CurvedAnimation( parent: _replaceController, curve: const Interval(0.0, 0.25, curve: Curves.easeIn), ), ); } @override void dispose() { _selectController.dispose(); _replaceController.dispose(); super.dispose(); } @override void didUpdateWidget(PhotoItem oldWidget) { super.didUpdateWidget(oldWidget); if (widget.photo != oldWidget.photo) { _replace(oldWidget.photo, widget.photo); } if (widget.selected != oldWidget.selected) _select(); } Future<void> _replace(Photo oldPhoto, Photo newPhoto) async { try { setState(() { _oldPhoto = oldPhoto; _newPhoto = newPhoto; }); await _replaceController.forward().orCancel; setState(() { _oldPhoto = newPhoto; _newPhoto = null; _replaceController.value = 0.0; _selectController.value = 0.0; }); } on TickerCanceled { // This is never reached... } } void _select() { if (widget.selected) { _selectController.forward(); } else { _selectController.reverse(); } } @override Widget build(BuildContext context) { return Stack( children: <Widget>[ Positioned.fill( child: ClipRect( child: SlideTransition( position: _replaceOldPhotoAnimation, child: Material( color: widget.color, child: InkWell( onTap: widget.onTap, child: ScaleTransition( scale: _stackScaleAnimation, child: Stack( children: <Widget>[ PositionedTransition( rect: _imagePositionAnimation, child: Image.asset( _oldPhoto.asset, fit: BoxFit.cover, ), ), Positioned( top: 0.0, left: 0.0, child: FadeTransition( opacity: _checkSelectedOpacityAnimation, child: FadeTransition( opacity: _removeCheckAnimation, child: ScaleTransition( alignment: Alignment.topLeft, scale: _checkScaleAnimation, child: const PhotoCheck(), ), ), ), ), PositionedTransition( rect: _imagePositionAnimation, child: Container( margin: const EdgeInsets.all(8), alignment: Alignment.topRight, child: Text( widget.photo.id.toString(), style: const TextStyle(color: Colors.green), ), ), ), ], ), ), ), ), ), ), ), Positioned.fill( child: ClipRect( child: SlideTransition( position: _replaceNewPhotoAnimation, child: _newPhoto == null ? null : Image.asset( _newPhoto!.asset, fit: BoxFit.cover, ), ), ), ), ], ); } } class ImagesDemo extends StatefulWidget { const ImagesDemo({super.key}); @override State<ImagesDemo> createState() => _ImagesDemoState(); } class _ImagesDemoState extends State<ImagesDemo> with SingleTickerProviderStateMixin { static const double _photoBlockHeight = 576.0; int? _selectedPhotoIndex; void _selectPhoto(int photoIndex) { setState(() { _selectedPhotoIndex = photoIndex == _selectedPhotoIndex ? null : photoIndex; }); } void _removeSelectedPhoto() { if (_selectedPhotoIndex == null) return; setState(() { allPhotos.removeAt(_selectedPhotoIndex!); _selectedPhotoIndex = null; }); } Widget _buildPhotoBlock( BuildContext context, int blockIndex, int blockFrameCount) { final List<Widget> rows = []; var startPhotoIndex = blockIndex * blockFrameCount; final photoColor = Colors.grey[500]!; for (int rowIndex = 0; rowIndex < photoBlockFrames.length; rowIndex += 1) { final List<Widget> rowChildren = []; final int rowLength = photoBlockFrames[rowIndex].length; for (var frameIndex = 0; frameIndex < rowLength; frameIndex += 1) { final frame = photoBlockFrames[rowIndex][frameIndex]; final photoIndex = startPhotoIndex + frameIndex; rowChildren.add( Expanded( flex: (frame.width * 100).toInt(), child: Container( padding: const EdgeInsets.all(4), height: frame.height * _photoBlockHeight, child: PhotoItem( photo: allPhotos[photoIndex], color: photoColor, selected: photoIndex == _selectedPhotoIndex, onTap: () { _selectPhoto(photoIndex); }, ), ), ), ); } rows.add(Row( crossAxisAlignment: CrossAxisAlignment.center, children: rowChildren, )); startPhotoIndex += rowLength; } return Column(children: rows); } @override Widget build(BuildContext context) { timeDilation = 20.0; // 1.0 is normal animation speed. // Number of PhotoBlockFrames in each _photoBlockHeight block final int photoBlockFrameCount = photoBlockFrames.map((l) => l.length).reduce((s, n) => s + n); return Scaffold( appBar: AppBar( title: const Text('Images Demo'), actions: [ IconButton( icon: const Icon(Icons.delete), onPressed: _removeSelectedPhoto, ), ], ), body: SizedBox.expand( child: ListView.builder( padding: const EdgeInsets.all(4), itemExtent: _photoBlockHeight, itemCount: (allPhotos.length / photoBlockFrameCount).floor(), itemBuilder: (context, blockIndex) { return _buildPhotoBlock(context, blockIndex, photoBlockFrameCount); }, ), ), ); } } void main() { runApp( const MaterialApp( home: ImagesDemo(), ), ); }
website/examples/_animation/staggered_pic_selection/lib/main.dart/0
{'file_path': 'website/examples/_animation/staggered_pic_selection/lib/main.dart', 'repo_id': 'website', 'token_count': 5015}
name: null_safety_basics description: Some code to demonstrate null safety. version: 1.0.0 environment: sdk: ^3.2.0 dependencies: flutter: sdk: flutter dev_dependencies: example_utils: path: ../example_utils flutter_test: sdk: flutter flutter: uses-material-design: true
website/examples/basics/pubspec.yaml/0
{'file_path': 'website/examples/basics/pubspec.yaml', 'repo_id': 'website', 'token_count': 115}
import 'package:flutter/material.dart'; void main() { runApp(const MaterialApp(home: PhysicsCardDragDemo())); } class PhysicsCardDragDemo extends StatelessWidget { const PhysicsCardDragDemo({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: const DraggableCard( child: FlutterLogo( size: 128, ), ), ); } } class DraggableCard extends StatefulWidget { const DraggableCard({required this.child, super.key}); final Widget child; @override State<DraggableCard> createState() => _DraggableCardState(); } class _DraggableCardState extends State<DraggableCard> { @override void initState() { super.initState(); } @override void dispose() { super.dispose(); } @override Widget build(BuildContext context) { return Align( child: Card( child: widget.child, ), ); } }
website/examples/cookbook/animation/physics_simulation/lib/starter.dart/0
{'file_path': 'website/examples/cookbook/animation/physics_simulation/lib/starter.dart', 'repo_id': 'website', 'token_count': 364}
name: orientation description: Sample code for orientation cookbook recipe. environment: sdk: ^3.2.0 dependencies: flutter: sdk: flutter dev_dependencies: example_utils: path: ../../../example_utils flutter: uses-material-design: true
website/examples/cookbook/design/orientation/pubspec.yaml/0
{'file_path': 'website/examples/cookbook/design/orientation/pubspec.yaml', 'repo_id': 'website', 'token_count': 89}
import 'dart:math' as math; import 'package:flutter/material.dart'; @immutable class ExampleExpandableFab extends StatelessWidget { static const _actionTitles = ['Create Post', 'Upload Photo', 'Upload Video']; const ExampleExpandableFab({super.key}); void _showAction(BuildContext context, int index) { showDialog<void>( context: context, builder: (context) { return AlertDialog( content: Text(_actionTitles[index]), actions: [ TextButton( onPressed: () => Navigator.of(context).pop(), child: const Text('CLOSE'), ), ], ); }, ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Expandable Fab'), ), body: ListView.builder( padding: const EdgeInsets.symmetric(vertical: 8), itemCount: 25, itemBuilder: (context, index) { return FakeItem(isBig: index.isOdd); }, ), floatingActionButton: ExpandableFab( distance: 112, children: [ ActionButton( onPressed: () => _showAction(context, 0), icon: const Icon(Icons.format_size), ), ActionButton( onPressed: () => _showAction(context, 1), icon: const Icon(Icons.insert_photo), ), ActionButton( onPressed: () => _showAction(context, 2), icon: const Icon(Icons.videocam), ), ], ), ); } } @immutable class ExpandableFab extends StatefulWidget { const ExpandableFab({ super.key, this.initialOpen, required this.distance, required this.children, }); final bool? initialOpen; final double distance; final List<Widget> children; @override State<ExpandableFab> createState() => _ExpandableFabState(); } // #docregion ExpandableFabState3 class _ExpandableFabState extends State<ExpandableFab> with SingleTickerProviderStateMixin { late final AnimationController _controller; late final Animation<double> _expandAnimation; bool _open = false; @override void initState() { super.initState(); _open = widget.initialOpen ?? false; _controller = AnimationController( value: _open ? 1.0 : 0.0, duration: const Duration(milliseconds: 250), vsync: this, ); _expandAnimation = CurvedAnimation( curve: Curves.fastOutSlowIn, reverseCurve: Curves.easeOutQuad, parent: _controller, ); } @override void dispose() { _controller.dispose(); super.dispose(); } void _toggle() { setState(() { _open = !_open; if (_open) { _controller.forward(); } else { _controller.reverse(); } }); } // code-excerpt-closing-bracket // #enddocregion ExpandableFabState3 @override Widget build(BuildContext context) { return SizedBox.expand( child: Stack( alignment: Alignment.bottomRight, clipBehavior: Clip.none, children: [ _buildTapToCloseFab(), ..._buildExpandingActionButtons(), _buildTapToOpenFab(), ], ), ); } Widget _buildTapToCloseFab() { return SizedBox( width: 56, height: 56, child: Center( child: Material( shape: const CircleBorder(), clipBehavior: Clip.antiAlias, elevation: 4, child: InkWell( onTap: _toggle, child: Padding( padding: const EdgeInsets.all(8), child: Icon( Icons.close, color: Theme.of(context).primaryColor, ), ), ), ), ), ); } List<Widget> _buildExpandingActionButtons() { final children = <Widget>[]; final count = widget.children.length; final step = 90.0 / (count - 1); for (var i = 0, angleInDegrees = 0.0; i < count; i++, angleInDegrees += step) { children.add( _ExpandingActionButton( directionInDegrees: angleInDegrees, maxDistance: widget.distance, progress: _expandAnimation, child: widget.children[i], ), ); } return children; } Widget _buildTapToOpenFab() { return IgnorePointer( ignoring: _open, child: AnimatedContainer( transformAlignment: Alignment.center, transform: Matrix4.diagonal3Values( _open ? 0.7 : 1.0, _open ? 0.7 : 1.0, 1.0, ), duration: const Duration(milliseconds: 250), curve: const Interval(0.0, 0.5, curve: Curves.easeOut), child: AnimatedOpacity( opacity: _open ? 0.0 : 1.0, curve: const Interval(0.25, 1.0, curve: Curves.easeInOut), duration: const Duration(milliseconds: 250), child: FloatingActionButton( onPressed: _toggle, child: const Icon(Icons.create), ), ), ), ); } } // #docregion ExpandingActionButton @immutable class _ExpandingActionButton extends StatelessWidget { const _ExpandingActionButton({ required this.directionInDegrees, required this.maxDistance, required this.progress, required this.child, }); final double directionInDegrees; final double maxDistance; final Animation<double> progress; final Widget child; @override Widget build(BuildContext context) { return AnimatedBuilder( animation: progress, builder: (context, child) { final offset = Offset.fromDirection( directionInDegrees * (math.pi / 180.0), progress.value * maxDistance, ); return Positioned( right: 4.0 + offset.dx, bottom: 4.0 + offset.dy, child: Transform.rotate( angle: (1.0 - progress.value) * math.pi / 2, child: child!, ), ); }, child: FadeTransition( opacity: progress, child: child, ), ); } } // #enddocregion ExpandingActionButton @immutable class ActionButton extends StatelessWidget { const ActionButton({ super.key, this.onPressed, required this.icon, }); final VoidCallback? onPressed; final Widget icon; @override Widget build(BuildContext context) { final theme = Theme.of(context); return Material( shape: const CircleBorder(), clipBehavior: Clip.antiAlias, color: theme.colorScheme.secondary, elevation: 4.0, child: IconTheme.merge( data: IconThemeData(color: theme.colorScheme.onSecondary), child: IconButton( onPressed: onPressed, icon: icon, ), ), ); } } @immutable class FakeItem extends StatelessWidget { const FakeItem({ super.key, required this.isBig, }); final bool isBig; @override Widget build(BuildContext context) { return Container( margin: const EdgeInsets.symmetric(vertical: 8, horizontal: 24), height: isBig ? 128 : 36, decoration: BoxDecoration( borderRadius: const BorderRadius.all(Radius.circular(8)), color: Colors.grey.shade300, ), ); } }
website/examples/cookbook/effects/expandable_fab/lib/excerpt3.dart/0
{'file_path': 'website/examples/cookbook/effects/expandable_fab/lib/excerpt3.dart', 'repo_id': 'website', 'token_count': 3205}
import 'package:flutter/material.dart'; // #docregion SetupFlow class SetupFlow extends StatefulWidget { const SetupFlow({ super.key, required this.setupPageRoute, }); final String setupPageRoute; @override State<SetupFlow> createState() => SetupFlowState(); } class SetupFlowState extends State<SetupFlow> { @override Widget build(BuildContext context) { return const SizedBox(); } } // #enddocregion SetupFlow
website/examples/cookbook/effects/nested_nav/lib/setupflow.dart/0
{'file_path': 'website/examples/cookbook/effects/nested_nav/lib/setupflow.dart', 'repo_id': 'website', 'token_count': 140}
import 'package:flutter/material.dart'; @immutable class FilterSelector extends StatefulWidget { const FilterSelector({ super.key, required this.filters, required this.onFilterChanged, this.padding = const EdgeInsets.symmetric(vertical: 24), }); final List<Color> filters; final void Function(Color selectedColor) onFilterChanged; final EdgeInsets padding; @override State<FilterSelector> createState() => _FilterSelectorState(); } // #docregion PageViewController class _FilterSelectorState extends State<FilterSelector> { static const _filtersPerScreen = 5; static const _viewportFractionPerItem = 1.0 / _filtersPerScreen; late final PageController _controller; Color itemColor(int index) => widget.filters[index % widget.filters.length]; @override void initState() { super.initState(); _controller = PageController( viewportFraction: _viewportFractionPerItem, ); _controller.addListener(_onPageChanged); } void _onPageChanged() { final page = (_controller.page ?? 0).round(); widget.onFilterChanged(widget.filters[page]); } @override void dispose() { _controller.dispose(); super.dispose(); } Widget _buildCarousel(double itemSize) { return Container( height: itemSize, margin: widget.padding, child: PageView.builder( controller: _controller, itemCount: widget.filters.length, itemBuilder: (context, index) { return Center( child: FilterItem( color: itemColor(index), onFilterSelected: () {}, ), ); }, ), ); } //code-excerpt-close-bracket // #enddocregion PageViewController @override Widget build(BuildContext context) { _buildCarousel(5); // Makes sure _buildCarousel is used return Container(); } } @immutable class FilterItem extends StatelessWidget { const FilterItem({ super.key, required this.color, this.onFilterSelected, }); final Color color; final VoidCallback? onFilterSelected; @override Widget build(BuildContext context) { return GestureDetector( onTap: onFilterSelected, child: AspectRatio( aspectRatio: 1.0, child: Padding( padding: const EdgeInsets.all(8), child: ClipOval( child: Image.network( 'https://docs.flutter.dev/cookbook/img-files' '/effects/instagram-buttons/millennial-texture.jpg', color: color.withOpacity(0.5), colorBlendMode: BlendMode.hardLight, ), ), ), ), ); } }
website/examples/cookbook/effects/photo_filter_carousel/lib/excerpt5.dart/0
{'file_path': 'website/examples/cookbook/effects/photo_filter_carousel/lib/excerpt5.dart', 'repo_id': 'website', 'token_count': 1047}
import 'package:flutter/material.dart'; class Menu extends StatefulWidget { const Menu({super.key}); @override State<Menu> createState() => _MenuState(); } // #docregion AnimationController class _MenuState extends State<Menu> with SingleTickerProviderStateMixin { late AnimationController _staggeredController; @override void initState() { super.initState(); _staggeredController = AnimationController( vsync: this, ); } @override void dispose() { _staggeredController.dispose(); super.dispose(); } // #enddocregion AnimationController @override Widget build(BuildContext context) { return Container(); } }
website/examples/cookbook/effects/staggered_menu_animation/lib/step2.dart/0
{'file_path': 'website/examples/cookbook/effects/staggered_menu_animation/lib/step2.dart', 'repo_id': 'website', 'token_count': 216}
import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { const appTitle = 'Form Validation Demo'; return MaterialApp( title: appTitle, home: Scaffold( appBar: AppBar( title: const Text(appTitle), ), body: const MyCustomForm(), ), ); } } // Create a Form widget. class MyCustomForm extends StatefulWidget { const MyCustomForm({super.key}); @override MyCustomFormState createState() { return MyCustomFormState(); } } // Create a corresponding State class. // This class holds data related to the form. class MyCustomFormState extends State<MyCustomForm> { // Create a global key that uniquely identifies the Form widget // and allows validation of the form. // // Note: This is a GlobalKey<FormState>, // not a GlobalKey<MyCustomFormState>. final _formKey = GlobalKey<FormState>(); @override Widget build(BuildContext context) { // Build a Form widget using the _formKey created above. return Form( key: _formKey, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // #docregion TextFormField TextFormField( // The validator receives the text that the user has entered. validator: (value) { if (value == null || value.isEmpty) { return 'Please enter some text'; } return null; }, ), // #enddocregion TextFormField Padding( padding: const EdgeInsets.symmetric(vertical: 16), // #docregion ElevatedButton child: ElevatedButton( onPressed: () { // Validate returns true if the form is valid, or false otherwise. if (_formKey.currentState!.validate()) { // If the form is valid, display a snackbar. In the real world, // you'd often call a server or save the information in a database. ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('Processing Data')), ); } }, child: const Text('Submit'), ), // #enddocregion ElevatedButton ), ], ), ); } }
website/examples/cookbook/forms/validation/lib/main.dart/0
{'file_path': 'website/examples/cookbook/forms/validation/lib/main.dart', 'repo_id': 'website', 'token_count': 1067}
import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { const title = 'Fade in images'; return MaterialApp( title: title, home: Scaffold( appBar: AppBar( title: const Text(title), ), body: Center( // #docregion AssetNetwork child: FadeInImage.assetNetwork( placeholder: 'assets/loading.gif', image: 'https://picsum.photos/250?image=9', ), // #enddocregion AssetNetwork ), ), ); } }
website/examples/cookbook/images/fading_in_images/lib/asset_main.dart/0
{'file_path': 'website/examples/cookbook/images/fading_in_images/lib/asset_main.dart', 'repo_id': 'website', 'token_count': 302}
import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { const title = 'Grid List'; return MaterialApp( title: title, home: Scaffold( appBar: AppBar( title: const Text(title), ), // #docregion GridView body: GridView.count( // Create a grid with 2 columns. If you change the scrollDirection to // horizontal, this produces 2 rows. crossAxisCount: 2, // Generate 100 widgets that display their index in the List. children: List.generate(100, (index) { return Center( child: Text( 'Item $index', style: Theme.of(context).textTheme.headlineSmall, ), ); }), ), // #enddocregion GridView ), ); } }
website/examples/cookbook/lists/grid_lists/lib/main.dart/0
{'file_path': 'website/examples/cookbook/lists/grid_lists/lib/main.dart', 'repo_id': 'website', 'token_count': 449}
// #docregion InitializeSDK import 'package:flutter/widgets.dart'; import 'package:sentry_flutter/sentry_flutter.dart'; Future<void> main() async { await SentryFlutter.init( (options) => options.dsn = 'https://example@sentry.io/example', appRunner: () => runApp(const MyApp()), ); } // #enddocregion InitializeSDK Future<void> captureErrors() async { try { // Do something } catch (exception, stackTrace) { // #docregion CaptureException await Sentry.captureException(exception, stackTrace: stackTrace); // #enddocregion CaptureException } } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return Container(); } }
website/examples/cookbook/maintenance/error_reporting/lib/main.dart/0
{'file_path': 'website/examples/cookbook/maintenance/error_reporting/lib/main.dart', 'repo_id': 'website', 'token_count': 253}
import 'package:flutter/material.dart'; // #docregion FirstSecondRoutes class FirstRoute extends StatelessWidget { const FirstRoute({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('First Route'), ), body: Center( child: ElevatedButton( child: const Text('Open route'), onPressed: () { // Navigate to second route when tapped. }, ), ), ); } } class SecondRoute extends StatelessWidget { const SecondRoute({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Second Route'), ), body: Center( child: ElevatedButton( onPressed: () { // Navigate back to first route when tapped. }, child: const Text('Go back!'), ), ), ); } }
website/examples/cookbook/navigation/navigation_basics/lib/main_step1.dart/0
{'file_path': 'website/examples/cookbook/navigation/navigation_basics/lib/main_step1.dart', 'repo_id': 'website', 'token_count': 417}
import 'dart:async'; import 'dart:convert'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; // #docregion fetchPhotos Future<List<Photo>> fetchPhotos(http.Client client) async { final response = await client .get(Uri.parse('https://jsonplaceholder.typicode.com/photos')); // Use the compute function to run parsePhotos in a separate isolate. return compute(parsePhotos, response.body); } // #enddocregion fetchPhotos // A function that converts a response body into a List<Photo>. List<Photo> parsePhotos(String responseBody) { final parsed = (jsonDecode(responseBody) as List).cast<Map<String, dynamic>>(); return parsed.map<Photo>((json) => Photo.fromJson(json)).toList(); } class Photo { final int albumId; final int id; final String title; final String url; final String thumbnailUrl; const Photo({ required this.albumId, required this.id, required this.title, required this.url, required this.thumbnailUrl, }); factory Photo.fromJson(Map<String, dynamic> json) { return Photo( albumId: json['albumId'] as int, id: json['id'] as int, title: json['title'] as String, url: json['url'] as String, thumbnailUrl: json['thumbnailUrl'] as String, ); } } void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { const appTitle = 'Isolate Demo'; return const MaterialApp( title: appTitle, home: MyHomePage(title: appTitle), ); } } class MyHomePage extends StatelessWidget { const MyHomePage({super.key, required this.title}); final String title; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(title), ), body: FutureBuilder<List<Photo>>( future: fetchPhotos(http.Client()), builder: (context, snapshot) { if (snapshot.hasError) { return const Center( child: Text('An error has occurred!'), ); } else if (snapshot.hasData) { return PhotosList(photos: snapshot.data!); } else { return const Center( child: CircularProgressIndicator(), ); } }, ), ); } } class PhotosList extends StatelessWidget { const PhotosList({super.key, required this.photos}); final List<Photo> photos; @override Widget build(BuildContext context) { return GridView.builder( gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( crossAxisCount: 2, ), itemCount: photos.length, itemBuilder: (context, index) { return Image.network(photos[index].thumbnailUrl); }, ); } }
website/examples/cookbook/networking/background_parsing/lib/main.dart/0
{'file_path': 'website/examples/cookbook/networking/background_parsing/lib/main.dart', 'repo_id': 'website', 'token_count': 1091}
name: reading_writing_files description: Reading and Writing Files environment: sdk: ^3.2.0 dependencies: flutter: sdk: flutter path_provider: ^2.0.15 dev_dependencies: example_utils: path: ../../../example_utils flutter_test: sdk: flutter flutter: uses-material-design: true
website/examples/cookbook/persistence/reading_writing_files/pubspec.yaml/0
{'file_path': 'website/examples/cookbook/persistence/reading_writing_files/pubspec.yaml', 'repo_id': 'website', 'token_count': 118}
class Counter { int value = 0; void increment() => value++; void decrement() => value--; }
website/examples/cookbook/testing/unit/counter_app/lib/counter.dart/0
{'file_path': 'website/examples/cookbook/testing/unit/counter_app/lib/counter.dart', 'repo_id': 'website', 'token_count': 31}
import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; // ignore_for_file: unused_local_variable // #docregion main void main() { testWidgets('MyWidget has a title and message', (tester) async { await tester.pumpWidget(const MyWidget(title: 'T', message: 'M')); // Create the Finders. final titleFinder = find.text('T'); final messageFinder = find.text('M'); }); } // #enddocregion main class MyWidget extends StatelessWidget { const MyWidget({ super.key, required this.title, required this.message, }); final String title; final String message; @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', home: Scaffold( appBar: AppBar( title: Text(title), ), body: Center( child: Text(message), ), ), ); } }
website/examples/cookbook/testing/widget/introduction/test/main_step5_test.dart/0
{'file_path': 'website/examples/cookbook/testing/widget/introduction/test/main_step5_test.dart', 'repo_id': 'website', 'token_count': 355}
import 'dart:isolate'; import 'package:flutter/services.dart'; import 'package:shared_preferences/shared_preferences.dart'; void main() { // Identify the root isolate to pass to the background isolate. RootIsolateToken rootIsolateToken = RootIsolateToken.instance!; Isolate.spawn(_isolateMain, rootIsolateToken); } Future<void> _isolateMain(RootIsolateToken rootIsolateToken) async { // Register the background isolate with the root isolate. BackgroundIsolateBinaryMessenger.ensureInitialized(rootIsolateToken); // You can now use the shared_preferences plugin. SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); print(sharedPreferences.getBool('isDebug')); }
website/examples/development/concurrency/isolates/lib/isolate_binary_messenger.dart/0
{'file_path': 'website/examples/development/concurrency/isolates/lib/isolate_binary_messenger.dart', 'repo_id': 'website', 'token_count': 204}
// ignore_for_file: avoid_print, prefer_const_declarations, prefer_const_constructors import 'package:flutter/material.dart'; // #docregion Main import 'package:flutter/widgets.dart'; void main() { runApp(const Center(child: Text('Hello', textDirection: TextDirection.ltr))); } // #enddocregion Main // #docregion Enum class Color { Color(this.i, this.j); final int i; final int j; } // #enddocregion Enum // #docregion Class class A<T, V> { T? i; V? v; } // #enddocregion Class // #docregion SampleTable final sampleTable = [ Table( children: const [ TableRow( children: [Text('T1')], ) ], ), Table( children: const [ TableRow( children: [Text('T2')], ) ], ), Table( children: const [ TableRow( children: [Text('T3')], ) ], ), Table( children: const [ TableRow( children: [Text('T10')], // modified ) ], ), ]; // #enddocregion SampleTable // #docregion Const const foo = 2; // modified // #docregion FinalFoo final bar = foo; // #enddocregion FinalFoo void onClick() { print(foo); print(bar); } // #enddocregion Const
website/examples/development/tools/lib/hot-reload/after.dart/0
{'file_path': 'website/examples/development/tools/lib/hot-reload/after.dart', 'repo_id': 'website', 'token_count': 487}
import 'package:flutter/material.dart'; class WelcomeScreen extends StatelessWidget { const WelcomeScreen({super.key}); @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Text( 'Welcome!', style: Theme.of(context).textTheme.displayMedium, ), ), ); } } void main() => runApp(const SignUpApp()); class SignUpApp extends StatelessWidget { const SignUpApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( routes: { '/': (context) => const SignUpScreen(), '/welcome': (context) => const WelcomeScreen(), }, ); } } class SignUpScreen extends StatelessWidget { const SignUpScreen({super.key}); @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.grey[200], body: const Center( child: SizedBox( width: 400, child: Card( child: SignUpForm(), ), ), ), ); } } class SignUpForm extends StatefulWidget { const SignUpForm({super.key}); @override State<SignUpForm> createState() => _SignUpFormState(); } class _SignUpFormState extends State<SignUpForm> { final _firstNameTextController = TextEditingController(); final _lastNameTextController = TextEditingController(); final _usernameTextController = TextEditingController(); double _formProgress = 0; void _showWelcomeScreen() { Navigator.of(context).pushNamed('/welcome'); } // #docregion updateFormProgress void _updateFormProgress() { var progress = 0.0; final controllers = [ _firstNameTextController, _lastNameTextController, _usernameTextController ]; // #docregion forLoop for (final controller in controllers) { if (controller.value.text.isNotEmpty) { progress += 1 / controllers.length; } } // #enddocregion forLoop setState(() { _formProgress = progress; }); } // #enddocregion updateFormProgress @override Widget build(BuildContext context) { // #docregion onChanged return Form( onChanged: _updateFormProgress, // NEW child: Column( // #enddocregion onChanged mainAxisSize: MainAxisSize.min, children: [ LinearProgressIndicator(value: _formProgress), Text('Sign up', style: Theme.of(context).textTheme.headlineMedium), Padding( padding: const EdgeInsets.all(8), child: TextFormField( controller: _firstNameTextController, decoration: const InputDecoration(hintText: 'First name'), ), ), Padding( padding: const EdgeInsets.all(8), child: TextFormField( controller: _lastNameTextController, decoration: const InputDecoration(hintText: 'Last name'), ), ), Padding( padding: const EdgeInsets.all(8), child: TextFormField( controller: _usernameTextController, decoration: const InputDecoration(hintText: 'Username'), ), ), // #docregion onPressed TextButton( style: ButtonStyle( foregroundColor: MaterialStateProperty.resolveWith((states) { return states.contains(MaterialState.disabled) ? null : Colors.white; }), backgroundColor: MaterialStateProperty.resolveWith((states) { return states.contains(MaterialState.disabled) ? null : Colors.blue; }), ), onPressed: // #docregion ternary _formProgress == 1 ? _showWelcomeScreen : null, // UPDATED // #enddocregion ternary child: const Text('Sign up'), ), // #enddocregion onPressed ], ), ); } }
website/examples/get-started/codelab_web/lib/step2.dart/0
{'file_path': 'website/examples/get-started/codelab_web/lib/step2.dart', 'repo_id': 'website', 'token_count': 1782}
import 'dart:developer' as developer; import 'package:flutter/material.dart'; void main() { runApp(const SampleApp()); } class SampleApp extends StatelessWidget { const SampleApp({super.key}); // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'Sample App', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), ), home: const SampleAppPage(), ); } } class SampleAppPage extends StatefulWidget { const SampleAppPage({super.key}); @override State<SampleAppPage> createState() => _SampleAppPageState(); } class _SampleAppPageState extends State<SampleAppPage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Sample App'), ), body: ListView(children: _getListData()), ); } List<Widget> _getListData() { List<Widget> widgets = []; for (int i = 0; i < 100; i++) { widgets.add( GestureDetector( onTap: () { developer.log('row tapped'); }, child: Padding( padding: const EdgeInsets.all(10), child: Text('Row $i'), ), ), ); } return widgets; } }
website/examples/get-started/flutter-for/android_devs/lib/list_item_tapped.dart/0
{'file_path': 'website/examples/get-started/flutter-for/android_devs/lib/list_item_tapped.dart', 'repo_id': 'website', 'token_count': 542}
import 'dart:async'; import 'dart:convert'; import 'dart:isolate'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; void main() { runApp(const SampleApp()); } class SampleApp extends StatelessWidget { const SampleApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( title: 'Sample App', home: SampleAppPage(), ); } } class SampleAppPage extends StatefulWidget { const SampleAppPage({super.key}); @override State<SampleAppPage> createState() => _SampleAppPageState(); } class _SampleAppPageState extends State<SampleAppPage> { List<Map<String, dynamic>> data = <Map<String, dynamic>>[]; @override void initState() { super.initState(); loadData(); } bool get showLoadingDialog => data.isEmpty; // #docregion loadData Future<void> loadData() async { final ReceivePort receivePort = ReceivePort(); await Isolate.spawn(dataLoader, receivePort.sendPort); // The 'echo' isolate sends its SendPort as the first message. final SendPort sendPort = await receivePort.first as SendPort; final List<Map<String, dynamic>> msg = await sendReceive( sendPort, 'https://jsonplaceholder.typicode.com/posts', ); setState(() { data = msg; }); } // The entry point for the isolate. static Future<void> dataLoader(SendPort sendPort) async { // Open the ReceivePort for incoming messages. final ReceivePort port = ReceivePort(); // Notify any other isolates what port this isolate listens to. sendPort.send(port.sendPort); await for (final dynamic msg in port) { final String url = msg[0] as String; final SendPort replyTo = msg[1] as SendPort; final Uri dataURL = Uri.parse(url); final http.Response response = await http.get(dataURL); // Lots of JSON to parse replyTo.send(jsonDecode(response.body) as List<Map<String, dynamic>>); } } Future<List<Map<String, dynamic>>> sendReceive(SendPort port, String msg) { final ReceivePort response = ReceivePort(); port.send(<dynamic>[msg, response.sendPort]); return response.first as Future<List<Map<String, dynamic>>>; } // #enddocregion loadData Widget getBody() { bool showLoadingDialog = data.isEmpty; if (showLoadingDialog) { return getProgressDialog(); } else { return getListView(); } } Widget getProgressDialog() { return const Center(child: CircularProgressIndicator()); } ListView getListView() { return ListView.builder( itemCount: data.length, itemBuilder: (context, position) { return getRow(position); }, ); } Widget getRow(int i) { return Padding( padding: const EdgeInsets.all(10), child: Text("Row ${data[i]["title"]}"), ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Sample App'), ), body: getBody(), ); } }
website/examples/get-started/flutter-for/ios_devs/lib/isolates.dart/0
{'file_path': 'website/examples/get-started/flutter-for/ios_devs/lib/isolates.dart', 'repo_id': 'website', 'token_count': 1086}
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; void main() { runApp( const MaterialApp( home: Scaffold( body: Center( child: ElevatedButton( onPressed: _incrementCounter, child: Text('Increment Counter'), ), ), ), ), ); } Future<void> _incrementCounter() async { SharedPreferences prefs = await SharedPreferences.getInstance(); int counter = (prefs.getInt('counter') ?? 0) + 1; await prefs.setInt('counter', counter); }
website/examples/get-started/flutter-for/ios_devs/lib/shared_prefs.dart/0
{'file_path': 'website/examples/get-started/flutter-for/ios_devs/lib/shared_prefs.dart', 'repo_id': 'website', 'token_count': 244}
// ignore_for_file: avoid_print import 'dart:convert'; // #docregion ImportDartIO import 'dart:io'; // #enddocregion ImportDartIO // #docregion PackageImport import 'package:flutter/material.dart'; // #enddocregion PackageImport // #docregion SharedPrefs import 'package:shared_preferences/shared_preferences.dart'; // #enddocregion SharedPrefs // #docregion Main // Dart void main() { print('Hello, this is the main function.'); } // #enddocregion Main class MyWidget extends StatelessWidget { const MyWidget({super.key}); @override Widget build(BuildContext context) { // #docregion ImageAsset return Image.asset('assets/background.png'); // #enddocregion ImageAsset } } class NetworkImage extends StatelessWidget { const NetworkImage({super.key}); @override Widget build(BuildContext context) { // #docregion ImageNetwork return Image.network('https://docs.flutter.dev/assets/images/docs/owl.jpg'); // #enddocregion ImageNetwork } } class ListViewExample extends StatelessWidget { const ListViewExample({super.key}); @override Widget build(BuildContext context) { // #docregion ListView var data = [ 'Hello', 'World', ]; return ListView.builder( itemCount: data.length, itemBuilder: (context, index) { return Text(data[index]); }, ); // #enddocregion ListView } } // #docregion CustomPaint class MyCanvasPainter extends CustomPainter { const MyCanvasPainter(); @override void paint(Canvas canvas, Size size) { final Paint paint = Paint()..color = Colors.amber; canvas.drawCircle(const Offset(100, 200), 40, paint); final Paint paintRect = Paint()..color = Colors.lightBlue; final Rect rect = Rect.fromPoints( const Offset(150, 300), const Offset(300, 400), ); canvas.drawRect(rect, paintRect); } @override bool shouldRepaint(MyCanvasPainter oldDelegate) => false; } class MyCanvasWidget extends StatelessWidget { const MyCanvasWidget({super.key}); @override Widget build(BuildContext context) { return const Scaffold( body: CustomPaint(painter: MyCanvasPainter()), ); } } // #enddocregion CustomPaint class TextStyleExample extends StatelessWidget { const TextStyleExample({super.key}); @override Widget build(BuildContext context) { // #docregion TextStyle const TextStyle textStyle = TextStyle( color: Colors.cyan, fontSize: 32, fontWeight: FontWeight.w600, ); return const Center( child: Column( children: <Widget>[ Text('Sample text', style: textStyle), Padding( padding: EdgeInsets.all(20), child: Icon( Icons.lightbulb_outline, size: 48, color: Colors.redAccent, ), ), ], ), ); // #enddocregion TextStyle } } class IconExample extends StatelessWidget { const IconExample({super.key}); @override Widget build(BuildContext context) { // #docregion Icon return const Icon(Icons.lightbulb_outline, color: Colors.redAccent); // #enddocregion Icon } } // #docregion Swatch class SampleApp extends StatelessWidget { const SampleApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Sample App', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), textSelectionTheme: const TextSelectionThemeData(selectionColor: Colors.red)), home: const SampleAppPage(), ); } } // #enddocregion Swatch class ThemeExample extends StatelessWidget { const ThemeExample({super.key}); // #docregion Theme @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData( primaryColor: Colors.cyan, brightness: Brightness.dark, ), home: const StylingPage(), ); } // #enddocregion Theme } class StylingPage extends StatelessWidget { const StylingPage({super.key}); @override Widget build(BuildContext context) { return const Text('Hello World!'); } } class SampleAppPage extends StatelessWidget { const SampleAppPage({super.key}); @override Widget build(BuildContext context) { return const Text('Hello World!'); } } class ThemeDataExample extends StatelessWidget { const ThemeDataExample({super.key, required this.brightness}); final Brightness brightness; // #docregion ThemeData @override Widget build(BuildContext context) { return Theme( data: ThemeData( primaryColor: Colors.cyan, brightness: brightness, ), child: Scaffold( backgroundColor: Theme.of(context).primaryColor, //... ), ); } // #enddocregion ThemeData } class SharedPrefsExample extends StatefulWidget { const SharedPrefsExample({super.key}); @override State<SharedPrefsExample> createState() => _SharedPrefsExampleState(); } class _SharedPrefsExampleState extends State<SharedPrefsExample> { int? _counter; // #docregion SharedPrefsUpdate Future<void> updateCounter() async { final prefs = await SharedPreferences.getInstance(); int? counter = prefs.getInt('counter'); if (counter is int) { await prefs.setInt('counter', ++counter); } setState(() { _counter = counter; }); } // #enddocregion SharedPrefsUpdate @override Widget build(BuildContext context) { return Text(_counter.toString()); } } class DrawerExample extends StatelessWidget { const DrawerExample({super.key}); // #docregion Drawer @override Widget build(BuildContext context) { return Drawer( elevation: 20, child: ListTile( leading: const Icon(Icons.change_history), title: const Text('Screen2'), onTap: () { Navigator.of(context).pushNamed('/b'); }, ), ); } // #enddocregion Drawer } class ScaffoldExample extends StatelessWidget { const ScaffoldExample({super.key}); // #docregion Scaffold @override Widget build(BuildContext context) { return Scaffold( drawer: Drawer( elevation: 20, child: ListTile( leading: const Icon(Icons.change_history), title: const Text('Screen2'), onTap: () { Navigator.of(context).pushNamed('/b'); }, ), ), appBar: AppBar(title: const Text('Home')), body: Container(), ); } // #enddocregion Scaffold } class GestureDetectorExample extends StatelessWidget { const GestureDetectorExample({super.key}); // #docregion GestureDetector @override Widget build(BuildContext context) { return GestureDetector( child: Scaffold( appBar: AppBar(title: const Text('Gestures')), body: const Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text('Tap, Long Press, Swipe Horizontally or Vertically'), ], )), ), onTap: () { print('Tapped'); }, onLongPress: () { print('Long Pressed'); }, onVerticalDragEnd: (value) { print('Swiped Vertically'); }, onHorizontalDragEnd: (value) { print('Swiped Horizontally'); }, ); } // #enddocregion GestureDetector } class HttpExample extends StatefulWidget { const HttpExample({super.key}); @override State<HttpExample> createState() => _HttpExampleState(); } class _HttpExampleState extends State<HttpExample> { String _ipAddress = ''; // #docregion HTTP final url = Uri.parse('https://httpbin.org/ip'); final httpClient = HttpClient(); Future<void> getIPAddress() async { final request = await httpClient.getUrl(url); final response = await request.close(); final responseBody = await response.transform(utf8.decoder).join(); final ip = jsonDecode(responseBody)['origin'] as String; setState(() { _ipAddress = ip; }); } // #enddocregion HTTP @override Widget build(BuildContext context) { return Text(_ipAddress); } } class TextEditingExample extends StatefulWidget { const TextEditingExample({super.key}); @override State<TextEditingExample> createState() => _TextEditingExampleState(); } class _TextEditingExampleState extends State<TextEditingExample> { // #docregion TextEditingController final TextEditingController _controller = TextEditingController(); @override Widget build(BuildContext context) { return Column(children: [ TextField( controller: _controller, decoration: const InputDecoration( hintText: 'Type something', labelText: 'Text Field', ), ), ElevatedButton( child: const Text('Submit'), onPressed: () { showDialog( context: context, builder: (context) { return AlertDialog( title: const Text('Alert'), content: Text('You typed ${_controller.text}'), ); }); }, ), ]); } // #enddocregion TextEditingController } class FormExample extends StatefulWidget { const FormExample({super.key}); @override State<FormExample> createState() => _FormExampleState(); } class _FormExampleState extends State<FormExample> { final formKey = GlobalKey<FormState>(); String? _email = ''; final String _password = ''; // #docregion FormSubmit void _submit() { final form = formKey.currentState; if (form != null && form.validate()) { form.save(); showDialog( context: context, builder: (context) { return AlertDialog( title: const Text('Alert'), content: Text('Email: $_email, password: $_password')); }, ); } } // #enddocregion FormSubmit // #docregion FormState @override Widget build(BuildContext context) { return Form( key: formKey, child: Column( children: <Widget>[ TextFormField( validator: (value) { if (value != null && value.contains('@')) { return null; } return 'Not a valid email.'; }, onSaved: (val) { _email = val; }, decoration: const InputDecoration( hintText: 'Enter your email', labelText: 'Email', ), ), ElevatedButton( onPressed: _submit, child: const Text('Login'), ), ], ), ); } // #enddocregion FormState } class PlatformExample extends StatelessWidget { const PlatformExample({super.key}); String whichPlatform(BuildContext context) { // #docregion Platform final platform = Theme.of(context).platform; if (platform == TargetPlatform.iOS) { return 'iOS'; } if (platform == TargetPlatform.android) { return 'android'; } if (platform == TargetPlatform.fuchsia) { return 'fuchsia'; } return 'not recognized '; // #enddocregion Platform } @override Widget build(BuildContext context) { return Text(whichPlatform(context)); } } class DismissableWidgets extends StatefulWidget { const DismissableWidgets({super.key}); @override State<DismissableWidgets> createState() => _DismissableWidgetsState(); } class _DismissableWidgetsState extends State<DismissableWidgets> { final List<Card> cards = [ const Card( child: Text('Hello!'), ), const Card( child: Text('World!'), ) ]; @override Widget build(BuildContext context) { // #docregion Dismissable return Dismissible( key: Key(widget.key.toString()), onDismissed: (dismissDirection) { cards.removeLast(); }, child: Container( //... ), ); // #enddocregion Dismissable } }
website/examples/get-started/flutter-for/react_native_devs/lib/examples.dart/0
{'file_path': 'website/examples/get-started/flutter-for/react_native_devs/lib/examples.dart', 'repo_id': 'website', 'token_count': 4740}
import 'dart:async'; import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; void main() { runApp(const SampleApp()); } class SampleApp extends StatelessWidget { const SampleApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( title: 'Sample App', home: SampleAppPage(), ); } } class SampleAppPage extends StatefulWidget { const SampleAppPage({super.key}); @override State<SampleAppPage> createState() => _SampleAppPageState(); } class _SampleAppPageState extends State<SampleAppPage> { List<Map<String, dynamic>> data = <Map<String, dynamic>>[]; @override void initState() { super.initState(); loadData(); } bool get showLoadingDialog => data.isEmpty; Future<void> loadData() async { final Uri dataURL = Uri.parse( 'https://jsonplaceholder.typicode.com/posts', ); final http.Response response = await http.get(dataURL); setState(() { data = jsonDecode(response.body); }); } Widget getBody() { if (showLoadingDialog) { return getProgressDialog(); } return getListView(); } Widget getProgressDialog() { return const Center(child: CircularProgressIndicator()); } ListView getListView() { return ListView.builder( itemCount: data.length, itemBuilder: (context, index) { return getRow(index); }, ); } Widget getRow(int index) { return Padding( padding: const EdgeInsets.all(10), child: Text('Row ${data[index]['title']}'), ); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Sample App')), body: getBody(), ); } }
website/examples/get-started/flutter-for/xamarin_devs/lib/loading.dart/0
{'file_path': 'website/examples/get-started/flutter-for/xamarin_devs/lib/loading.dart', 'repo_id': 'website', 'token_count': 655}
// Copyright 2020 The Flutter team. 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'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), ), home: const MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { const MyHomePage({ super.key, required this.title, }); final String title; @override State<MyHomePage> createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { setState(() { _counter++; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const Text( 'You have pushed the button this many times:', ), Text( '$_counter', style: Theme.of(context).textTheme.headlineMedium, ), ], ), ), floatingActionButton: FloatingActionButton( // Provide a Key to this button. This allows finding this // specific button inside the test suite, and tapping it. key: const Key('increment'), onPressed: _incrementCounter, tooltip: 'Increment', child: const Icon(Icons.add), ), ); } }
website/examples/integration_test/lib/main.dart/0
{'file_path': 'website/examples/integration_test/lib/main.dart', 'repo_id': 'website', 'token_count': 746}
import 'package:flutter/material.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'nn_intl.dart'; void main() { runApp( // #docregion MaterialApp const MaterialApp( localizationsDelegates: [ GlobalWidgetsLocalizations.delegate, GlobalMaterialLocalizations.delegate, NnMaterialLocalizations.delegate, // Add the newly created delegate ], supportedLocales: [ Locale('en', 'US'), Locale('nn'), ], home: Home(), ), // #enddocregion MaterialApp ); } class Home extends StatelessWidget { const Home({super.key}); @override Widget build(BuildContext context) { return Localizations.override( context: context, locale: const Locale('nn'), child: Scaffold( appBar: AppBar(), drawer: Drawer( child: ListTile( leading: const Icon(Icons.change_history), title: const Text('Change history'), onTap: () { Navigator.pop(context); // close the drawer }, ), ), body: const Center( child: Padding( padding: EdgeInsets.all(50), child: Text( 'Long press hamburger icon in the app bar (aka the drawer menu)' 'to see a localized tooltip for the `nn` locale. '), ), ), ), ); } }
website/examples/internationalization/add_language/lib/main.dart/0
{'file_path': 'website/examples/internationalization/add_language/lib/main.dart', 'repo_id': 'website', 'token_count': 636}
// DO NOT EDIT. This is code generated via package:intl/generate_localized.dart // This is a library that provides messages for a en locale. All the // messages from the main program should be duplicated here with the same // function name. // Ignore issues from commonly used lints in this file. // ignore_for_file:unnecessary_brace_in_string_interps // ignore_for_file:prefer_single_quotes,comment_references, directives_ordering // ignore_for_file:annotate_overrides,prefer_generic_function_type_aliases // ignore_for_file:unused_import, file_names import 'package:intl/intl.dart'; import 'package:intl/message_lookup_by_library.dart'; final messages = MessageLookup(); typedef String? MessageIfAbsent(String? messageStr, List<Object>? args); class MessageLookup extends MessageLookupByLibrary { @override String get localeName => 'en'; @override final Map<String, dynamic> messages = _notInlinedMessages(_notInlinedMessages); static Map<String, dynamic> _notInlinedMessages(_) => {'title': MessageLookupByLibrary.simpleMessage('Hello World')}; }
website/examples/internationalization/intl_example/lib/l10n/messages_en.dart/0
{'file_path': 'website/examples/internationalization/intl_example/lib/l10n/messages_en.dart', 'repo_id': 'website', 'token_count': 333}
// Basic Flutter widget test. Learn more at https://docs.flutter.dev/testing. import 'package:flutter_test/flutter_test.dart'; import 'package:layout/main.dart'; void main() { testWidgets('Codelab smoke test', (tester) async { await tester.pumpWidget(const MyApp()); expect(find.text('Hello World'), findsOneWidget); }); }
website/examples/layout/base/test/widget_test.dart/0
{'file_path': 'website/examples/layout/base/test/widget_test.dart', 'repo_id': 'website', 'token_count': 116}
import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart' show debugPaintSizeEnabled; void main() { debugPaintSizeEnabled = false; // Set to true for visual layout runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter layout demo', home: Scaffold( appBar: AppBar( title: const Text('Flutter layout demo'), ), body: Center(child: _buildImageColumn()), ), ); } // #docregion column Widget _buildImageColumn() { return Container( decoration: const BoxDecoration( color: Colors.black26, ), child: Column( children: [ _buildImageRow(1), _buildImageRow(3), ], ), ); } // #enddocregion column // #docregion row Widget _buildDecoratedImage(int imageIndex) => Expanded( child: Container( decoration: BoxDecoration( border: Border.all(width: 10, color: Colors.black38), borderRadius: const BorderRadius.all(Radius.circular(8)), ), margin: const EdgeInsets.all(4), child: Image.asset('images/pic$imageIndex.jpg'), ), ); Widget _buildImageRow(int imageIndex) => Row( children: [ _buildDecoratedImage(imageIndex), _buildDecoratedImage(imageIndex + 1), ], ); // #enddocregion row }
website/examples/layout/container/lib/main.dart/0
{'file_path': 'website/examples/layout/container/lib/main.dart', 'repo_id': 'website', 'token_count': 645}
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'src/passing_callbacks.dart' as callbacks; import 'src/performance.dart' as performance; import 'src/provider.dart'; import 'src/set_state.dart' as set_state; // #docregion main void main() { runApp( ChangeNotifierProvider( create: (context) => CartModel(), child: const MyApp(), ), ); } // #enddocregion main Map<String, WidgetBuilder> _routes = { '/setstate': (context) => const set_state.HelperScaffoldWrapper(), '/provider': (context) => const MyHomepage(), '/callbacks': (context) => const callbacks.MyHomepage(), '/perf': (context) => const performance.MyHomepage(), }; // #docregion multi-provider-main void multiProviderMain() { runApp( MultiProvider( providers: [ ChangeNotifierProvider(create: (context) => CartModel()), Provider(create: (context) => SomeOtherClass()), ], child: const MyApp(), ), ); } // #enddocregion multi-provider-main class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter State Management Code Excerpts', routes: _routes, home: const Material( child: _Menu(), ), ); } } class SomeOtherClass {} class _Menu extends StatelessWidget { const _Menu(); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Simple state management'), ), body: Wrap( children: [ for (final name in _routes.keys) TextButton( onPressed: () => Navigator.pushNamed(context, name), child: Text(name), ) ], ), ); } }
website/examples/state_mgmt/simple/lib/main.dart/0
{'file_path': 'website/examples/state_mgmt/simple/lib/main.dart', 'repo_id': 'website', 'token_count': 719}
import 'package:flutter/material.dart'; void main() { runApp( const MaterialApp( home: AppHome(), ), ); } class AppHome extends StatelessWidget { const AppHome({super.key}); @override Widget build(BuildContext context) { return Material( child: Center( child: TextButton( onPressed: () { debugDumpApp(); }, child: const Text('Dump Widget Tree'), ), ), ); } }
website/examples/testing/code_debugging/lib/dump_app.dart/0
{'file_path': 'website/examples/testing/code_debugging/lib/dump_app.dart', 'repo_id': 'website', 'token_count': 210}
// ignore_for_file: directives_ordering import './backend.dart'; import 'package:flutter/services.dart'; // #docregion CatchError import 'package:flutter/material.dart'; import 'dart:ui'; void main() { MyBackend myBackend = MyBackend(); PlatformDispatcher.instance.onError = (error, stack) { myBackend.sendError(error, stack); return true; }; runApp(const MyApp()); } // #enddocregion CatchError // #docregion CustomError class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( builder: (context, widget) { Widget error = const Text('...rendering error...'); if (widget is Scaffold || widget is Navigator) { error = Scaffold(body: Center(child: error)); } ErrorWidget.builder = (errorDetails) => error; if (widget != null) return widget; throw StateError('widget is null'); }, ); } } // #enddocregion CustomError class MyButton extends StatelessWidget { const MyButton({super.key}); @override Widget build(BuildContext context) { // #docregion OnPressed return OutlinedButton( child: const Text('Click me!'), onPressed: () async { const channel = MethodChannel('crashy-custom-channel'); await channel.invokeMethod('blah'); }, ); // #enddocregion OnPressed } }
website/examples/testing/errors/lib/excerpts.dart/0
{'file_path': 'website/examples/testing/errors/lib/excerpts.dart', 'repo_id': 'website', 'token_count': 517}
import 'package:flutter/material.dart'; import '../global/device_type.dart'; class OkCancelDialog extends StatelessWidget { const OkCancelDialog({super.key, required this.message}); final String message; @override Widget build(BuildContext context) { return Dialog( child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 400), child: Padding( padding: const EdgeInsets.all(Insets.large), child: Column( mainAxisSize: MainAxisSize.min, children: [ Text(message), const SizedBox(height: Insets.large), _OkCancelButtons(), ], ), ), ), ); } } class _OkCancelButtons extends StatelessWidget { @override Widget build(BuildContext context) { // #docregion RowTextDirection TextDirection btnDirection = DeviceType.isWindows ? TextDirection.rtl : TextDirection.ltr; return Row( children: [ const Spacer(), Row( textDirection: btnDirection, children: [ DialogButton( label: 'Cancel', onPressed: () => Navigator.pop(context, false), ), DialogButton( label: 'Ok', onPressed: () => Navigator.pop(context, true), ), ], ), ], ); // #enddocregion RowTextDirection } } class DialogButton extends StatelessWidget { const DialogButton({ super.key, required this.onPressed, required this.label, }); final VoidCallback onPressed; final String label; @override Widget build(BuildContext context) { return TextButton( onPressed: onPressed, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), child: Text(label), ), ); } }
website/examples/ui/layout/adaptive_app_demos/lib/widgets/ok_cancel_dialog.dart/0
{'file_path': 'website/examples/ui/layout/adaptive_app_demos/lib/widgets/ok_cancel_dialog.dart', 'repo_id': 'website', 'token_count': 854}
import 'package:flutter/material.dart'; // #docregion Toggle void showOversizedImages() { debugInvertOversizedImages = true; } // #enddocregion Toggle // #docregion ResizedImage class ResizedImage extends StatelessWidget { const ResizedImage({super.key}); @override Widget build(BuildContext context) { return Image.asset( 'dash.png', cacheHeight: 213, cacheWidth: 392, ); } } // #enddocregion ResizedImage
website/examples/visual_debugging/lib/oversized_images.dart/0
{'file_path': 'website/examples/visual_debugging/lib/oversized_images.dart', 'repo_id': 'website', 'token_count': 158}
- group: 'China Flutter User Group' mirror: 'flutter-io.cn' urls: pubhosted: 'https://pub.flutter-io.cn' flutterstorage: 'https://storage.flutter-io.cn' issues: 'https://github.com/cfug/flutter.cn/issues/new/choose' group: https://github.com/cfug - group: 'Shanghai Jiao Tong University *nix User Group' mirror: 'mirror.sjtu.edu.cn' urls: pubhosted: 'https://mirror.sjtu.edu.cn/flutter-infra' flutterstorage: 'https://mirror.sjtu.edu.cn' issues: 'https://github.com/sjtug/mirror-requests' group: https://github.com/sjtug - group: 'Tsinghua University TUNA Association' mirror: 'mirrors.tuna.tsinghua.edu.cn' urls: pubhosted: 'https://mirrors.tuna.tsinghua.edu.cn/dart-pub' flutterstorage: 'https://mirrors.tuna.tsinghua.edu.cn/flutter' issues: 'https://github.com/tuna/issues' group: https://tuna.moe
website/src/_data/mirrors.yml/0
{'file_path': 'website/src/_data/mirrors.yml', 'repo_id': 'website', 'token_count': 366}
import 'dart:io'; import 'package:path/path.dart' as path; /// Ignore blocks with TODOs: /// /// ```html /// <!-- TODO(somebody): [Links here][are not rendered]. --> /// ``` final _htmlCommentPattern = RegExp(r'<!--.*?-->', dotAll: true); /// Ignore blocks with code: /// /// ```dart /// [[highlight]]flutter[[/highlight]] /// ``` final _codeBlockPattern = RegExp(r'<pre.*?</pre>', dotAll: true); /// Ignore PR titles that look like a link /// directly embedded in a paragraph /// and often found in release notes: /// /// ```html /// <p><a href="https://github.com/flutter/engine/pull/27070">27070</a> /// [web][felt] Fix stdout inheritance for sub-processes /// (cla: yes, waiting for tree to go green, platform-web, needs tests) /// </p> /// ``` final _pullRequestTitlePattern = RegExp( r'<p><a href="https://github.com/.*?/pull/\d+">\d+</a>.*?</p>', dotAll: true); /// Ignore PR titles that look like a link, /// directly embedded in a `<li>` /// and often found in release notes: /// /// ```html /// <li>[docs][FWW] DropdownButton, ScaffoldMessenger, and StatefulBuilder links /// by @craiglabenz in https://github.com/flutter/flutter/pull/100316</li> /// ``` final _pullRequestTitleInListItemPattern = RegExp(r'<li>.*? in.*?https://github.com/.*?/pull/.*?</li>', dotAll: true); /// All replacements to run on file content before finding invalid references. final _allReplacements = [ _htmlCommentPattern, _codeBlockPattern, _pullRequestTitlePattern, _pullRequestTitleInListItemPattern, ]; final _invalidLinkReferencePattern = RegExp(r'\[[^\[\]]+]\[[^\[\]]*]'); List<String> _findInContent(String content) { for (final replacement in _allReplacements) { content = content.replaceAll(replacement, ''); } // Use regex to find all links that displayed abnormally, // since a valid reference link should be an `<a>` tag after rendered: // // - `[flutter.dev][]` // - `[GitHub repo][repo]` // See also: // - https://github.github.com/gfm/#reference-link final invalidFound = _invalidLinkReferencePattern.allMatches(content); if (invalidFound.isEmpty) { return const []; } return invalidFound .map((e) => e[0]) .whereType<String>() .toList(growable: false); } /// Find all invalid link references /// within generated HTML files /// in the specified [directory]. Map<String, List<String>> findInvalidLinkReferences(String directory) { final invalidReferences = <String, List<String>>{}; for (final filePath in Directory(directory) .listSync(recursive: true) .map((f) => f.path) .where((p) => path.extension(p) == '.html')) { final content = File(filePath).readAsStringSync(); final results = _findInContent(content); if (results.isNotEmpty) { invalidReferences[path.relative(filePath, from: directory)] = results; } } return invalidReferences; } void main() { final filesToInvalidReferences = findInvalidLinkReferences('_site'); if (filesToInvalidReferences.isNotEmpty) { print('check_link_references: Invalid link references found!'); filesToInvalidReferences.forEach((sourceFile, invalidReferences) { print('\n$sourceFile:'); for (final invalidReference in invalidReferences) { print(invalidReference); } }); exit(1); } }
website/tool/dart_tools/bin/check_link_references.dart/0
{'file_path': 'website/tool/dart_tools/bin/check_link_references.dart', 'repo_id': 'website', 'token_count': 1129}
import 'package:widgetbook_example/models/meal.dart'; class MealRepository { List<Meal> loadMeals() { return [ Meal( title: 'Big double cheeseburger', imagePath: 'assets/burger.jpg', ingredients: [ 'marble beef', 'cheddar cheese', 'jalapeno pepper', 'pickled cucumber', 'letttuce', 'red onion', 'BBQ sauce', ], price: 8.5, weight: 320, ), Meal( title: 'Banana Pankakes', imagePath: 'assets/pancakes.jpg', ingredients: [ 'ripe bananas', 'chilli chocolate', 'brown sugar', 'blueberries', 'flour', ], price: 6.9, weight: 250, ), ]; } }
widgetbook/examples/widgetbook_example/lib/repositories/meal_repository.dart/0
{'file_path': 'widgetbook/examples/widgetbook_example/lib/repositories/meal_repository.dart', 'repo_id': 'widgetbook', 'token_count': 426}
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:widgetbook/src/knobs/knobs.dart'; /// The panel containing the knobs for a usecase class KnobsPanel extends StatelessWidget { const KnobsPanel({ Key? key, }) : super(key: key); @override Widget build(BuildContext context) { final knobs = context.watch<KnobsNotifier>().all(); if (knobs.isEmpty) { return const Center( child: Text( 'No knobs to display', style: TextStyle( fontSize: 30, ), ), ); } return SingleChildScrollView( physics: const ScrollPhysics(), child: ListView.separated( shrinkWrap: true, separatorBuilder: (context, index) { return Divider( thickness: 4, color: Theme.of(context).scaffoldBackgroundColor, ); }, physics: const NeverScrollableScrollPhysics(), itemCount: knobs.length, itemBuilder: (context, index) => Padding( padding: const EdgeInsets.all(12), child: knobs[index].build(), ), ), ); } }
widgetbook/packages/widgetbook/lib/src/knobs/knobs_panel.dart/0
{'file_path': 'widgetbook/packages/widgetbook/lib/src/knobs/knobs_panel.dart', 'repo_id': 'widgetbook', 'token_count': 512}
import 'package:widgetbook/src/models/organizers/organizer_helper/organizer_helper.dart'; import 'package:widgetbook/src/models/organizers/organizers.dart'; /// Helper to obtain all Stories in the navigation tree. class StoryHelper { static List<WidgetbookUseCase> getAllStoriesFromCategories( List<WidgetbookCategory> categories) { final widgets = WidgetHelper.getAllWidgetElementsFromCategories( categories, ); final stories = List<WidgetbookUseCase>.empty(growable: true); for (final widget in widgets) { stories.addAll(widget.useCases); } return stories; } }
widgetbook/packages/widgetbook/lib/src/models/organizers/organizer_helper/story_helper.dart/0
{'file_path': 'widgetbook/packages/widgetbook/lib/src/models/organizers/organizer_helper/story_helper.dart', 'repo_id': 'widgetbook', 'token_count': 203}
import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:widgetbook/src/models/models.dart'; part 'preview_state.freezed.dart'; @freezed class PreviewState with _$PreviewState { factory PreviewState({ required WidgetbookUseCase? selectedUseCase, }) = _PreviewState; factory PreviewState.unselected() { return PreviewState(selectedUseCase: null); } PreviewState._(); bool get isUseCaseSelected => selectedUseCase != null; }
widgetbook/packages/widgetbook/lib/src/navigation/preview_state.dart/0
{'file_path': 'widgetbook/packages/widgetbook/lib/src/navigation/preview_state.dart', 'repo_id': 'widgetbook', 'token_count': 147}
import 'dart:async'; import 'dart:collection'; import 'package:meta/meta.dart'; import 'package:widgetbook/src/models/model.dart'; import 'package:widgetbook/src/repositories/repository.dart'; class MemoryRepository<Item extends Model> extends Repository<Item> { MemoryRepository({Map<String, Item>? initialConfiguration}) : memory = initialConfiguration ?? HashMap(), _streamController = StreamController<List<Item>>.broadcast() { _streamController.onListen = _emitChangesToStream; } @internal final Map<String, Item> memory; final StreamController<List<Item>> _streamController; void _emitChangesToStream() { _streamController.add(memory.values.toList()); } String _addItemAndEmitChangesToStream(Item item) { final id = _addItem(item); _emitChangesToStream(); return id; } String _addItem(Item item) { memory.putIfAbsent(item.id, () => item); return item.id; } @override String addItem(Item item) { return _addItemAndEmitChangesToStream(item); } void _deleteItemAndEmitChangesToStream(Item item) { _deleteItem(item); _emitChangesToStream(); } void _deleteItem(Item item) { memory.remove(item.id); } @override void deleteItem(Item item) { _deleteItemAndEmitChangesToStream(item); } @override Stream<List<Item>> getStreamOfItems() { return _streamController.stream; } @override void setItem(Item item) { if (!memory.containsKey(item.id)) { _addItemAndEmitChangesToStream(item); } else { updateItem(item); } } @override void updateItem(Item item) { memory[item.id] = item; _emitChangesToStream(); } @override bool doesItemExist(String id) { return memory.containsKey(id); } @override Item getItem(String id) { return memory[id]!; } @override void deleteAll() { memory.clear(); _emitChangesToStream(); } @override void addAll(Iterable<Item> items) { final map = HashMap<String, Item>.fromIterable( items, key: (dynamic k) => k.id as String, value: (dynamic v) => v as Item, ); memory.addAll(map); _emitChangesToStream(); } @override Future<void> closeStream() { return _streamController.close(); } }
widgetbook/packages/widgetbook/lib/src/repositories/memory_repository.dart/0
{'file_path': 'widgetbook/packages/widgetbook/lib/src/repositories/memory_repository.dart', 'repo_id': 'widgetbook', 'token_count': 844}
import 'package:flutter/material.dart'; import 'package:widgetbook/src/state_change_notifier.dart'; import 'package:widgetbook/src/translate/translate_state.dart'; /// A provider handling [Offset] translation to a previewed device or /// collection. /// /// Allows the user to pan around and adjust the viewport in case the device is /// not in focus. class TranslateProvider extends StateChangeNotifier<TranslateState> { TranslateProvider({ TranslateState? state, }) : super( state: state ?? TranslateState(), ); /// Overrides the current [Offset] by the provided [offset]. void updateOffset(Offset offset) { state = TranslateState(offset: offset); } /// Updates the current [Offset] by the provided [offset]. void updateRelativeOffset(Offset offset) { state = state.copyWith( offset: state.offset + offset, ); } /// Resets the [Offset] to [Offset.zero] void resetOffset() { state = TranslateState(); } }
widgetbook/packages/widgetbook/lib/src/translate/translate_provider.dart/0
{'file_path': 'widgetbook/packages/widgetbook/lib/src/translate/translate_provider.dart', 'repo_id': 'widgetbook', 'token_count': 306}
import 'package:flutter/material.dart'; import 'package:widgetbook/src/models/organizers/organizer.dart'; import 'package:widgetbook/src/widgets/tiles/tile.dart'; import 'package:widgetbook/src/widgets/tiles/tile_spacer.dart'; class SpacedTile extends StatelessWidget { const SpacedTile({ Key? key, required this.organizer, required this.level, required this.iconData, required this.iconColor, this.onClicked, }) : super(key: key); final int level; final Organizer organizer; final IconData iconData; final Color iconColor; final VoidCallback? onClicked; @override Widget build(BuildContext context) { return Row( children: [ TileSpacer(level: level), Expanded( child: Tile( iconData: iconData, iconColor: iconColor, organizer: organizer, onClicked: onClicked, ), ), ], ); } }
widgetbook/packages/widgetbook/lib/src/widgets/tiles/spaced_tile.dart/0
{'file_path': 'widgetbook/packages/widgetbook/lib/src/widgets/tiles/spaced_tile.dart', 'repo_id': 'widgetbook', 'token_count': 384}
import 'package:flutter/material.dart'; import 'package:widgetbook/src/workbench/workbench_button.dart'; /// A [SelectionItem] represents on element in a collection. An element can be /// selected and will be displayed within the Workbench. /// /// Selected elements change color to indicate that the element is active. class SelectionItem<T> extends StatelessWidget { const SelectionItem({ Key? key, required this.name, required this.selectedItem, required this.item, required this.onPressed, }) : super(key: key); final String name; final T? selectedItem; final T item; final VoidCallback onPressed; bool get _areEqual => selectedItem == item; @override Widget build(BuildContext context) { return WorkbenchButton.text( onPressed: onPressed, color: _areEqual ? Theme.of(context).colorScheme.primary : Colors.transparent, child: Text( name, ), ); } }
widgetbook/packages/widgetbook/lib/src/workbench/selection_item.dart/0
{'file_path': 'widgetbook/packages/widgetbook/lib/src/workbench/selection_item.dart', 'repo_id': 'widgetbook', 'token_count': 328}
import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'widget_test_helper.dart'; extension ProviderTesterExtension on WidgetTester { Future<Provider> pumpBuilderAndReturnProvider<Provider>(Widget widget) async { await pumpWidgetWithMaterialApp(widget); final providerFinder = find.byType(Provider); expect(providerFinder, findsOneWidget); final provider = firstWidget(providerFinder) as Provider; return provider; } Future<T> invokeMethodAndReturnPumpedProvider<T>( VoidCallback method, ) async { method(); await pumpAndSettle(); return getProvider<T>(); } T getProvider<T>() { final providerFinder = find.byType(T); return firstWidget(providerFinder) as T; } }
widgetbook/packages/widgetbook/test/helper/provider_helper.dart/0
{'file_path': 'widgetbook/packages/widgetbook/test/helper/provider_helper.dart', 'repo_id': 'widgetbook', 'token_count': 257}