text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
// Copyright 2013 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:flutter/material.dart'; import 'package:flutter_markdown/flutter_markdown.dart'; import '../shared/markdown_demo_widget.dart'; import '../shared/markdown_extensions.dart'; // ignore_for_file: public_member_api_docs class DemoScreen extends StatelessWidget { const DemoScreen({super.key, required this.child}); static const String routeName = '/demoScreen'; final MarkdownDemoWidget? child; static const List<String> _tabLabels = <String>['Formatted', 'Raw', 'Notes']; @override Widget build(BuildContext context) { return DefaultTabController( length: 3, child: Scaffold( appBar: AppBar( title: Text(child!.title), bottom: TabBar( indicatorPadding: const EdgeInsets.only(bottom: 8), indicatorSize: TabBarIndicatorSize.label, tabs: <Widget>[ for (final String label in _tabLabels) Tab(text: label), ], ), ), body: TabBarView( children: <Widget>[ DemoFormattedView(child: child), DemoRawDataView(data: child!.data), DemoNotesView(notes: child!.notes), //child.notes as String), ], ), ), ); } } class DemoFormattedView extends StatelessWidget { const DemoFormattedView({super.key, required this.child}); final Widget? child; @override Widget build(BuildContext context) { return Container( alignment: Alignment.center, child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 1250), child: child, ), ); } } class DemoRawDataView extends StatelessWidget { const DemoRawDataView({super.key, required this.data}); final Future<String> data; @override Widget build(BuildContext context) { return FutureBuilder<String>( future: data, builder: (BuildContext context, AsyncSnapshot<String> snapshot) { if (snapshot.connectionState == ConnectionState.done) { return SingleChildScrollView( child: Container( padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), child: Text( snapshot.data!, softWrap: true, style: Theme.of(context) .primaryTextTheme .bodyLarge! .copyWith(fontFamily: 'Roboto Mono', color: Colors.black), ), ), ); } else { return const CircularProgressIndicator(); } }, ); } } class DemoNotesView extends StatelessWidget { const DemoNotesView({super.key, required this.notes}); final Future<String> notes; // Handle the link. The [href] in the callback contains information // from the link. The url_launcher package or other similar package // can be used to execute the link. Future<void> linkOnTapHandler( BuildContext context, String text, String? href, String title, ) async { await showDialog<Widget>( context: context, builder: (BuildContext context) => _createDialog(context, text, href, title), ); } Widget _createDialog( BuildContext context, String text, String? href, String title, ) => AlertDialog( title: const Text('Reference Link'), content: SingleChildScrollView( child: ListBody( children: <Widget>[ Text( 'See the following link for more information:', style: Theme.of(context).textTheme.bodyLarge, ), const SizedBox(height: 8), Text( 'Link text: $text', style: Theme.of(context).textTheme.bodyMedium, ), const SizedBox(height: 8), Text( 'Link destination: $href', style: Theme.of(context).textTheme.bodyMedium, ), const SizedBox(height: 8), Text( 'Link title: $title', style: Theme.of(context).textTheme.bodyMedium, ), ], ), ), actions: <Widget>[ TextButton( onPressed: () => Navigator.of(context).pop(), child: const Text('OK'), ) ], ); @override Widget build(BuildContext context) { return FutureBuilder<String>( future: notes, builder: (BuildContext context, AsyncSnapshot<String> snapshot) { if (snapshot.connectionState == ConnectionState.done) { return Markdown( data: snapshot.data!, extensionSet: MarkdownExtensionSet.githubFlavored.value, onTapLink: (String text, String? href, String title) => linkOnTapHandler(context, text, href, title), ); } else { return const CircularProgressIndicator(); } }, ); } }
packages/packages/flutter_markdown/example/lib/screens/demo_screen.dart/0
{ "file_path": "packages/packages/flutter_markdown/example/lib/screens/demo_screen.dart", "repo_id": "packages", "token_count": 2257 }
986
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
packages/packages/flutter_markdown/example/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "packages/packages/flutter_markdown/example/macos/Runner/Configs/Release.xcconfig", "repo_id": "packages", "token_count": 32 }
987
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io' as io; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter_markdown/flutter_markdown.dart'; import 'package:flutter_test/flutter_test.dart'; import 'image_test_mocks.dart'; import 'utils.dart'; void main() => defineTests(); void defineTests() { group('Image', () { setUp(() { // Only needs to be done once since the HttpClient generated // by this override is cached as a static singleton. io.HttpOverrides.global = TestHttpOverrides(); }); testWidgets( 'should not interrupt styling', (WidgetTester tester) async { const String data = '_textbefore ![alt](https://img) textafter_'; await tester.pumpWidget( boilerplate( const Markdown(data: data), ), ); final Iterable<Text> texts = tester.widgetList(find.byType(Text)); final Text firstTextWidget = texts.first; final TextSpan firstTextSpan = firstTextWidget.textSpan! as TextSpan; final Image image = tester.widget(find.byType(Image)); final NetworkImage networkImage = image.image as NetworkImage; final Text secondTextWidget = texts.last; final TextSpan secondTextSpan = secondTextWidget.textSpan! as TextSpan; expect(firstTextSpan.text, 'textbefore '); expect(firstTextSpan.style!.fontStyle, FontStyle.italic); expect(networkImage.url, 'https://img'); expect(secondTextSpan.text, ' textafter'); expect(secondTextSpan.style!.fontStyle, FontStyle.italic); }, ); testWidgets( 'should work with a link', (WidgetTester tester) async { const String data = '![alt](https://img#50x50)'; await tester.pumpWidget( boilerplate( const Markdown(data: data), ), ); final Image image = tester.widget(find.byType(Image)); final NetworkImage networkImage = image.image as NetworkImage; expect(networkImage.url, 'https://img'); expect(image.width, 50); expect(image.height, 50); }, ); testWidgets( 'should work with relative remote image', (WidgetTester tester) async { const String data = '![alt](/img.png)'; await tester.pumpWidget( boilerplate( const Markdown( data: data, imageDirectory: 'https://localhost', ), ), ); final Iterable<Widget> widgets = tester.allWidgets; final Image image = widgets.firstWhere((Widget widget) => widget is Image) as Image; expect(image.image is NetworkImage, isTrue); expect((image.image as NetworkImage).url, 'https://localhost/img.png'); }, ); testWidgets( 'local files should be files on non-web', (WidgetTester tester) async { const String data = '![alt](http.png)'; await tester.pumpWidget( boilerplate( const Markdown(data: data), ), ); final Iterable<Widget> widgets = tester.allWidgets; final Image image = widgets.firstWhere((Widget widget) => widget is Image) as Image; expect(image.image is FileImage, isTrue); }, skip: kIsWeb, ); testWidgets( 'local files should be network on web', (WidgetTester tester) async { const String data = '![alt](http.png)'; await tester.pumpWidget( boilerplate( const Markdown(data: data), ), ); final Iterable<Widget> widgets = tester.allWidgets; final Image image = widgets.firstWhere((Widget widget) => widget is Image) as Image; expect(image.image is NetworkImage, isTrue); }, skip: !kIsWeb, ); testWidgets( 'should work with resources', (WidgetTester tester) async { TestWidgetsFlutterBinding.ensureInitialized(); const String data = '![alt](resource:assets/logo.png)'; await tester.pumpWidget( boilerplate( MaterialApp( home: DefaultAssetBundle( bundle: TestAssetBundle(), child: Center( child: Container( color: Colors.white, width: 500, child: const Markdown( data: data, ), ), ), ), ), ), ); final Image image = tester.allWidgets .firstWhere((Widget widget) => widget is Image) as Image; expect(image.image is AssetImage, isTrue); expect((image.image as AssetImage).assetName, 'assets/logo.png'); // Force the asset image to be rasterized so it can be compared. await tester.runAsync(() async { final Element element = tester.element(find.byType(Markdown)); await precacheImage(image.image, element); }); await tester.pumpAndSettle(); await expectLater( find.byType(Container), matchesGoldenFile( 'assets/images/golden/image_test/resource_asset_logo.png')); }, skip: kIsWeb, // Goldens are platform-specific. ); testWidgets( 'should work with local image files', (WidgetTester tester) async { const String data = '![alt](img.png#50x50)'; await tester.pumpWidget( boilerplate( const Markdown(data: data), ), ); final Image image = tester.widget(find.byType(Image)); final FileImage fileImage = image.image as FileImage; expect(fileImage.file.path, 'img.png'); expect(image.width, 50); expect(image.height, 50); }, skip: kIsWeb, ); testWidgets( 'should show properly next to text', (WidgetTester tester) async { const String data = 'Hello ![alt](img#50x50)'; await tester.pumpWidget( boilerplate( const Markdown(data: data), ), ); final Text text = tester.widget(find.byType(Text)); final TextSpan textSpan = text.textSpan! as TextSpan; expect(textSpan.text, 'Hello '); expect(textSpan.style, isNotNull); }, ); testWidgets( 'should work when nested in a link', (WidgetTester tester) async { final List<String> tapTexts = <String>[]; final List<String?> tapResults = <String?>[]; const String data = '[![alt](https://img#50x50)](href)'; await tester.pumpWidget( boilerplate( Markdown( data: data, onTapLink: (String text, String? value, String title) { tapTexts.add(text); tapResults.add(value); }, ), ), ); final GestureDetector detector = tester.widget(find.byType(GestureDetector)); detector.onTap!(); expect(tapTexts.length, 1); expect(tapTexts, everyElement('alt')); expect(tapResults.length, 1); expect(tapResults, everyElement('href')); }, ); testWidgets( 'should work when nested in a link with text', (WidgetTester tester) async { final List<String> tapTexts = <String>[]; final List<String?> tapResults = <String?>[]; const String data = '[Text before ![alt](https://img#50x50) text after](href)'; await tester.pumpWidget( boilerplate( Markdown( data: data, onTapLink: (String text, String? value, String title) { tapTexts.add(text); tapResults.add(value); }, ), ), ); final GestureDetector detector = tester.widget(find.byType(GestureDetector)); detector.onTap!(); final Iterable<Text> texts = tester.widgetList(find.byType(Text)); final Text firstTextWidget = texts.first; final TextSpan firstSpan = firstTextWidget.textSpan! as TextSpan; (firstSpan.recognizer as TapGestureRecognizer?)!.onTap!(); final Text lastTextWidget = texts.last; final TextSpan lastSpan = lastTextWidget.textSpan! as TextSpan; (lastSpan.recognizer as TapGestureRecognizer?)!.onTap!(); expect(firstSpan.children, null); expect(firstSpan.text, 'Text before '); expect(firstSpan.recognizer.runtimeType, equals(TapGestureRecognizer)); expect(lastSpan.children, null); expect(lastSpan.text, ' text after'); expect(lastSpan.recognizer.runtimeType, equals(TapGestureRecognizer)); expect(tapTexts.length, 3); expect(tapTexts, everyElement('Text before alt text after')); expect(tapResults.length, 3); expect(tapResults, everyElement('href')); }, ); testWidgets( 'should work alongside different links', (WidgetTester tester) async { final List<String> tapTexts = <String>[]; final List<String?> tapResults = <String?>[]; const String data = '[Link before](firstHref)[![alt](https://img#50x50)](imageHref)[link after](secondHref)'; await tester.pumpWidget( boilerplate( Markdown( data: data, onTapLink: (String text, String? value, String title) { tapTexts.add(text); tapResults.add(value); }, ), ), ); final Iterable<Text> texts = tester.widgetList(find.byType(Text)); final Text firstTextWidget = texts.first; final TextSpan firstSpan = firstTextWidget.textSpan! as TextSpan; (firstSpan.recognizer as TapGestureRecognizer?)!.onTap!(); final GestureDetector detector = tester.widget(find.byType(GestureDetector)); detector.onTap!(); final Text lastTextWidget = texts.last; final TextSpan lastSpan = lastTextWidget.textSpan! as TextSpan; (lastSpan.recognizer as TapGestureRecognizer?)!.onTap!(); expect(firstSpan.children, null); expect(firstSpan.text, 'Link before'); expect(firstSpan.recognizer.runtimeType, equals(TapGestureRecognizer)); expect(lastSpan.children, null); expect(lastSpan.text, 'link after'); expect(lastSpan.recognizer.runtimeType, equals(TapGestureRecognizer)); expect(tapTexts.length, 3); expect(tapTexts, <String>['Link before', 'alt', 'link after']); expect(tapResults.length, 3); expect(tapResults, <String>['firstHref', 'imageHref', 'secondHref']); }, ); testWidgets( 'custom image builder', (WidgetTester tester) async { const String data = '![alt](https://img.png)'; Widget builder(Uri uri, String? title, String? alt) => Image.asset('assets/logo.png'); await tester.pumpWidget( boilerplate( MaterialApp( home: DefaultAssetBundle( bundle: TestAssetBundle(), child: Center( child: Container( color: Colors.white, width: 500, child: Markdown( data: data, imageBuilder: builder, ), ), ), ), ), ), ); final Iterable<Widget> widgets = tester.allWidgets; final Image image = widgets.firstWhere((Widget widget) => widget is Image) as Image; expect(image.image.runtimeType, AssetImage); expect((image.image as AssetImage).assetName, 'assets/logo.png'); // Force the asset image to be rasterized so it can be compared. await tester.runAsync(() async { final Element element = tester.element(find.byType(Markdown)); await precacheImage(image.image, element); }); await tester.pumpAndSettle(); await expectLater( find.byType(Container), matchesGoldenFile( 'assets/images/golden/image_test/custom_builder_asset_logo.png')); }, skip: kIsWeb, // Goldens are platform-specific. ); }); }
packages/packages/flutter_markdown/test/image_test.dart/0
{ "file_path": "packages/packages/flutter_markdown/test/image_test.dart", "repo_id": "packages", "token_count": 5802 }
988
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'dart:io' as io; import 'package:flutter/foundation.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; final TextTheme textTheme = Typography.material2018() .black .merge(const TextTheme(bodyMedium: TextStyle(fontSize: 12.0))); Iterable<Widget> selfAndDescendantWidgetsOf(Finder start, WidgetTester tester) { final Element startElement = tester.element(start); final Iterable<Widget> descendants = collectAllElementsFrom(startElement, skipOffstage: false) .map((Element e) => e.widget); return <Widget>[ startElement.widget, ...descendants, ]; } // Returns the RenderEditable displaying the given text. RenderEditable findRenderEditableWithText(WidgetTester tester, String text) { final Iterable<RenderObject> roots = tester.renderObjectList(find.byType(EditableText)); expect(roots, isNotEmpty); late RenderEditable renderEditable; void recursiveFinder(RenderObject child) { if (child is RenderEditable && child.plainText == text) { renderEditable = child; return; } child.visitChildren(recursiveFinder); } for (final RenderObject root in roots) { root.visitChildren(recursiveFinder); } expect(renderEditable, isNotNull); return renderEditable; } // Returns the [textOffset] position in rendered [text]. Offset positionInRenderedText( WidgetTester tester, String text, int textOffset) { final RenderEditable renderEditable = findRenderEditableWithText(tester, text); final Iterable<TextSelectionPoint> textOffsetPoints = renderEditable.getEndpointsForSelection( TextSelection.collapsed(offset: textOffset), ); // Map the points to global positions. final List<TextSelectionPoint> endpoints = textOffsetPoints.map<TextSelectionPoint>((TextSelectionPoint point) { return TextSelectionPoint( renderEditable.localToGlobal(point.point), point.direction, ); }).toList(); expect(endpoints.length, 1); return endpoints[0].point + const Offset(kIsWeb ? 1.0 : 0.0, -2.0); } void expectWidgetTypes(Iterable<Widget> widgets, List<Type> expected) { final List<Type> actual = widgets.map((Widget w) => w.runtimeType).toList(); expect(actual, expected); } void expectTextStrings(Iterable<Widget> widgets, List<String> strings) { int currentString = 0; for (final Widget widget in widgets) { TextSpan? span; if (widget is RichText) { span = widget.text as TextSpan; } else if (widget is SelectableText) { span = widget.textSpan; } if (span != null) { final String text = _extractTextFromTextSpan(span); expect(text, equals(strings[currentString])); currentString += 1; } } } String _extractTextFromTextSpan(TextSpan span) { String text = span.text ?? ''; if (span.children != null) { for (final TextSpan child in span.children!.toList().cast<TextSpan>()) { text += _extractTextFromTextSpan(child); } } return text; } // Check the font style and weight of the text span. void expectTextSpanStyle( TextSpan textSpan, FontStyle? style, FontWeight weight) { // Verify a text style is set expect(textSpan.style, isNotNull, reason: 'text span text style is null'); // Font style check if (style == null) { expect(textSpan.style!.fontStyle, isNull, reason: 'font style is not null'); } else { expect(textSpan.style!.fontStyle, isNotNull, reason: 'font style is null'); expect( textSpan.style!.fontStyle == style, isTrue, reason: 'font style is not $style', ); } // Font weight check expect(textSpan.style, isNotNull, reason: 'font style is null'); expect( textSpan.style!.fontWeight == weight, isTrue, reason: 'font weight is not $weight', ); } @immutable class MarkdownLink { const MarkdownLink(this.text, this.destination, [this.title = '']); final String text; final String? destination; final String title; @override bool operator ==(Object other) => other is MarkdownLink && other.text == text && other.destination == destination && other.title == title; @override int get hashCode => '$text$destination$title'.hashCode; @override String toString() { return '[$text]($destination "$title")'; } } /// Verify a valid link structure has been created. This routine checks for the /// link text and the associated [TapGestureRecognizer] on the text span. void expectValidLink(String linkText) { final Finder textFinder = find.byType(Text); expect(textFinder, findsOneWidget); final Text text = textFinder.evaluate().first.widget as Text; // Verify the link text. expect(text.textSpan, isNotNull); expect(text.textSpan, isA<TextSpan>()); // Verify the link text is a onTap gesture recognizer. final TextSpan textSpan = text.textSpan! as TextSpan; expectLinkTextSpan(textSpan, linkText); } void expectLinkTextSpan(TextSpan textSpan, String linkText) { expect(textSpan.children, isNull); expect(textSpan.toPlainText(), linkText); expect(textSpan.recognizer, isNotNull); expect(textSpan.recognizer, isA<TapGestureRecognizer>()); final TapGestureRecognizer? tapRecognizer = textSpan.recognizer as TapGestureRecognizer?; expect(tapRecognizer?.onTap, isNotNull); // Execute the onTap callback handler. tapRecognizer!.onTap!(); } void expectInvalidLink(String linkText) { final Finder textFinder = find.byType(Text); expect(textFinder, findsOneWidget); final Text text = textFinder.evaluate().first.widget as Text; expect(text.textSpan, isNotNull); expect(text.textSpan, isA<TextSpan>()); final String plainText = text.textSpan!.toPlainText(); expect(plainText, linkText); final TextSpan textSpan = text.textSpan! as TextSpan; expect(textSpan.recognizer, isNull); } void expectTableSize(int rows, int columns) { final Finder tableFinder = find.byType(Table); expect(tableFinder, findsOneWidget); final Table table = tableFinder.evaluate().first.widget as Table; expect(table.children.length, rows); for (int index = 0; index < rows; index++) { expect(_ambiguate(table.children[index].children)!.length, columns); } } void expectLinkTap(MarkdownLink? actual, MarkdownLink expected) { expect(actual, equals(expected), reason: 'incorrect link tap results, actual: $actual expected: $expected'); } String dumpRenderView() { return WidgetsBinding.instance.rootElement!.toStringDeep().replaceAll( RegExp(r'SliverChildListDelegate#\d+', multiLine: true), 'SliverChildListDelegate', ); } /// Wraps a widget with a left-to-right [Directionality] for tests. Widget boilerplate(Widget child) { return Directionality( textDirection: TextDirection.ltr, child: child, ); } class TestAssetBundle extends CachingAssetBundle { @override Future<ByteData> load(String key) async { if (key == 'AssetManifest.json') { const String manifest = r'{"assets/logo.png":["assets/logo.png"]}'; final ByteData asset = ByteData.view(utf8.encoder.convert(manifest).buffer); return Future<ByteData>.value(asset); } else if (key == 'AssetManifest.bin') { final ByteData manifest = const StandardMessageCodec().encodeMessage( <String, List<Object>>{'assets/logo.png': <Object>[]})!; return Future<ByteData>.value(manifest); } else if (key == 'AssetManifest.smcbin') { final ByteData manifest = const StandardMessageCodec().encodeMessage( <String, List<Object>>{'assets/logo.png': <Object>[]})!; return Future<ByteData>.value(manifest); } else if (key == 'assets/logo.png') { // The root directory tests are run from is different for 'flutter test' // verses 'flutter test test/*_test.dart'. Adjust the root directory // to access the assets directory. final io.Directory rootDirectory = io.Directory.current.path.endsWith('${io.Platform.pathSeparator}test') ? io.Directory.current.parent : io.Directory.current; final io.File file = io.File('${rootDirectory.path}/test/assets/images/logo.png'); final ByteData asset = ByteData.view(file.readAsBytesSync().buffer); return asset; } else { throw ArgumentError('Unknown asset key: $key'); } } } /// This allows a value of type T or T? to be treated as a value of type T?. /// /// We use this so that APIs that have become non-nullable can still be used /// with `!` and `?` on the stable branch. T? _ambiguate<T>(T? value) => value;
packages/packages/flutter_markdown/test/utils.dart/0
{ "file_path": "packages/packages/flutter_markdown/test/utils.dart", "repo_id": "packages", "token_count": 3093 }
989
// Copyright 2013 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:meta/meta.dart'; import 'file_system.dart'; import 'logger.dart'; /// Emum for each officially supported platform. enum SupportedPlatform { android, ios, linux, macos, web, windows, fuchsia, } class FlutterProjectFactory { FlutterProjectFactory(); @visibleForTesting final Map<String, FlutterProject> projects = <String, FlutterProject>{}; /// Returns a [FlutterProject] view of the given directory or a ToolExit error, /// if `pubspec.yaml` or `example/pubspec.yaml` is invalid. FlutterProject fromDirectory(Directory directory) { return projects.putIfAbsent(directory.path, () { return FlutterProject(directory); }); } } /// Represents the contents of a Flutter project at the specified [directory]. class FlutterProject { FlutterProject(this.directory); /// Returns a [FlutterProject] view of the current directory or a ToolExit error, /// if `pubspec.yaml` or `example/pubspec.yaml` is invalid. static FlutterProject current(FileSystem fs) => FlutterProject(fs.currentDirectory); /// Create a [FlutterProject] and bypass the project caching. @visibleForTesting static FlutterProject fromDirectoryTest(Directory directory, [Logger? logger]) { logger ??= BufferLogger.test(); return FlutterProject(directory); } Directory directory; /// The `pubspec.yaml` file of this project. File get pubspecFile => directory.childFile('pubspec.yaml'); /// The `.metadata` file of this project. File get metadataFile => directory.childFile('.metadata'); /// Returns a list of platform names that are supported by the project. List<SupportedPlatform> getSupportedPlatforms() { final List<SupportedPlatform> platforms = <SupportedPlatform>[]; if (directory.childDirectory('android').existsSync()) { platforms.add(SupportedPlatform.android); } if (directory.childDirectory('ios').existsSync()) { platforms.add(SupportedPlatform.ios); } if (directory.childDirectory('web').existsSync()) { platforms.add(SupportedPlatform.web); } if (directory.childDirectory('macos').existsSync()) { platforms.add(SupportedPlatform.macos); } if (directory.childDirectory('linux').existsSync()) { platforms.add(SupportedPlatform.linux); } if (directory.childDirectory('windows').existsSync()) { platforms.add(SupportedPlatform.windows); } if (directory.childDirectory('fuchsia').existsSync()) { platforms.add(SupportedPlatform.fuchsia); } return platforms; } }
packages/packages/flutter_migrate/lib/src/base/project.dart/0
{ "file_path": "packages/packages/flutter_migrate/lib/src/base/project.dart", "repo_id": "packages", "token_count": 845 }
990
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:io'; import 'dart:typed_data'; import 'package:process/process.dart'; import 'base/common.dart'; import 'base/file_system.dart'; import 'base/logger.dart'; import 'base/terminal.dart'; /// The default name of the migrate working directory used to stage proposed changes. const String kDefaultMigrateStagingDirectoryName = 'migrate_staging_dir'; /// Utility class that contains methods that wrap git and other shell commands. class MigrateUtils { MigrateUtils({ required Logger logger, required FileSystem fileSystem, required ProcessManager processManager, }) : _processManager = processManager, _logger = logger, _fileSystem = fileSystem; final Logger _logger; final FileSystem _fileSystem; final ProcessManager _processManager; Future<ProcessResult> _runCommand(List<String> command, {String? workingDirectory, bool runInShell = false}) { return _processManager.run(command, workingDirectory: workingDirectory, runInShell: runInShell); } /// Calls `git diff` on two files and returns the diff as a DiffResult. Future<DiffResult> diffFiles(File one, File two) async { if (one.existsSync() && !two.existsSync()) { return DiffResult(diffType: DiffType.deletion); } if (!one.existsSync() && two.existsSync()) { return DiffResult(diffType: DiffType.addition); } final List<String> cmdArgs = <String>[ 'git', 'diff', '--no-index', one.absolute.path, two.absolute.path ]; final ProcessResult result = await _runCommand(cmdArgs); // diff exits with 1 if diffs are found. checkForErrors(result, allowedExitCodes: <int>[0, 1], commandDescription: 'git ${cmdArgs.join(' ')}'); return DiffResult( diffType: DiffType.command, diff: result.stdout as String, exitCode: result.exitCode); } /// Clones a copy of the flutter repo into the destination directory. Returns false if unsuccessful. Future<bool> cloneFlutter(String revision, String destination) async { // Use https url instead of ssh to avoid need to setup ssh on git. List<String> cmdArgs = <String>[ 'git', 'clone', '--filter=blob:none', 'https://github.com/flutter/flutter.git', destination ]; ProcessResult result = await _runCommand(cmdArgs); checkForErrors(result, commandDescription: cmdArgs.join(' ')); cmdArgs.clear(); cmdArgs = <String>['git', 'reset', '--hard', revision]; result = await _runCommand(cmdArgs, workingDirectory: destination); if (!checkForErrors(result, commandDescription: cmdArgs.join(' '), exit: false)) { return false; } return true; } /// Calls `flutter create` as a re-entrant command. Future<String> createFromTemplates( String flutterBinPath, { required String name, bool legacyNameParameter = false, required String androidLanguage, required String iosLanguage, required String outputDirectory, String? createVersion, List<String> platforms = const <String>[], int iterationsAllowed = 5, }) async { // Limit the number of iterations this command is allowed to attempt to prevent infinite looping. if (iterationsAllowed <= 0) { _logger.printError( 'Unable to `flutter create` with the version of flutter at $flutterBinPath'); return outputDirectory; } final List<String> cmdArgs = <String>['$flutterBinPath/flutter', 'create']; if (!legacyNameParameter) { cmdArgs.add('--project-name=$name'); } cmdArgs.add('--android-language=$androidLanguage'); cmdArgs.add('--ios-language=$iosLanguage'); if (platforms.isNotEmpty) { String platformsArg = '--platforms='; for (int i = 0; i < platforms.length; i++) { if (i > 0) { platformsArg += ','; } platformsArg += platforms[i]; } cmdArgs.add(platformsArg); } cmdArgs.add('--no-pub'); if (legacyNameParameter) { cmdArgs.add(name); } else { cmdArgs.add(outputDirectory); } final ProcessResult result = await _runCommand(cmdArgs, workingDirectory: outputDirectory); final String error = result.stderr as String; // Catch errors due to parameters not existing. // Old versions of the tool does not include the platforms option. if (error.contains('Could not find an option named "platforms".')) { return createFromTemplates( flutterBinPath, name: name, legacyNameParameter: legacyNameParameter, androidLanguage: androidLanguage, iosLanguage: iosLanguage, outputDirectory: outputDirectory, iterationsAllowed: iterationsAllowed--, ); } // Old versions of the tool does not include the project-name option. if ((result.stderr as String) .contains('Could not find an option named "project-name".')) { return createFromTemplates( flutterBinPath, name: name, legacyNameParameter: true, androidLanguage: androidLanguage, iosLanguage: iosLanguage, outputDirectory: outputDirectory, platforms: platforms, iterationsAllowed: iterationsAllowed--, ); } if (error.contains('Multiple output directories specified.')) { if (error.contains('Try moving --platforms')) { return createFromTemplates( flutterBinPath, name: name, legacyNameParameter: legacyNameParameter, androidLanguage: androidLanguage, iosLanguage: iosLanguage, outputDirectory: outputDirectory, iterationsAllowed: iterationsAllowed--, ); } } checkForErrors(result, commandDescription: cmdArgs.join(' '), silent: true); if (legacyNameParameter) { return _fileSystem.path.join(outputDirectory, name); } return outputDirectory; } /// Runs the git 3-way merge on three files and returns the results as a MergeResult. /// /// Passing the same path for base and current will perform a two-way fast forward merge. Future<MergeResult> gitMergeFile({ required String base, required String current, required String target, required String localPath, }) async { final List<String> cmdArgs = <String>[ 'git', 'merge-file', '-p', current, base, target ]; final ProcessResult result = await _runCommand(cmdArgs); checkForErrors(result, allowedExitCodes: <int>[-1], commandDescription: cmdArgs.join(' ')); return StringMergeResult(result, localPath); } /// Calls `git init` on the workingDirectory. Future<void> gitInit(String workingDirectory) async { final List<String> cmdArgs = <String>['git', 'init']; final ProcessResult result = await _runCommand(cmdArgs, workingDirectory: workingDirectory); checkForErrors(result, commandDescription: cmdArgs.join(' ')); } /// Returns true if the workingDirectory git repo has any uncommited changes. Future<bool> hasUncommittedChanges(String workingDirectory, {String? migrateStagingDir}) async { final List<String> cmdArgs = <String>[ 'git', 'ls-files', '--deleted', '--modified', '--others', '--exclude-standard', '--exclude=${migrateStagingDir ?? kDefaultMigrateStagingDirectoryName}' ]; final ProcessResult result = await _runCommand(cmdArgs, workingDirectory: workingDirectory); checkForErrors(result, allowedExitCodes: <int>[-1], commandDescription: cmdArgs.join(' ')); if ((result.stdout as String).isEmpty) { return false; } return true; } /// Returns true if the workingDirectory is a git repo. Future<bool> isGitRepo(String workingDirectory) async { final List<String> cmdArgs = <String>[ 'git', 'rev-parse', '--is-inside-work-tree' ]; final ProcessResult result = await _runCommand(cmdArgs, workingDirectory: workingDirectory); checkForErrors(result, allowedExitCodes: <int>[-1], commandDescription: cmdArgs.join(' ')); if (result.exitCode == 0) { return true; } return false; } /// Returns true if the file at `filePath` is covered by the `.gitignore` Future<bool> isGitIgnored(String filePath, String workingDirectory) async { final List<String> cmdArgs = <String>['git', 'check-ignore', filePath]; final ProcessResult result = await _runCommand(cmdArgs, workingDirectory: workingDirectory); checkForErrors(result, allowedExitCodes: <int>[0, 1, 128], commandDescription: cmdArgs.join(' ')); return result.exitCode == 0; } /// Runs `flutter pub upgrade --major-revisions`. Future<void> flutterPubUpgrade(String workingDirectory) async { final List<String> cmdArgs = <String>[ 'flutter', 'pub', 'upgrade', '--major-versions' ]; final ProcessResult result = await _runCommand(cmdArgs, workingDirectory: workingDirectory); checkForErrors(result, commandDescription: cmdArgs.join(' ')); } /// Runs `./gradlew tasks` in the android directory of a flutter project. Future<void> gradlewTasks(String workingDirectory) async { final String baseCommand = isWindows ? 'gradlew.bat' : './gradlew'; final List<String> cmdArgs = <String>[baseCommand, 'tasks']; final ProcessResult result = await _runCommand(cmdArgs, workingDirectory: workingDirectory, runInShell: isWindows); checkForErrors(result, commandDescription: cmdArgs.join(' ')); } /// Verifies that the ProcessResult does not contain an error. /// /// If an error is detected, the error can be optionally logged or exit the tool. /// /// Passing -1 in allowedExitCodes means all exit codes are valid. bool checkForErrors(ProcessResult result, {List<int> allowedExitCodes = const <int>[0], String? commandDescription, bool exit = true, bool silent = false}) { if (allowedExitCodes.contains(result.exitCode) || allowedExitCodes.contains(-1)) { return true; } if (!silent) { _logger.printError( 'Command encountered an error with exit code ${result.exitCode}.'); if (commandDescription != null) { _logger.printError('Command:'); _logger.printError(commandDescription, indent: 2); } _logger.printError('Stdout:'); _logger.printError(result.stdout as String, indent: 2); _logger.printError('Stderr:'); _logger.printError(result.stderr as String, indent: 2); } if (exit) { throwToolExit( 'Command failed with exit code ${result.exitCode}: ${result.stderr}\n${result.stdout}', exitCode: result.exitCode); } return false; } /// Returns true if the file does not contain any git conflit markers. bool conflictsResolved(String contents) { final bool hasMarker = contents.contains('>>>>>>>') || contents.contains('=======') || contents.contains('<<<<<<<'); return !hasMarker; } } Future<bool> gitRepoExists( String projectDirectory, Logger logger, MigrateUtils migrateUtils) async { if (await migrateUtils.isGitRepo(projectDirectory)) { return true; } logger.printStatus( 'Project is not a git repo. Please initialize a git repo and try again.'); printCommand('git init', logger); return false; } Future<bool> hasUncommittedChanges( String projectDirectory, Logger logger, MigrateUtils migrateUtils) async { if (await migrateUtils.hasUncommittedChanges(projectDirectory)) { logger.printStatus( 'There are uncommitted changes in your project. Please git commit, abandon, or stash your changes before trying again.'); logger.printStatus('You may commit your changes using'); printCommand('git add .', logger, newlineAfter: false); printCommand('git commit -m "<message>"', logger); return true; } return false; } void printCommand(String command, Logger logger, {bool newlineAfter = true}) { logger.printStatus( '\n\$ $command${newlineAfter ? '\n' : ''}', color: TerminalColor.grey, indent: 4, newline: false, ); } /// Prints a command to logger with appropriate formatting. void printCommandText(String command, Logger logger, {bool? standalone = true, bool newlineAfter = true}) { final String prefix = standalone == null ? '' : (standalone ? 'dart run <flutter_migrate_dir>${Platform.pathSeparator}bin${Platform.pathSeparator}flutter_migrate.dart ' : 'flutter migrate '); printCommand('$prefix$command', logger, newlineAfter: newlineAfter); } /// Defines the classification of difference between files. enum DiffType { command, addition, deletion, ignored, none, } /// Tracks the output of a git diff command or any special cases such as addition of a new /// file or deletion of an existing file. class DiffResult { DiffResult({ required this.diffType, this.diff, this.exitCode, }) : assert(diffType == DiffType.command && exitCode != null || diffType != DiffType.command && exitCode == null); /// The diff string output by git. final String? diff; final DiffType diffType; /// The exit code of the command. This is zero when no diffs are found. /// /// The exitCode is null when the diffType is not `command`. final int? exitCode; } /// Data class to hold the results of a merge. abstract class MergeResult { /// Initializes a MergeResult based off of a ProcessResult. MergeResult(ProcessResult result, this.localPath) : hasConflict = result.exitCode != 0, exitCode = result.exitCode; /// Manually initializes a MergeResult with explicit values. MergeResult.explicit({ required this.hasConflict, required this.exitCode, required this.localPath, }); /// True when there is a merge conflict. bool hasConflict; /// The exitcode of the merge command. int exitCode; /// The local path relative to the project root of the file. String localPath; } /// The results of a string merge. class StringMergeResult extends MergeResult { /// Initializes a BinaryMergeResult based off of a ProcessResult. StringMergeResult(super.result, super.localPath) : mergedString = result.stdout as String; /// Manually initializes a StringMergeResult with explicit values. StringMergeResult.explicit({ required this.mergedString, required super.hasConflict, required super.exitCode, required super.localPath, }) : super.explicit(); /// The final merged string. String mergedString; } /// The results of a binary merge. class BinaryMergeResult extends MergeResult { /// Initializes a BinaryMergeResult based off of a ProcessResult. BinaryMergeResult(super.result, super.localPath) : mergedBytes = result.stdout as Uint8List; /// Manually initializes a BinaryMergeResult with explicit values. BinaryMergeResult.explicit({ required this.mergedBytes, required super.hasConflict, required super.exitCode, required super.localPath, }) : super.explicit(); /// The final merged bytes. Uint8List mergedBytes; }
packages/packages/flutter_migrate/lib/src/utils.dart/0
{ "file_path": "packages/packages/flutter_migrate/lib/src/utils.dart", "repo_id": "packages", "token_count": 5344 }
991
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:io' as io; import 'package:flutter_migrate/src/base/context.dart'; import 'package:flutter_migrate/src/base/file_system.dart'; import 'package:flutter_migrate/src/base/io.dart'; import 'package:meta/meta.dart'; import 'package:path/path.dart' as path; // flutter_ignore: package_path_import import 'package:test/test.dart' as test_package show test; import 'package:test/test.dart' hide test; import 'test_utils.dart'; export 'package:test/test.dart' hide isInstanceOf, test; bool tryToDelete(FileSystemEntity fileEntity) { // This should not be necessary, but it turns out that // on Windows it's common for deletions to fail due to // bogus (we think) "access denied" errors. try { if (fileEntity.existsSync()) { fileEntity.deleteSync(recursive: true); return true; } } on FileSystemException catch (error) { // We print this so that it's visible in the logs, to get an idea of how // common this problem is, and if any patterns are ever noticed by anyone. // ignore: avoid_print print('Failed to delete ${fileEntity.path}: $error'); } return false; } /// Gets the path to the root of the Flutter repository. /// /// This will first look for a `FLUTTER_ROOT` environment variable. If the /// environment variable is set, it will be returned. Otherwise, this will /// deduce the path from `platform.script`. String getFlutterRoot() { if (io.Platform.environment.containsKey('FLUTTER_ROOT')) { return io.Platform.environment['FLUTTER_ROOT']!; } Error invalidScript() => StateError( 'Could not determine flutter_tools/ path from script URL (${io.Platform.script}); consider setting FLUTTER_ROOT explicitly.'); Uri scriptUri; switch (io.Platform.script.scheme) { case 'file': scriptUri = io.Platform.script; case 'data': final RegExp flutterTools = RegExp( r'(file://[^"]*[/\\]flutter_tools[/\\][^"]+\.dart)', multiLine: true); final Match? match = flutterTools.firstMatch(Uri.decodeFull(io.Platform.script.path)); if (match == null) { throw invalidScript(); } scriptUri = Uri.parse(match.group(1)!); default: throw invalidScript(); } final List<String> parts = path.split(fileSystem.path.fromUri(scriptUri)); final int toolsIndex = parts.indexOf('flutter_tools'); if (toolsIndex == -1) { throw invalidScript(); } final String toolsPath = path.joinAll(parts.sublist(0, toolsIndex + 1)); return path.normalize(path.join(toolsPath, '..', '..')); } String getMigratePackageRoot() { return io.Directory.current.path; } String getMigrateMain() { return fileSystem.path .join(getMigratePackageRoot(), 'bin', 'flutter_migrate.dart'); } Future<ProcessResult> runMigrateCommand(List<String> args, {String? workingDirectory}) { final List<String> commandArgs = <String>['dart', 'run', getMigrateMain()]; commandArgs.addAll(args); return processManager.run(commandArgs, workingDirectory: workingDirectory); } /// The tool overrides `test` to ensure that files created under the /// system temporary directory are deleted after each test by calling /// `LocalFileSystem.dispose()`. @isTest void test( String description, FutureOr<void> Function() body, { String? testOn, dynamic skip, List<String>? tags, Map<String, dynamic>? onPlatform, int? retry, Timeout? timeout, }) { test_package.test( description, () async { addTearDown(() async { await fileSystem.dispose(); }); return body(); }, skip: skip, tags: tags, onPlatform: onPlatform, retry: retry, testOn: testOn, timeout: timeout, // We don't support "timeout"; see ../../dart_test.yaml which // configures all tests to have a 15 minute timeout which should // definitely be enough. ); } /// Executes a test body in zone that does not allow context-based injection. /// /// For classes which have been refactored to exclude context-based injection /// or globals like [fs] or [platform], prefer using this test method as it /// will prevent accidentally including these context getters in future code /// changes. /// /// For more information, see https://github.com/flutter/flutter/issues/47161 @isTest void testWithoutContext( String description, FutureOr<void> Function() body, { String? testOn, dynamic skip, List<String>? tags, Map<String, dynamic>? onPlatform, int? retry, Timeout? timeout, }) { return test( description, () async { return runZoned(body, zoneValues: <Object, Object>{ contextKey: const _NoContext(), }); }, skip: skip, tags: tags, onPlatform: onPlatform, retry: retry, testOn: testOn, timeout: timeout, // We support timeout here due to the packages repo not setting default // timeout to 15min. ); } /// An implementation of [AppContext] that throws if context.get is called in the test. /// /// The intention of the class is to ensure we do not accidentally regress when /// moving towards more explicit dependency injection by accidentally using /// a Zone value in place of a constructor parameter. class _NoContext implements AppContext { const _NoContext(); @override T get<T>() { throw UnsupportedError('context.get<$T> is not supported in test methods. ' 'Use Testbed or testUsingContext if accessing Zone injected ' 'values.'); } @override String get name => 'No Context'; @override Future<V> run<V>({ required FutureOr<V> Function() body, String? name, Map<Type, Generator>? overrides, Map<Type, Generator>? fallbacks, ZoneSpecification? zoneSpecification, }) async { return body(); } } /// Matcher for functions that throw [AssertionError]. final Matcher throwsAssertionError = throwsA(isA<AssertionError>());
packages/packages/flutter_migrate/test/src/common.dart/0
{ "file_path": "packages/packages/flutter_migrate/test/src/common.dart", "repo_id": "packages", "token_count": 2023 }
992
// Copyright 2013 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:flutter_plugin_android_lifecycle_example/main.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); testWidgets('loads', (WidgetTester tester) async { await tester.pumpWidget(const MyApp()); }); }
packages/packages/flutter_plugin_android_lifecycle/example/integration_test/flutter_plugin_android_lifecycle_test.dart/0
{ "file_path": "packages/packages/flutter_plugin_android_lifecycle/example/integration_test/flutter_plugin_android_lifecycle_test.dart", "repo_id": "packages", "token_count": 161 }
993
# go_router A declarative routing package for Flutter that uses the Router API to provide a convenient, url-based API for navigating between different screens. You can define URL patterns, navigate using a URL, handle deep links, and a number of other navigation-related scenarios. ## Features GoRouter has a number of features to make navigation straightforward: - Parsing path and query parameters using a template syntax (for example, "user/:id') - Displaying multiple screens for a destination (sub-routes) - Redirection support - you can re-route the user to a different URL based on application state, for example to a sign-in when the user is not authenticated - Support for multiple Navigators via [ShellRoute](https://pub.dev/documentation/go_router/latest/go_router/ShellRoute-class.html) - you can display an inner Navigator that displays its own pages based on the matched route. For example, to display a BottomNavigationBar that stays visible at the bottom of the screen - Support for both Material and Cupertino apps - Backwards-compatibility with Navigator API ## Documentation See the API documentation for details on the following topics: - [Getting started](https://pub.dev/documentation/go_router/latest/topics/Get%20started-topic.html) - [Upgrade an existing app](https://pub.dev/documentation/go_router/latest/topics/Upgrading-topic.html) - [Configuration](https://pub.dev/documentation/go_router/latest/topics/Configuration-topic.html) - [Navigation](https://pub.dev/documentation/go_router/latest/topics/Navigation-topic.html) - [Redirection](https://pub.dev/documentation/go_router/latest/topics/Redirection-topic.html) - [Web](https://pub.dev/documentation/go_router/latest/topics/Web-topic.html) - [Deep linking](https://pub.dev/documentation/go_router/latest/topics/Deep%20linking-topic.html) - [Transition animations](https://pub.dev/documentation/go_router/latest/topics/Transition%20animations-topic.html) - [Type-safe routes](https://pub.dev/documentation/go_router/latest/topics/Type-safe%20routes-topic.html) - [Named routes](https://pub.dev/documentation/go_router/latest/topics/Named%20routes-topic.html) - [Error handling](https://pub.dev/documentation/go_router/latest/topics/Error%20handling-topic.html) ## Migration Guides - [Migrating to 13.0.0](https://flutter.dev/go/go-router-v13-breaking-changes). - [Migrating to 12.0.0](https://flutter.dev/go/go-router-v12-breaking-changes). - [Migrating to 11.0.0](https://flutter.dev/go/go-router-v11-breaking-changes). - [Migrating to 10.0.0](https://flutter.dev/go/go-router-v10-breaking-changes). - [Migrating to 9.0.0](https://flutter.dev/go/go-router-v9-breaking-changes). - [Migrating to 8.0.0](https://flutter.dev/go/go-router-v8-breaking-changes). - [Migrating to 7.0.0](https://flutter.dev/go/go-router-v7-breaking-changes). - [Migrating to 6.0.0](https://flutter.dev/go/go-router-v6-breaking-changes) - [Migrating to 5.1.2](https://flutter.dev/go/go-router-v5-1-2-breaking-changes) - [Migrating to 5.0](https://flutter.dev/go/go-router-v5-breaking-changes) - [Migrating to 4.0](https://flutter.dev/go/go-router-v4-breaking-changes) - [Migrating to 3.0](https://flutter.dev/go/go-router-v3-breaking-changes) - [Migrating to 2.5](https://flutter.dev/go/go-router-v2-5-breaking-changes) - [Migrating to 2.0](https://flutter.dev/go/go-router-v2-breaking-changes) ## Changelog See the [Changelog](https://github.com/flutter/packages/blob/main/packages/go_router/CHANGELOG.md) for a list of new features and breaking changes. ## Triage See the [GitHub issues](https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-asc+label%3Ateam-go_router+) for all Go Router issues. The project follows the same priority system as flutter framework. [P0](https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-asc+label%3Ateam-go_router+label%3AP0+) [P1](https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-asc+label%3Ateam-go_router+label%3AP1+) [P2](https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-asc+label%3Ateam-go_router+label%3AP2+) [P3](https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-asc+label%3Ateam-go_router+label%3AP3+) [Package PRs](https://github.com/flutter/packages/pulls?q=is%3Apr+is%3Aopen+label%3A%22p%3A+go_router%22%2C%22p%3A+go_router_builder%22)
packages/packages/go_router/README.md/0
{ "file_path": "packages/packages/go_router/README.md", "repo_id": "packages", "token_count": 1582 }
994
buildFlags: _pluginToolsConfigGlobalKey: - "--no-tree-shake-icons" - "--dart-define=buildmode=testing"
packages/packages/go_router/example/.pluginToolsConfig.yaml/0
{ "file_path": "packages/packages/go_router/example/.pluginToolsConfig.yaml", "repo_id": "packages", "token_count": 45 }
995
// Copyright 2013 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 'book.dart'; /// Author data class. class Author { /// Creates an author data object. Author({ required this.id, required this.name, }); /// The id of the author. final int id; /// The name of the author. final String name; /// The books of the author. final List<Book> books = <Book>[]; }
packages/packages/go_router/example/lib/books/src/data/author.dart/0
{ "file_path": "packages/packages/go_router/example/lib/books/src/data/author.dart", "repo_id": "packages", "token_count": 150 }
996
// Copyright 2013 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:flutter/material.dart'; import 'package:go_router/go_router.dart'; /// This sample app demonstrates how to use GoRoute.onExit. void main() => runApp(const MyApp()); /// The route configuration. final GoRouter _router = GoRouter( routes: <RouteBase>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) { return const HomeScreen(); }, routes: <RouteBase>[ GoRoute( path: 'details', builder: (BuildContext context, GoRouterState state) { return const DetailsScreen(); }, onExit: (BuildContext context) async { final bool? confirmed = await showDialog<bool>( context: context, builder: (_) { return AlertDialog( content: const Text('Are you sure to leave this page?'), actions: <Widget>[ TextButton( onPressed: () => Navigator.of(context).pop(false), child: const Text('Cancel'), ), TextButton( onPressed: () => Navigator.of(context).pop(true), child: const Text('Confirm'), ), ], ); }, ); return confirmed ?? false; }, ), GoRoute( path: 'settings', builder: (BuildContext context, GoRouterState state) { return const SettingsScreen(); }, ), ], ), ], ); /// The main app. class MyApp extends StatelessWidget { /// Constructs a [MyApp] const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp.router( routerConfig: _router, ); } } /// The home screen class HomeScreen extends StatelessWidget { /// Constructs a [HomeScreen] const HomeScreen({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Home Screen')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ElevatedButton( onPressed: () => context.go('/details'), child: const Text('Go to the Details screen'), ), ], ), ), ); } } /// The details screen class DetailsScreen extends StatelessWidget { /// Constructs a [DetailsScreen] const DetailsScreen({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Details Screen')), body: Center( child: Column( children: <Widget>[ TextButton( onPressed: () { context.pop(); }, child: const Text('go back'), ), TextButton( onPressed: () { context.go('/settings'); }, child: const Text('go to settings'), ), ], )), ); } } /// The settings screen class SettingsScreen extends StatelessWidget { /// Constructs a [SettingsScreen] const SettingsScreen({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Settings Screen')), body: const Center( child: Text('Settings'), ), ); } }
packages/packages/go_router/example/lib/on_exit.dart/0
{ "file_path": "packages/packages/go_router/example/lib/on_exit.dart", "repo_id": "packages", "token_count": 1666 }
997
// Copyright 2013 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:flutter/material.dart'; import 'package:go_router/go_router.dart'; final GlobalKey<NavigatorState> _rootNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'root'); final GlobalKey<NavigatorState> _shellNavigatorKey = GlobalKey<NavigatorState>(debugLabel: 'shell'); // This scenario demonstrates how to set up nested navigation using ShellRoute, // which is a pattern where an additional Navigator is placed in the widget tree // to be used instead of the root navigator. This allows deep-links to display // pages along with other UI components such as a BottomNavigationBar. // // This example demonstrates how use topRoute in a ShellRoute to create the // title in the AppBar above the child, which is different for each GoRoute. void main() { runApp(ShellRouteExampleApp()); } /// An example demonstrating how to use [ShellRoute] class ShellRouteExampleApp extends StatelessWidget { /// Creates a [ShellRouteExampleApp] ShellRouteExampleApp({super.key}); final GoRouter _router = GoRouter( navigatorKey: _rootNavigatorKey, initialLocation: '/a', debugLogDiagnostics: true, routes: <RouteBase>[ /// Application shell ShellRoute( navigatorKey: _shellNavigatorKey, builder: (BuildContext context, GoRouterState state, Widget child) { final String? routeName = GoRouterState.of(context).topRoute?.name; // This title could also be created using a route's path parameters in GoRouterState final String title = switch (routeName) { 'a' => 'A Screen', 'a.details' => 'A Details', 'b' => 'B Screen', 'b.details' => 'B Details', 'c' => 'C Screen', 'c.details' => 'C Details', _ => 'Unknown', }; return ScaffoldWithNavBar(title: title, child: child); }, routes: <RouteBase>[ /// The first screen to display in the bottom navigation bar. GoRoute( // The name of this route used to determine the title in the ShellRoute. name: 'a', path: '/a', builder: (BuildContext context, GoRouterState state) { return const ScreenA(); }, routes: <RouteBase>[ // The details screen to display stacked on the inner Navigator. // This will cover screen A but not the application shell. GoRoute( // The name of this route used to determine the title in the ShellRoute. name: 'a.details', path: 'details', builder: (BuildContext context, GoRouterState state) { return const DetailsScreen(label: 'A'); }, ), ], ), /// Displayed when the second item in the the bottom navigation bar is /// selected. GoRoute( // The name of this route used to determine the title in the ShellRoute. name: 'b', path: '/b', builder: (BuildContext context, GoRouterState state) { return const ScreenB(); }, routes: <RouteBase>[ // The details screen to display stacked on the inner Navigator. // This will cover screen B but not the application shell. GoRoute( // The name of this route used to determine the title in the ShellRoute. name: 'b.details', path: 'details', builder: (BuildContext context, GoRouterState state) { return const DetailsScreen(label: 'B'); }, ), ], ), /// The third screen to display in the bottom navigation bar. GoRoute( // The name of this route used to determine the title in the ShellRoute. name: 'c', path: '/c', builder: (BuildContext context, GoRouterState state) { return const ScreenC(); }, routes: <RouteBase>[ // The details screen to display stacked on the inner Navigator. // This will cover screen C but not the application shell. GoRoute( // The name of this route used to determine the title in the ShellRoute. name: 'c.details', path: 'details', builder: (BuildContext context, GoRouterState state) { return const DetailsScreen(label: 'C'); }, ), ], ), ], ), ], ); @override Widget build(BuildContext context) { return MaterialApp.router( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), routerConfig: _router, ); } } /// Builds the "shell" for the app by building a Scaffold with a /// BottomNavigationBar, where [child] is placed in the body of the Scaffold. class ScaffoldWithNavBar extends StatelessWidget { /// Constructs an [ScaffoldWithNavBar]. const ScaffoldWithNavBar({ super.key, required this.title, required this.child, }); /// The title to display in the AppBar. final String title; /// The widget to display in the body of the Scaffold. /// In this sample, it is a Navigator. final Widget child; @override Widget build(BuildContext context) { return Scaffold( body: child, appBar: AppBar( title: Text(title), leading: _buildLeadingButton(context), ), bottomNavigationBar: BottomNavigationBar( items: const <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: Icon(Icons.home), label: 'A Screen', ), BottomNavigationBarItem( icon: Icon(Icons.business), label: 'B Screen', ), BottomNavigationBarItem( icon: Icon(Icons.notification_important_rounded), label: 'C Screen', ), ], currentIndex: _calculateSelectedIndex(context), onTap: (int idx) => _onItemTapped(idx, context), ), ); } /// Builds the app bar leading button using the current location [Uri]. /// /// The [Scaffold]'s default back button cannot be used because it doesn't /// have the context of the current child. Widget? _buildLeadingButton(BuildContext context) { final RouteMatchList currentConfiguration = GoRouter.of(context).routerDelegate.currentConfiguration; final RouteMatch lastMatch = currentConfiguration.last; final Uri location = lastMatch is ImperativeRouteMatch ? lastMatch.matches.uri : currentConfiguration.uri; final bool canPop = location.pathSegments.length > 1; return canPop ? BackButton(onPressed: GoRouter.of(context).pop) : null; } static int _calculateSelectedIndex(BuildContext context) { final String location = GoRouterState.of(context).uri.toString(); if (location.startsWith('/a')) { return 0; } if (location.startsWith('/b')) { return 1; } if (location.startsWith('/c')) { return 2; } return 0; } void _onItemTapped(int index, BuildContext context) { switch (index) { case 0: GoRouter.of(context).go('/a'); case 1: GoRouter.of(context).go('/b'); case 2: GoRouter.of(context).go('/c'); } } } /// The first screen in the bottom navigation bar. class ScreenA extends StatelessWidget { /// Constructs a [ScreenA] widget. const ScreenA({super.key}); @override Widget build(BuildContext context) { return Scaffold( body: Center( child: TextButton( onPressed: () { GoRouter.of(context).go('/a/details'); }, child: const Text('View A details'), ), ), ); } } /// The second screen in the bottom navigation bar. class ScreenB extends StatelessWidget { /// Constructs a [ScreenB] widget. const ScreenB({super.key}); @override Widget build(BuildContext context) { return Scaffold( body: Center( child: TextButton( onPressed: () { GoRouter.of(context).go('/b/details'); }, child: const Text('View B details'), ), ), ); } } /// The third screen in the bottom navigation bar. class ScreenC extends StatelessWidget { /// Constructs a [ScreenC] widget. const ScreenC({super.key}); @override Widget build(BuildContext context) { return Scaffold( body: Center( child: TextButton( onPressed: () { GoRouter.of(context).go('/c/details'); }, child: const Text('View C details'), ), ), ); } } /// The details screen for either the A, B or C screen. class DetailsScreen extends StatelessWidget { /// Constructs a [DetailsScreen]. const DetailsScreen({ required this.label, super.key, }); /// The label to display in the center of the screen. final String label; @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Text( 'Details for $label', style: Theme.of(context).textTheme.headlineMedium, ), ), ); } }
packages/packages/go_router/example/lib/shell_route_top_route.dart/0
{ "file_path": "packages/packages/go_router/example/lib/shell_route_top_route.dart", "repo_id": "packages", "token_count": 3951 }
998
// Copyright 2013 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:flutter_test/flutter_test.dart'; import 'package:go_router_examples/extra_codec.dart' as example; void main() { testWidgets('example works', (WidgetTester tester) async { await tester.pumpWidget(const example.MyApp()); expect(find.text('The extra for this page is: null'), findsOneWidget); await tester.tap(find.text('Set extra to ComplexData1')); await tester.pumpAndSettle(); expect(find.text('The extra for this page is: ComplexData1(data: data)'), findsOneWidget); await tester.tap(find.text('Set extra to ComplexData2')); await tester.pumpAndSettle(); expect(find.text('The extra for this page is: ComplexData2(data: data)'), findsOneWidget); }); test('invalid extra throws', () { const example.MyExtraCodec extraCodec = example.MyExtraCodec(); const List<Object?> invalidValue = <Object?>['invalid']; expect( () => extraCodec.decode(invalidValue), throwsA( predicate( (Object? exception) => exception is FormatException && exception.message == 'Unable to parse input: $invalidValue', ), ), ); }); }
packages/packages/go_router/example/test/extra_codec_test.dart/0
{ "file_path": "packages/packages/go_router/example/test/extra_codec_test.dart", "repo_id": "packages", "token_count": 491 }
999
// Copyright 2013 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:flutter/widgets.dart'; import 'configuration.dart'; import 'logging.dart'; import 'match.dart'; import 'misc/error_screen.dart'; import 'misc/errors.dart'; import 'pages/cupertino.dart'; import 'pages/custom_transition_page.dart'; import 'pages/material.dart'; import 'route.dart'; import 'route_data.dart'; import 'state.dart'; /// Signature of a go router builder function with navigator. typedef GoRouterBuilderWithNav = Widget Function( BuildContext context, Widget child, ); typedef _PageBuilderForAppType = Page<void> Function({ required LocalKey key, required String? name, required Object? arguments, required String restorationId, required Widget child, }); typedef _ErrorBuilderForAppType = Widget Function( BuildContext context, GoRouterState state, ); /// Signature for a function that takes in a `route` to be popped with /// the `result` and returns a boolean decision on whether the pop /// is successful. /// /// The `match` is the corresponding [RouteMatch] the `route` /// associates with. /// /// Used by of [RouteBuilder.onPopPageWithRouteMatch]. typedef PopPageWithRouteMatchCallback = bool Function( Route<dynamic> route, dynamic result, RouteMatchBase match); /// Builds the top-level Navigator for GoRouter. class RouteBuilder { /// [RouteBuilder] constructor. RouteBuilder({ required this.configuration, required this.builderWithNav, required this.errorPageBuilder, required this.errorBuilder, required this.restorationScopeId, required this.observers, required this.onPopPageWithRouteMatch, this.requestFocus = true, }); /// Builder function for a go router with Navigator. final GoRouterBuilderWithNav builderWithNav; /// Error page builder for the go router delegate. final GoRouterPageBuilder? errorPageBuilder; /// Error widget builder for the go router delegate. final GoRouterWidgetBuilder? errorBuilder; /// The route configuration for the app. final RouteConfiguration configuration; /// Restoration ID to save and restore the state of the navigator, including /// its history. final String? restorationScopeId; /// Whether or not the navigator created by this builder and it's new topmost route should request focus /// when the new route is pushed onto the navigator. /// /// Defaults to true. final bool requestFocus; /// NavigatorObserver used to receive notifications when navigating in between routes. /// changes. final List<NavigatorObserver> observers; /// A callback called when a `route` produced by `match` is about to be popped /// with the `result`. /// /// If this method returns true, this builder pops the `route` and `match`. /// /// If this method returns false, this builder aborts the pop. final PopPageWithRouteMatchCallback onPopPageWithRouteMatch; /// Builds the top-level Navigator for the given [RouteMatchList]. Widget build( BuildContext context, RouteMatchList matchList, bool routerNeglect, ) { if (matchList.isEmpty && !matchList.isError) { // The build method can be called before async redirect finishes. Build a // empty box until then. return const SizedBox.shrink(); } assert(matchList.isError || !matchList.last.route.redirectOnly); return builderWithNav( context, _CustomNavigator( navigatorKey: configuration.navigatorKey, observers: observers, navigatorRestorationId: restorationScopeId, onPopPageWithRouteMatch: onPopPageWithRouteMatch, matchList: matchList, matches: matchList.matches, configuration: configuration, errorBuilder: errorBuilder, errorPageBuilder: errorPageBuilder, ), ); } } class _CustomNavigator extends StatefulWidget { const _CustomNavigator({ super.key, required this.navigatorKey, required this.observers, required this.navigatorRestorationId, required this.onPopPageWithRouteMatch, required this.matchList, required this.matches, required this.configuration, required this.errorBuilder, required this.errorPageBuilder, }); final GlobalKey<NavigatorState> navigatorKey; final List<NavigatorObserver> observers; /// The actual [RouteMatchBase]s to be built. /// /// This can be different from matches in [matchList] if this widget is used /// to build navigator in shell route. In this case, these matches come from /// the [ShellRouteMatch.matches]. final List<RouteMatchBase> matches; final RouteMatchList matchList; final RouteConfiguration configuration; final PopPageWithRouteMatchCallback onPopPageWithRouteMatch; final String? navigatorRestorationId; final GoRouterWidgetBuilder? errorBuilder; final GoRouterPageBuilder? errorPageBuilder; @override State<StatefulWidget> createState() => _CustomNavigatorState(); } class _CustomNavigatorState extends State<_CustomNavigator> { HeroController? _controller; late Map<Page<Object?>, RouteMatchBase> _pageToRouteMatchBase; final GoRouterStateRegistry _registry = GoRouterStateRegistry(); List<Page<Object?>>? _pages; @override void didUpdateWidget(_CustomNavigator oldWidget) { super.didUpdateWidget(oldWidget); if (widget.matchList != oldWidget.matchList) { _pages = null; } } @override void didChangeDependencies() { super.didChangeDependencies(); // Create a HeroController based on the app type. if (_controller == null) { if (isMaterialApp(context)) { _controller = createMaterialHeroController(); } else if (isCupertinoApp(context)) { _controller = createCupertinoHeroController(); } else { _controller = HeroController(); } } // This method can also be called if any of the page builders depend on // the context. In this case, make sure _pages are rebuilt. _pages = null; } @override void dispose() { _controller?.dispose(); _registry.dispose(); super.dispose(); } void _updatePages(BuildContext context) { assert(_pages == null); final List<Page<Object?>> pages = <Page<Object?>>[]; final Map<Page<Object?>, RouteMatchBase> pageToRouteMatchBase = <Page<Object?>, RouteMatchBase>{}; final Map<Page<Object?>, GoRouterState> registry = <Page<Object?>, GoRouterState>{}; if (widget.matchList.isError) { pages.add(_buildErrorPage(context, widget.matchList)); } else { for (final RouteMatchBase match in widget.matches) { final Page<Object?>? page = _buildPage(context, match); if (page == null) { continue; } pages.add(page); pageToRouteMatchBase[page] = match; registry[page] = match.buildState(widget.configuration, widget.matchList); } } _pages = pages; _registry.updateRegistry(registry); _pageToRouteMatchBase = pageToRouteMatchBase; } Page<Object?>? _buildPage(BuildContext context, RouteMatchBase match) { if (match is RouteMatch) { if (match is ImperativeRouteMatch && match.matches.isError) { return _buildErrorPage(context, match.matches); } return _buildPageForGoRoute(context, match); } if (match is ShellRouteMatch) { return _buildPageForShellRoute(context, match); } throw GoError('unknown match type ${match.runtimeType}'); } /// Builds a [Page] for a [RouteMatch] Page<Object?>? _buildPageForGoRoute(BuildContext context, RouteMatch match) { final GoRouterPageBuilder? pageBuilder = match.route.pageBuilder; final GoRouterState state = match.buildState(widget.configuration, widget.matchList); if (pageBuilder != null) { final Page<Object?> page = pageBuilder(context, state); if (page is! NoOpPage) { return page; } } final GoRouterWidgetBuilder? builder = match.route.builder; if (builder == null) { return null; } return _buildPlatformAdapterPage(context, state, Builder(builder: (BuildContext context) { return builder(context, state); })); } /// Builds a [Page] for a [ShellRouteMatch] Page<Object?> _buildPageForShellRoute( BuildContext context, ShellRouteMatch match, ) { final GoRouterState state = match.buildState(widget.configuration, widget.matchList); final GlobalKey<NavigatorState> navigatorKey = match.navigatorKey; final ShellRouteContext shellRouteContext = ShellRouteContext( route: match.route, routerState: state, navigatorKey: navigatorKey, routeMatchList: widget.matchList, navigatorBuilder: (List<NavigatorObserver>? observers, String? restorationScopeId) { return _CustomNavigator( // The state needs to persist across rebuild. key: GlobalObjectKey(navigatorKey.hashCode), navigatorRestorationId: restorationScopeId, navigatorKey: navigatorKey, matches: match.matches, matchList: widget.matchList, configuration: widget.configuration, observers: observers ?? const <NavigatorObserver>[], onPopPageWithRouteMatch: widget.onPopPageWithRouteMatch, // This is used to recursively build pages under this shell route. errorBuilder: widget.errorBuilder, errorPageBuilder: widget.errorPageBuilder, ); }, ); final Page<Object?>? page = match.route.buildPage(context, state, shellRouteContext); if (page != null && page is! NoOpPage) { return page; } // Return the result of the route's builder() or pageBuilder() return _buildPlatformAdapterPage( context, state, Builder( builder: (BuildContext context) { return match.route.buildWidget(context, state, shellRouteContext)!; }, ), ); } _PageBuilderForAppType? _pageBuilderForAppType; _ErrorBuilderForAppType? _errorBuilderForAppType; void _cacheAppType(BuildContext context) { // cache app type-specific page and error builders if (_pageBuilderForAppType == null) { assert(_errorBuilderForAppType == null); // can be null during testing final Element? elem = context is Element ? context : null; if (elem != null && isMaterialApp(elem)) { log('Using MaterialApp configuration'); _pageBuilderForAppType = pageBuilderForMaterialApp; _errorBuilderForAppType = (BuildContext c, GoRouterState s) => MaterialErrorScreen(s.error); } else if (elem != null && isCupertinoApp(elem)) { log('Using CupertinoApp configuration'); _pageBuilderForAppType = pageBuilderForCupertinoApp; _errorBuilderForAppType = (BuildContext c, GoRouterState s) => CupertinoErrorScreen(s.error); } else { log('Using WidgetsApp configuration'); _pageBuilderForAppType = ({ required LocalKey key, required String? name, required Object? arguments, required String restorationId, required Widget child, }) => NoTransitionPage<void>( name: name, arguments: arguments, key: key, restorationId: restorationId, child: child, ); _errorBuilderForAppType = (BuildContext c, GoRouterState s) => ErrorScreen(s.error); } } assert(_pageBuilderForAppType != null); assert(_errorBuilderForAppType != null); } /// builds the page based on app type, i.e. MaterialApp vs. CupertinoApp Page<Object?> _buildPlatformAdapterPage( BuildContext context, GoRouterState state, Widget child, ) { // build the page based on app type _cacheAppType(context); return _pageBuilderForAppType!( key: state.pageKey, name: state.name ?? state.path, arguments: <String, String>{ ...state.pathParameters, ...state.uri.queryParameters }, restorationId: state.pageKey.value, child: child, ); } GoRouterState _buildErrorState(RouteMatchList matchList) { assert(matchList.isError); return GoRouterState( widget.configuration, uri: matchList.uri, matchedLocation: matchList.uri.path, fullPath: matchList.fullPath, pathParameters: matchList.pathParameters, error: matchList.error, pageKey: ValueKey<String>('${matchList.uri}(error)'), topRoute: matchList.lastOrNull?.route, ); } /// Builds a an error page. Page<void> _buildErrorPage(BuildContext context, RouteMatchList matchList) { final GoRouterState state = _buildErrorState(matchList); assert(state.error != null); // If the error page builder is provided, use that, otherwise, if the error // builder is provided, wrap that in an app-specific page (for example, // MaterialPage). Finally, if nothing is provided, use a default error page // wrapped in the app-specific page. _cacheAppType(context); final GoRouterWidgetBuilder? errorBuilder = widget.errorBuilder; return widget.errorPageBuilder != null ? widget.errorPageBuilder!(context, state) : _buildPlatformAdapterPage( context, state, errorBuilder != null ? errorBuilder(context, state) : _errorBuilderForAppType!(context, state), ); } bool _handlePopPage(Route<Object?> route, Object? result) { final Page<Object?> page = route.settings as Page<Object?>; final RouteMatchBase match = _pageToRouteMatchBase[page]!; return widget.onPopPageWithRouteMatch(route, result, match); } @override Widget build(BuildContext context) { if (_pages == null) { _updatePages(context); } assert(_pages != null); return GoRouterStateRegistryScope( registry: _registry, child: HeroControllerScope( controller: _controller!, child: Navigator( key: widget.navigatorKey, restorationScopeId: widget.navigatorRestorationId, pages: _pages!, observers: widget.observers, onPopPage: _handlePopPage, ), ), ); } }
packages/packages/go_router/lib/src/builder.dart/0
{ "file_path": "packages/packages/go_router/lib/src/builder.dart", "repo_id": "packages", "token_count": 5112 }
1,000
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:flutter/widgets.dart'; import 'package:meta/meta.dart'; import 'package:meta/meta_meta.dart'; import 'route.dart'; import 'state.dart'; /// Baseclass for supporting /// [Type-safe routing](https://pub.dev/documentation/go_router/latest/topics/Type-safe%20routes-topic.html). abstract class RouteData { /// Allows subclasses to have `const` constructors. const RouteData(); } /// A class to represent a [GoRoute] in /// [Type-safe routing](https://pub.dev/documentation/go_router/latest/topics/Type-safe%20routes-topic.html). /// /// Subclasses must override one of [build], [buildPage], or /// [redirect]. /// {@category Type-safe routes} abstract class GoRouteData extends RouteData { /// Allows subclasses to have `const` constructors. /// /// [GoRouteData] is abstract and cannot be instantiated directly. const GoRouteData(); /// Creates the [Widget] for `this` route. /// /// Subclasses must override one of [build], [buildPage], or /// [redirect]. /// /// Corresponds to [GoRoute.builder]. Widget build(BuildContext context, GoRouterState state) => throw UnimplementedError( 'One of `build` or `buildPage` must be implemented.', ); /// A page builder for this route. /// /// Subclasses can override this function to provide a custom [Page]. /// /// Subclasses must override one of [build], [buildPage] or /// [redirect]. /// /// Corresponds to [GoRoute.pageBuilder]. /// /// By default, returns a [Page] instance that is ignored, causing a default /// [Page] implementation to be used with the results of [build]. Page<void> buildPage(BuildContext context, GoRouterState state) => const NoOpPage(); /// An optional redirect function for this route. /// /// Subclasses must override one of [build], [buildPage], or /// [redirect]. /// /// Corresponds to [GoRoute.redirect]. FutureOr<String?> redirect(BuildContext context, GoRouterState state) => null; /// A helper function used by generated code. /// /// Should not be used directly. static String $location(String path, {Map<String, dynamic>? queryParams}) => Uri.parse(path) .replace( queryParameters: // Avoid `?` in generated location if `queryParams` is empty queryParams?.isNotEmpty ?? false ? queryParams : null, ) .toString(); /// A helper function used by generated code. /// /// Should not be used directly. static GoRoute $route<T extends GoRouteData>({ required String path, String? name, required T Function(GoRouterState) factory, GlobalKey<NavigatorState>? parentNavigatorKey, List<RouteBase> routes = const <RouteBase>[], }) { T factoryImpl(GoRouterState state) { final Object? extra = state.extra; // If the "extra" value is of type `T` then we know it's the source // instance of `GoRouteData`, so it doesn't need to be recreated. if (extra is T) { return extra; } return (_stateObjectExpando[state] ??= factory(state)) as T; } Widget builder(BuildContext context, GoRouterState state) => factoryImpl(state).build(context, state); Page<void> pageBuilder(BuildContext context, GoRouterState state) => factoryImpl(state).buildPage(context, state); FutureOr<String?> redirect(BuildContext context, GoRouterState state) => factoryImpl(state).redirect(context, state); return GoRoute( path: path, name: name, builder: builder, pageBuilder: pageBuilder, redirect: redirect, routes: routes, parentNavigatorKey: parentNavigatorKey, ); } /// Used to cache [GoRouteData] that corresponds to a given [GoRouterState] /// to minimize the number of times it has to be deserialized. static final Expando<GoRouteData> _stateObjectExpando = Expando<GoRouteData>( 'GoRouteState to GoRouteData expando', ); } /// A class to represent a [ShellRoute] in /// [Type-safe routing](https://pub.dev/documentation/go_router/latest/topics/Type-safe%20routes-topic.html). abstract class ShellRouteData extends RouteData { /// Allows subclasses to have `const` constructors. /// /// [ShellRouteData] is abstract and cannot be instantiated directly. const ShellRouteData(); /// [pageBuilder] is used to build the page Page<void> pageBuilder( BuildContext context, GoRouterState state, Widget navigator, ) => const NoOpPage(); /// [builder] is used to build the widget Widget builder( BuildContext context, GoRouterState state, Widget navigator, ) => throw UnimplementedError( 'One of `builder` or `pageBuilder` must be implemented.', ); /// A helper function used by generated code. /// /// Should not be used directly. static ShellRoute $route<T extends ShellRouteData>({ required T Function(GoRouterState) factory, GlobalKey<NavigatorState>? navigatorKey, GlobalKey<NavigatorState>? parentNavigatorKey, List<RouteBase> routes = const <RouteBase>[], List<NavigatorObserver>? observers, String? restorationScopeId, }) { T factoryImpl(GoRouterState state) { return (_stateObjectExpando[state] ??= factory(state)) as T; } Widget builder( BuildContext context, GoRouterState state, Widget navigator, ) => factoryImpl(state).builder( context, state, navigator, ); Page<void> pageBuilder( BuildContext context, GoRouterState state, Widget navigator, ) => factoryImpl(state).pageBuilder( context, state, navigator, ); return ShellRoute( builder: builder, pageBuilder: pageBuilder, parentNavigatorKey: parentNavigatorKey, routes: routes, navigatorKey: navigatorKey, observers: observers, restorationScopeId: restorationScopeId, ); } /// Used to cache [ShellRouteData] that corresponds to a given [GoRouterState] /// to minimize the number of times it has to be deserialized. static final Expando<ShellRouteData> _stateObjectExpando = Expando<ShellRouteData>( 'GoRouteState to ShellRouteData expando', ); } /// Base class for supporting /// [StatefulShellRoute](https://pub.dev/documentation/go_router/latest/go_router/StatefulShellRoute-class.html) abstract class StatefulShellRouteData extends RouteData { /// Default const constructor const StatefulShellRouteData(); /// [pageBuilder] is used to build the page Page<void> pageBuilder( BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell, ) => const NoOpPage(); /// [builder] is used to build the widget Widget builder( BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell, ) => throw UnimplementedError( 'One of `builder` or `pageBuilder` must be implemented.', ); /// A helper function used by generated code. /// /// Should not be used directly. static StatefulShellRoute $route<T extends StatefulShellRouteData>({ required T Function(GoRouterState) factory, required List<StatefulShellBranch> branches, GlobalKey<NavigatorState>? parentNavigatorKey, ShellNavigationContainerBuilder? navigatorContainerBuilder, String? restorationScopeId, }) { T factoryImpl(GoRouterState state) { return (_stateObjectExpando[state] ??= factory(state)) as T; } Widget builder( BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell, ) => factoryImpl(state).builder( context, state, navigationShell, ); Page<void> pageBuilder( BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell, ) => factoryImpl(state).pageBuilder( context, state, navigationShell, ); if (navigatorContainerBuilder != null) { return StatefulShellRoute( branches: branches, builder: builder, pageBuilder: pageBuilder, navigatorContainerBuilder: navigatorContainerBuilder, parentNavigatorKey: parentNavigatorKey, restorationScopeId: restorationScopeId, ); } return StatefulShellRoute.indexedStack( branches: branches, builder: builder, pageBuilder: pageBuilder, parentNavigatorKey: parentNavigatorKey, restorationScopeId: restorationScopeId, ); } /// Used to cache [StatefulShellRouteData] that corresponds to a given [GoRouterState] /// to minimize the number of times it has to be deserialized. static final Expando<StatefulShellRouteData> _stateObjectExpando = Expando<StatefulShellRouteData>( 'GoRouteState to StatefulShellRouteData expando', ); } /// Base class for supporting /// [StatefulShellRoute](https://pub.dev/documentation/go_router/latest/go_router/StatefulShellRoute-class.html) abstract class StatefulShellBranchData { /// Default const constructor const StatefulShellBranchData(); /// A helper function used by generated code. /// /// Should not be used directly. static StatefulShellBranch $branch<T extends StatefulShellBranchData>({ GlobalKey<NavigatorState>? navigatorKey, List<RouteBase> routes = const <RouteBase>[], List<NavigatorObserver>? observers, String? initialLocation, String? restorationScopeId, }) { return StatefulShellBranch( routes: routes, navigatorKey: navigatorKey, observers: observers, initialLocation: initialLocation, restorationScopeId: restorationScopeId, ); } } /// A superclass for each typed route descendant class TypedRoute<T extends RouteData> { /// Default const constructor const TypedRoute(); } /// A superclass for each typed go route descendant @Target(<TargetKind>{TargetKind.library, TargetKind.classType}) class TypedGoRoute<T extends GoRouteData> extends TypedRoute<T> { /// Default const constructor const TypedGoRoute({ required this.path, this.name, this.routes = const <TypedRoute<RouteData>>[], }); /// The path that corresponds to this route. /// /// See [GoRoute.path]. /// /// final String path; /// The name that corresponds to this route. /// Used by Analytics services such as Firebase Analytics /// to log the screen views in their system. /// /// See [GoRoute.name]. /// final String? name; /// Child route definitions. /// /// See [RouteBase.routes]. final List<TypedRoute<RouteData>> routes; } /// A superclass for each typed shell route descendant @Target(<TargetKind>{TargetKind.library, TargetKind.classType}) class TypedShellRoute<T extends ShellRouteData> extends TypedRoute<T> { /// Default const constructor const TypedShellRoute({ this.routes = const <TypedRoute<RouteData>>[], }); /// Child route definitions. /// /// See [RouteBase.routes]. final List<TypedRoute<RouteData>> routes; } /// A superclass for each typed shell route descendant @Target(<TargetKind>{TargetKind.library, TargetKind.classType}) class TypedStatefulShellRoute<T extends StatefulShellRouteData> extends TypedRoute<T> { /// Default const constructor const TypedStatefulShellRoute({ this.branches = const <TypedStatefulShellBranch<StatefulShellBranchData>>[], }); /// Child route definitions. /// /// See [RouteBase.routes]. final List<TypedStatefulShellBranch<StatefulShellBranchData>> branches; } /// A superclass for each typed shell route descendant @Target(<TargetKind>{TargetKind.library, TargetKind.classType}) class TypedStatefulShellBranch<T extends StatefulShellBranchData> { /// Default const constructor const TypedStatefulShellBranch({ this.routes = const <TypedRoute<RouteData>>[], }); /// Child route definitions. /// /// See [RouteBase.routes]. final List<TypedRoute<RouteData>> routes; } /// Internal class used to signal that the default page behavior should be used. @internal class NoOpPage extends Page<void> { /// Creates an instance of NoOpPage; const NoOpPage(); @override Route<void> createRoute(BuildContext context) => throw UnsupportedError('Should never be called'); }
packages/packages/go_router/lib/src/route_data.dart/0
{ "file_path": "packages/packages/go_router/lib/src/route_data.dart", "repo_id": "packages", "token_count": 4212 }
1,001
// Copyright 2013 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. // ignore_for_file: cascade_invocations, diagnostic_describe_all_properties, unawaited_futures import 'dart:async'; import 'package:collection/collection.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import 'package:go_router/src/match.dart'; import 'package:logging/logging.dart'; import 'test_helpers.dart'; const bool enableLogs = false; final Logger log = Logger('GoRouter tests'); Future<void> sendPlatformUrl(String url, WidgetTester tester) async { final Map<String, dynamic> testRouteInformation = <String, dynamic>{ 'location': url, }; final ByteData message = const JSONMethodCodec().encodeMethodCall( MethodCall('pushRouteInformation', testRouteInformation), ); await tester.binding.defaultBinaryMessenger .handlePlatformMessage('flutter/navigation', message, (_) {}); } void main() { if (enableLogs) { Logger.root.onRecord.listen((LogRecord e) => debugPrint('$e')); } group('path routes', () { testWidgets('match home route', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen()), ]; final GoRouter router = await createRouter(routes, tester); final RouteMatchList matches = router.routerDelegate.currentConfiguration; expect(matches.matches, hasLength(1)); expect(matches.uri.toString(), '/'); expect(find.byType(HomeScreen), findsOneWidget); }); testWidgets('If there is more than one route to match, use the first match', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute(name: '1', path: '/', builder: dummy), GoRoute(name: '2', path: '/', builder: dummy), ]; final GoRouter router = await createRouter(routes, tester); router.go('/'); final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(1)); expect((matches.first.route as GoRoute).name, '1'); expect(find.byType(DummyScreen), findsOneWidget); }); test('empty path', () { expect(() { GoRoute(path: ''); }, throwsA(isAssertionError)); }); test('leading / on sub-route', () { expect(() { GoRouter( routes: <RouteBase>[ GoRoute( path: '/', builder: dummy, routes: <GoRoute>[ GoRoute( path: '/foo', builder: dummy, ), ], ), ], ); }, throwsA(isAssertionError)); }); test('trailing / on sub-route', () { expect(() { GoRouter( routes: <RouteBase>[ GoRoute( path: '/', builder: dummy, routes: <GoRoute>[ GoRoute( path: 'foo/', builder: dummy, ), ], ), ], ); }, throwsA(isAssertionError)); }); testWidgets('lack of leading / on top-level route', (WidgetTester tester) async { await expectLater(() async { final List<GoRoute> routes = <GoRoute>[ GoRoute(path: 'foo', builder: dummy), ]; await createRouter(routes, tester); }, throwsA(isAssertionError)); }); testWidgets('match no routes', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute(path: '/', builder: dummy), ]; final GoRouter router = await createRouter( routes, tester, errorBuilder: (BuildContext context, GoRouterState state) => TestErrorScreen(state.error!), ); router.go('/foo'); await tester.pumpAndSettle(); final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(0)); expect(find.byType(TestErrorScreen), findsOneWidget); }); testWidgets('match 2nd top level route', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen()), GoRoute( path: '/login', builder: (BuildContext context, GoRouterState state) => const LoginScreen()), ]; final GoRouter router = await createRouter(routes, tester); router.go('/login'); await tester.pumpAndSettle(); final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(1)); expect(matches.first.matchedLocation, '/login'); expect(find.byType(LoginScreen), findsOneWidget); }); testWidgets('match 2nd top level route with subroutes', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: <GoRoute>[ GoRoute( path: 'page1', builder: (BuildContext context, GoRouterState state) => const Page1Screen()) ], ), GoRoute( path: '/login', builder: (BuildContext context, GoRouterState state) => const LoginScreen()), ]; final GoRouter router = await createRouter(routes, tester); router.go('/login'); await tester.pumpAndSettle(); final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(1)); expect(matches.first.matchedLocation, '/login'); expect(find.byType(LoginScreen), findsOneWidget); }); testWidgets('match top level route when location has trailing /', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/login', builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ]; final GoRouter router = await createRouter(routes, tester); router.go('/login/'); await tester.pumpAndSettle(); final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(1)); expect(matches.first.matchedLocation, '/login'); expect(find.byType(LoginScreen), findsOneWidget); }); testWidgets('match top level route when location has trailing / (2)', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/profile', builder: dummy, redirect: (_, __) => '/profile/foo'), GoRoute(path: '/profile/:kind', builder: dummy), ]; final GoRouter router = await createRouter(routes, tester); router.go('/profile/'); await tester.pumpAndSettle(); final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(1)); expect(matches.first.matchedLocation, '/profile/foo'); expect(find.byType(DummyScreen), findsOneWidget); }); testWidgets('match top level route when location has trailing / (3)', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/profile', builder: dummy, redirect: (_, __) => '/profile/foo'), GoRoute(path: '/profile/:kind', builder: dummy), ]; final GoRouter router = await createRouter(routes, tester); router.go('/profile/?bar=baz'); await tester.pumpAndSettle(); final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(1)); expect(matches.first.matchedLocation, '/profile/foo'); expect(find.byType(DummyScreen), findsOneWidget); }); testWidgets( 'match top level route when location has scheme/host and has trailing /', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), ]; final GoRouter router = await createRouter(routes, tester); router.go('https://www.domain.com/?bar=baz'); await tester.pumpAndSettle(); final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(1)); expect(matches.first.matchedLocation, '/'); expect(find.byType(HomeScreen), findsOneWidget); }); testWidgets( 'match top level route when location has scheme/host and has trailing / (2)', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/login', builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ]; final GoRouter router = await createRouter(routes, tester); router.go('https://www.domain.com/login/'); await tester.pumpAndSettle(); final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(1)); expect(matches.first.matchedLocation, '/login'); expect(find.byType(LoginScreen), findsOneWidget); }); testWidgets( 'match top level route when location has scheme/host and has trailing / (3)', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/profile', builder: dummy, redirect: (_, __) => '/profile/foo'), GoRoute(path: '/profile/:kind', builder: dummy), ]; final GoRouter router = await createRouter(routes, tester); router.go('https://www.domain.com/profile/'); await tester.pumpAndSettle(); final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(1)); expect(matches.first.matchedLocation, '/profile/foo'); expect(find.byType(DummyScreen), findsOneWidget); }); testWidgets( 'match top level route when location has scheme/host and has trailing / (4)', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/profile', builder: dummy, redirect: (_, __) => '/profile/foo'), GoRoute(path: '/profile/:kind', builder: dummy), ]; final GoRouter router = await createRouter(routes, tester); router.go('https://www.domain.com/profile/?bar=baz'); await tester.pumpAndSettle(); final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(1)); expect(matches.first.matchedLocation, '/profile/foo'); expect(find.byType(DummyScreen), findsOneWidget); }); testWidgets('repeatedly pops imperative route does not crash', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/123369. final UniqueKey home = UniqueKey(); final UniqueKey settings = UniqueKey(); final UniqueKey dialog = UniqueKey(); final GlobalKey<NavigatorState> navKey = GlobalKey<NavigatorState>(); final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (_, __) => DummyScreen(key: home), ), GoRoute( path: '/settings', builder: (_, __) => DummyScreen(key: settings), ), ]; final GoRouter router = await createRouter(routes, tester, navigatorKey: navKey); expect(find.byKey(home), findsOneWidget); router.push('/settings'); await tester.pumpAndSettle(); expect(find.byKey(home), findsNothing); expect(find.byKey(settings), findsOneWidget); showDialog<void>( context: navKey.currentContext!, builder: (_) => DummyScreen(key: dialog), ); await tester.pumpAndSettle(); expect(find.byKey(dialog), findsOneWidget); router.pop(); await tester.pumpAndSettle(); expect(find.byKey(dialog), findsNothing); expect(find.byKey(settings), findsOneWidget); showDialog<void>( context: navKey.currentContext!, builder: (_) => DummyScreen(key: dialog), ); await tester.pumpAndSettle(); expect(find.byKey(dialog), findsOneWidget); router.pop(); await tester.pumpAndSettle(); expect(find.byKey(dialog), findsNothing); expect(find.byKey(settings), findsOneWidget); }); testWidgets('can correctly pop stacks of repeated pages', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/#132229. final GlobalKey<NavigatorState> navKey = GlobalKey<NavigatorState>(); final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', pageBuilder: (_, __) => const MaterialPage<Object>(child: HomeScreen()), ), GoRoute( path: '/page1', pageBuilder: (_, __) => const MaterialPage<Object>(child: Page1Screen()), ), GoRoute( path: '/page2', pageBuilder: (_, __) => const MaterialPage<Object>(child: Page2Screen()), ), ]; final GoRouter router = await createRouter(routes, tester, navigatorKey: navKey); expect(find.byType(HomeScreen), findsOneWidget); router.push('/page1'); router.push('/page2'); router.push('/page1'); router.push('/page2'); await tester.pumpAndSettle(); expect(find.byType(HomeScreen), findsNothing); expect(find.byType(Page1Screen), findsNothing); expect(find.byType(Page2Screen), findsOneWidget); router.pop(); await tester.pumpAndSettle(); final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches; expect(matches.length, 4); expect(find.byType(HomeScreen), findsNothing); expect(find.byType(Page1Screen), findsOneWidget); expect(find.byType(Page2Screen), findsNothing); }); testWidgets('match sub-route', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: <GoRoute>[ GoRoute( path: 'login', builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ], ), ]; final GoRouter router = await createRouter(routes, tester); router.go('/login'); await tester.pumpAndSettle(); final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches; expect(matches.length, 2); expect(matches.first.matchedLocation, '/'); expect(find.byType(HomeScreen, skipOffstage: false), findsOneWidget); expect(matches[1].matchedLocation, '/login'); expect(find.byType(LoginScreen), findsOneWidget); }); testWidgets('match sub-routes', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: <GoRoute>[ GoRoute( path: 'family/:fid', builder: (BuildContext context, GoRouterState state) => const FamilyScreen('dummy'), routes: <GoRoute>[ GoRoute( path: 'person/:pid', builder: (BuildContext context, GoRouterState state) => const PersonScreen('dummy', 'dummy'), ), ], ), GoRoute( path: 'login', builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ], ), ]; final GoRouter router = await createRouter(routes, tester); { final RouteMatchList matches = router.routerDelegate.currentConfiguration; expect(matches.matches, hasLength(1)); expect(matches.uri.toString(), '/'); expect(find.byType(HomeScreen), findsOneWidget); } router.go('/login'); await tester.pumpAndSettle(); { final RouteMatchList matches = router.routerDelegate.currentConfiguration; expect(matches.matches.length, 2); expect(matches.matches.first.matchedLocation, '/'); expect(find.byType(HomeScreen, skipOffstage: false), findsOneWidget); expect(matches.matches[1].matchedLocation, '/login'); expect(find.byType(LoginScreen), findsOneWidget); } router.go('/family/f2'); await tester.pumpAndSettle(); { final RouteMatchList matches = router.routerDelegate.currentConfiguration; expect(matches.matches.length, 2); expect(matches.matches.first.matchedLocation, '/'); expect(find.byType(HomeScreen, skipOffstage: false), findsOneWidget); expect(matches.matches[1].matchedLocation, '/family/f2'); expect(find.byType(FamilyScreen), findsOneWidget); } router.go('/family/f2/person/p1'); await tester.pumpAndSettle(); { final RouteMatchList matches = router.routerDelegate.currentConfiguration; expect(matches.matches.length, 3); expect(matches.matches.first.matchedLocation, '/'); expect(find.byType(HomeScreen, skipOffstage: false), findsOneWidget); expect(matches.matches[1].matchedLocation, '/family/f2'); expect(find.byType(FamilyScreen, skipOffstage: false), findsOneWidget); expect(matches.matches[2].matchedLocation, '/family/f2/person/p1'); expect(find.byType(PersonScreen), findsOneWidget); } }); testWidgets('return first matching route if too many subroutes', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: <GoRoute>[ GoRoute( path: 'foo/bar', builder: (BuildContext context, GoRouterState state) => const FamilyScreen(''), ), GoRoute( path: 'bar', builder: (BuildContext context, GoRouterState state) => const Page1Screen(), ), GoRoute( path: 'foo', builder: (BuildContext context, GoRouterState state) => const Page2Screen(), routes: <GoRoute>[ GoRoute( path: 'bar', builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ], ), ], ), ]; final GoRouter router = await createRouter(routes, tester); router.go('/bar'); await tester.pumpAndSettle(); List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(2)); expect(find.byType(Page1Screen), findsOneWidget); router.go('/foo/bar'); await tester.pumpAndSettle(); matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(2)); expect(find.byType(FamilyScreen), findsOneWidget); router.go('/foo'); await tester.pumpAndSettle(); matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(2)); expect(find.byType(Page2Screen), findsOneWidget); }); testWidgets('router state', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( name: 'home', path: '/', builder: (BuildContext context, GoRouterState state) { expect(state.uri.toString(), '/'); expect(state.matchedLocation, '/'); expect(state.name, 'home'); expect(state.path, '/'); expect(state.fullPath, '/'); expect(state.pathParameters, <String, String>{}); expect(state.error, null); if (state.extra != null) { expect(state.extra! as int, 1); } return const HomeScreen(); }, routes: <GoRoute>[ GoRoute( name: 'login', path: 'login', builder: (BuildContext context, GoRouterState state) { expect(state.uri.toString(), '/login'); expect(state.matchedLocation, '/login'); expect(state.name, 'login'); expect(state.path, 'login'); expect(state.fullPath, '/login'); expect(state.pathParameters, <String, String>{}); expect(state.error, null); expect(state.extra! as int, 2); return const LoginScreen(); }, ), GoRoute( name: 'family', path: 'family/:fid', builder: (BuildContext context, GoRouterState state) { expect( state.uri.toString(), anyOf(<String>['/family/f2', '/family/f2/person/p1']), ); expect(state.matchedLocation, '/family/f2'); expect(state.name, 'family'); expect(state.path, 'family/:fid'); expect(state.fullPath, '/family/:fid'); expect(state.pathParameters, <String, String>{'fid': 'f2'}); expect(state.error, null); expect(state.extra! as int, 3); return FamilyScreen(state.pathParameters['fid']!); }, routes: <GoRoute>[ GoRoute( name: 'person', path: 'person/:pid', builder: (BuildContext context, GoRouterState state) { expect(state.uri.toString(), '/family/f2/person/p1'); expect(state.matchedLocation, '/family/f2/person/p1'); expect(state.name, 'person'); expect(state.path, 'person/:pid'); expect(state.fullPath, '/family/:fid/person/:pid'); expect( state.pathParameters, <String, String>{'fid': 'f2', 'pid': 'p1'}, ); expect(state.error, null); expect(state.extra! as int, 4); return PersonScreen(state.pathParameters['fid']!, state.pathParameters['pid']!); }, ), ], ), ], ), ]; final GoRouter router = await createRouter(routes, tester); router.go('/', extra: 1); await tester.pump(); router.push('/login', extra: 2); await tester.pump(); router.push('/family/f2', extra: 3); await tester.pump(); router.push('/family/f2/person/p1', extra: 4); await tester.pump(); }); testWidgets('match path case insensitively', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/family/:fid', builder: (BuildContext context, GoRouterState state) => FamilyScreen(state.pathParameters['fid']!), ), ]; final GoRouter router = await createRouter(routes, tester); const String loc = '/FaMiLy/f2'; router.go(loc); await tester.pumpAndSettle(); final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches; // NOTE: match the lower case, since location is canonicalized to match the // path case whereas the location can be any case; so long as the path // produces a match regardless of the location case, we win! expect( router.routerDelegate.currentConfiguration.uri .toString() .toLowerCase(), loc.toLowerCase()); expect(matches, hasLength(1)); expect(find.byType(FamilyScreen), findsOneWidget); }); testWidgets( 'If there is more than one route to match, use the first match.', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute(path: '/', builder: dummy), GoRoute(path: '/page1', builder: dummy), GoRoute(path: '/page1', builder: dummy), GoRoute(path: '/:ok', builder: dummy), ]; final GoRouter router = await createRouter(routes, tester); router.go('/user'); await tester.pumpAndSettle(); final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(1)); expect(find.byType(DummyScreen), findsOneWidget); }); testWidgets('Handles the Android back button correctly', (WidgetTester tester) async { final List<RouteBase> routes = <RouteBase>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) { return const Scaffold( body: Text('Screen A'), ); }, routes: <RouteBase>[ GoRoute( path: 'b', builder: (BuildContext context, GoRouterState state) { return const Scaffold( body: Text('Screen B'), ); }, ), ], ), ]; await createRouter(routes, tester, initialLocation: '/b'); expect(find.text('Screen A'), findsNothing); expect(find.text('Screen B'), findsOneWidget); await simulateAndroidBackButton(tester); await tester.pumpAndSettle(); expect(find.text('Screen A'), findsOneWidget); expect(find.text('Screen B'), findsNothing); }); testWidgets('Handles the Android back button correctly with ShellRoute', (WidgetTester tester) async { final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>(); final List<RouteBase> routes = <RouteBase>[ ShellRoute( builder: (BuildContext context, GoRouterState state, Widget child) { return Scaffold( appBar: AppBar(title: const Text('Shell')), body: child, ); }, routes: <GoRoute>[ GoRoute( path: '/a', builder: (BuildContext context, GoRouterState state) { return const Scaffold( body: Text('Screen A'), ); }, routes: <GoRoute>[ GoRoute( path: 'b', builder: (BuildContext context, GoRouterState state) { return const Scaffold( body: Text('Screen B'), ); }, routes: <GoRoute>[ GoRoute( path: 'c', builder: (BuildContext context, GoRouterState state) { return const Scaffold( body: Text('Screen C'), ); }, routes: <GoRoute>[ GoRoute( path: 'd', parentNavigatorKey: rootNavigatorKey, builder: (BuildContext context, GoRouterState state) { return const Scaffold( body: Text('Screen D'), ); }, ), ], ), ], ), ], ), ], ), ]; await createRouter(routes, tester, initialLocation: '/a/b/c/d', navigatorKey: rootNavigatorKey); expect(find.text('Shell'), findsNothing); expect(find.text('Screen A'), findsNothing); expect(find.text('Screen B'), findsNothing); expect(find.text('Screen C'), findsNothing); expect(find.text('Screen D'), findsOneWidget); await simulateAndroidBackButton(tester); await tester.pumpAndSettle(); expect(find.text('Shell'), findsOneWidget); expect(find.text('Screen A'), findsNothing); expect(find.text('Screen B'), findsNothing); expect(find.text('Screen C'), findsOneWidget); expect(find.text('Screen D'), findsNothing); await simulateAndroidBackButton(tester); await tester.pumpAndSettle(); expect(find.text('Shell'), findsOneWidget); expect(find.text('Screen A'), findsNothing); expect(find.text('Screen B'), findsOneWidget); expect(find.text('Screen C'), findsNothing); }); testWidgets( 'Handles the Android back button when parentNavigatorKey is set to the root navigator', (WidgetTester tester) async { final List<MethodCall> log = <MethodCall>[]; TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { log.add(methodCall); return null; }); Future<void> verify(AsyncCallback test, List<Object> expectations) async { log.clear(); await test(); expect(log, expectations); } final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>(); final List<RouteBase> routes = <RouteBase>[ GoRoute( parentNavigatorKey: rootNavigatorKey, path: '/a', builder: (BuildContext context, GoRouterState state) { return const Scaffold( body: Text('Screen A'), ); }, ), ]; await createRouter(routes, tester, initialLocation: '/a', navigatorKey: rootNavigatorKey); expect(find.text('Screen A'), findsOneWidget); await tester.runAsync(() async { await verify(() => simulateAndroidBackButton(tester), <Object>[ isMethodCall('SystemNavigator.pop', arguments: null), ]); }); }); testWidgets("Handles the Android back button when ShellRoute can't pop", (WidgetTester tester) async { final List<MethodCall> log = <MethodCall>[]; TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { log.add(methodCall); return null; }); Future<void> verify(AsyncCallback test, List<Object> expectations) async { log.clear(); await test(); expect(log, expectations); } final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>(); final List<RouteBase> routes = <RouteBase>[ GoRoute( parentNavigatorKey: rootNavigatorKey, path: '/a', builder: (BuildContext context, GoRouterState state) { return const Scaffold( body: Text('Screen A'), ); }, ), ShellRoute( builder: (BuildContext context, GoRouterState state, Widget child) { return Scaffold( appBar: AppBar( title: const Text('Shell'), ), body: child, ); }, routes: <RouteBase>[ GoRoute( path: '/b', builder: (BuildContext context, GoRouterState state) { return const Scaffold( body: Text('Screen B'), ); }, ), ], ), ]; await createRouter(routes, tester, initialLocation: '/b', navigatorKey: rootNavigatorKey); expect(find.text('Screen B'), findsOneWidget); await tester.runAsync(() async { await verify(() => simulateAndroidBackButton(tester), <Object>[ isMethodCall('SystemNavigator.pop', arguments: null), ]); }); }); }); testWidgets('does not crash when inherited widget changes', (WidgetTester tester) async { final ValueNotifier<String> notifier = ValueNotifier<String>('initial'); addTearDown(notifier.dispose); final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', pageBuilder: (BuildContext context, GoRouterState state) { final String value = context .dependOnInheritedWidgetOfExactType<TestInheritedNotifier>()! .notifier! .value; return MaterialPage<void>( key: state.pageKey, child: Text(value), ); }), ]; final GoRouter router = GoRouter( routes: routes, ); addTearDown(router.dispose); await tester.pumpWidget( MaterialApp.router( routerConfig: router, builder: (BuildContext context, Widget? child) { return TestInheritedNotifier(notifier: notifier, child: child!); }, ), ); expect(find.text(notifier.value), findsOneWidget); notifier.value = 'updated'; await tester.pump(); expect(find.text(notifier.value), findsOneWidget); }); testWidgets( 'Handles the Android back button when a second Shell has a GoRoute with parentNavigator key', (WidgetTester tester) async { final List<MethodCall> log = <MethodCall>[]; TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async { log.add(methodCall); return null; }); Future<void> verify(AsyncCallback test, List<Object> expectations) async { log.clear(); await test(); expect(log, expectations); } final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>(); final GlobalKey<NavigatorState> shellNavigatorKeyA = GlobalKey<NavigatorState>(); final GlobalKey<NavigatorState> shellNavigatorKeyB = GlobalKey<NavigatorState>(); final List<RouteBase> routes = <RouteBase>[ ShellRoute( navigatorKey: shellNavigatorKeyA, builder: (BuildContext context, GoRouterState state, Widget child) { return Scaffold( appBar: AppBar( title: const Text('Shell'), ), body: child, ); }, routes: <RouteBase>[ GoRoute( path: '/a', builder: (BuildContext context, GoRouterState state) { return const Scaffold( body: Text('Screen A'), ); }, routes: <RouteBase>[ ShellRoute( navigatorKey: shellNavigatorKeyB, builder: (BuildContext context, GoRouterState state, Widget child) { return Scaffold( appBar: AppBar( title: const Text('Shell'), ), body: child, ); }, routes: <RouteBase>[ GoRoute( path: 'b', parentNavigatorKey: shellNavigatorKeyB, builder: (BuildContext context, GoRouterState state) { return const Scaffold( body: Text('Screen B'), ); }, ), ], ), ], ), ], ), ]; await createRouter(routes, tester, initialLocation: '/a/b', navigatorKey: rootNavigatorKey); expect(find.text('Screen B'), findsOneWidget); // The first pop should not exit the app. await tester.runAsync(() async { await verify(() => simulateAndroidBackButton(tester), <Object>[]); }); // The second pop should exit the app. await tester.runAsync(() async { await verify(() => simulateAndroidBackButton(tester), <Object>[ isMethodCall('SystemNavigator.pop', arguments: null), ]); }); }); group('report correct url', () { final List<MethodCall> log = <MethodCall>[]; setUp(() { GoRouter.optionURLReflectsImperativeAPIs = false; TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler(SystemChannels.navigation, (MethodCall methodCall) async { log.add(methodCall); return null; }); }); tearDown(() { GoRouter.optionURLReflectsImperativeAPIs = false; TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler(SystemChannels.navigation, null); log.clear(); }); testWidgets('on push with optionURLReflectImperativeAPIs = true', (WidgetTester tester) async { GoRouter.optionURLReflectsImperativeAPIs = true; final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (_, __) => const DummyScreen(), ), GoRoute( path: '/settings', builder: (_, __) => const DummyScreen(), ), ]; final GoRouter router = await createRouter(routes, tester); log.clear(); router.push('/settings'); final RouteMatchListCodec codec = RouteMatchListCodec(router.configuration); await tester.pumpAndSettle(); expect(log, <Object>[ isMethodCall('selectMultiEntryHistory', arguments: null), IsRouteUpdateCall('/settings', false, codec.encode(router.routerDelegate.currentConfiguration)), ]); GoRouter.optionURLReflectsImperativeAPIs = false; }); testWidgets('on push', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (_, __) => const DummyScreen(), ), GoRoute( path: '/settings', builder: (_, __) => const DummyScreen(), ), ]; final GoRouter router = await createRouter(routes, tester); log.clear(); router.push('/settings'); final RouteMatchListCodec codec = RouteMatchListCodec(router.configuration); await tester.pumpAndSettle(); expect(log, <Object>[ isMethodCall('selectMultiEntryHistory', arguments: null), IsRouteUpdateCall('/', false, codec.encode(router.routerDelegate.currentConfiguration)), ]); }); testWidgets('on pop', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (_, __) => const DummyScreen(), routes: <RouteBase>[ GoRoute( path: 'settings', builder: (_, __) => const DummyScreen(), ), ]), ]; final GoRouter router = await createRouter(routes, tester, initialLocation: '/settings'); final RouteMatchListCodec codec = RouteMatchListCodec(router.configuration); log.clear(); router.pop(); await tester.pumpAndSettle(); expect(log, <Object>[ isMethodCall('selectMultiEntryHistory', arguments: null), IsRouteUpdateCall('/', false, codec.encode(router.routerDelegate.currentConfiguration)), ]); }); testWidgets('on pop twice', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (_, __) => const DummyScreen(), routes: <RouteBase>[ GoRoute( path: 'settings', builder: (_, __) => const DummyScreen(), routes: <RouteBase>[ GoRoute( path: 'profile', builder: (_, __) => const DummyScreen(), ), ]), ]), ]; final GoRouter router = await createRouter(routes, tester, initialLocation: '/settings/profile'); final RouteMatchListCodec codec = RouteMatchListCodec(router.configuration); log.clear(); router.pop(); router.pop(); await tester.pumpAndSettle(); expect(log, <Object>[ isMethodCall('selectMultiEntryHistory', arguments: null), IsRouteUpdateCall('/', false, codec.encode(router.routerDelegate.currentConfiguration)), ]); }); testWidgets('on pop with path parameters', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (_, __) => const DummyScreen(), routes: <RouteBase>[ GoRoute( path: 'settings/:id', builder: (_, __) => const DummyScreen(), ), ]), ]; final GoRouter router = await createRouter(routes, tester, initialLocation: '/settings/123'); final RouteMatchListCodec codec = RouteMatchListCodec(router.configuration); log.clear(); router.pop(); await tester.pumpAndSettle(); expect(log, <Object>[ isMethodCall('selectMultiEntryHistory', arguments: null), IsRouteUpdateCall('/', false, codec.encode(router.routerDelegate.currentConfiguration)), ]); }); testWidgets('on pop with path parameters case 2', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (_, __) => const DummyScreen(), routes: <RouteBase>[ GoRoute( path: ':id', builder: (_, __) => const DummyScreen(), ), ]), ]; final GoRouter router = await createRouter(routes, tester, initialLocation: '/123/'); final RouteMatchListCodec codec = RouteMatchListCodec(router.configuration); log.clear(); router.pop(); await tester.pumpAndSettle(); expect(log, <Object>[ isMethodCall('selectMultiEntryHistory', arguments: null), IsRouteUpdateCall('/', false, codec.encode(router.routerDelegate.currentConfiguration)), ]); }); testWidgets('Can manually pop root navigator and display correct url', (WidgetTester tester) async { final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>(); final List<RouteBase> routes = <RouteBase>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) { return const Scaffold( body: Text('Home'), ); }, routes: <RouteBase>[ ShellRoute( builder: (BuildContext context, GoRouterState state, Widget child) { return Scaffold( appBar: AppBar(), body: child, ); }, routes: <RouteBase>[ GoRoute( path: 'b', builder: (BuildContext context, GoRouterState state) { return const Scaffold( body: Text('Screen B'), ); }, routes: <RouteBase>[ GoRoute( path: 'c', builder: (BuildContext context, GoRouterState state) { return const Scaffold( body: Text('Screen C'), ); }, ), ], ), ], ), ], ), ]; final GoRouter router = await createRouter(routes, tester, initialLocation: '/b/c', navigatorKey: rootNavigatorKey); final RouteMatchListCodec codec = RouteMatchListCodec(router.configuration); expect(find.text('Screen C'), findsOneWidget); expect(log, <Object>[ isMethodCall('selectMultiEntryHistory', arguments: null), IsRouteUpdateCall('/b/c', true, codec.encode(router.routerDelegate.currentConfiguration)), ]); log.clear(); rootNavigatorKey.currentState!.pop(); await tester.pumpAndSettle(); expect(find.text('Home'), findsOneWidget); expect(log, <Object>[ isMethodCall('selectMultiEntryHistory', arguments: null), IsRouteUpdateCall('/', false, codec.encode(router.routerDelegate.currentConfiguration)), ]); }); testWidgets('can handle route information update from browser', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (_, __) => const DummyScreen(key: ValueKey<String>('home')), routes: <RouteBase>[ GoRoute( path: 'settings', builder: (_, GoRouterState state) => DummyScreen(key: ValueKey<String>('settings-${state.extra}')), ), ], ), ]; final GoRouter router = await createRouter(routes, tester); expect(find.byKey(const ValueKey<String>('home')), findsOneWidget); router.push('/settings', extra: 0); await tester.pumpAndSettle(); expect(find.byKey(const ValueKey<String>('settings-0')), findsOneWidget); log.clear(); router.push('/settings', extra: 1); await tester.pumpAndSettle(); expect(find.byKey(const ValueKey<String>('settings-1')), findsOneWidget); final Map<Object?, Object?> arguments = log.last.arguments as Map<Object?, Object?>; // Stores the state after the last push. This should contain the encoded // RouteMatchList. final Object? state = (log.last.arguments as Map<Object?, Object?>)['state']; final String location = (arguments['location'] ?? arguments['uri']!) as String; router.go('/'); await tester.pumpAndSettle(); expect(find.byKey(const ValueKey<String>('home')), findsOneWidget); router.routeInformationProvider.didPushRouteInformation( RouteInformation(uri: Uri.parse(location), state: state)); await tester.pumpAndSettle(); // Make sure it has all the imperative routes. expect(find.byKey(const ValueKey<String>('settings-1')), findsOneWidget); router.pop(); await tester.pumpAndSettle(); expect(find.byKey(const ValueKey<String>('settings-0')), findsOneWidget); router.pop(); await tester.pumpAndSettle(); expect(find.byKey(const ValueKey<String>('home')), findsOneWidget); }); testWidgets('works correctly with async redirect', (WidgetTester tester) async { final UniqueKey login = UniqueKey(); final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (_, __) => const DummyScreen(), ), GoRoute( path: '/login', builder: (_, __) => DummyScreen(key: login), ), ]; final Completer<void> completer = Completer<void>(); final GoRouter router = await createRouter(routes, tester, redirect: (_, __) async { await completer.future; return '/login'; }); final RouteMatchListCodec codec = RouteMatchListCodec(router.configuration); await tester.pumpAndSettle(); expect(find.byKey(login), findsNothing); expect(tester.takeException(), isNull); expect(log, <Object>[]); completer.complete(); await tester.pumpAndSettle(); expect(find.byKey(login), findsOneWidget); expect(tester.takeException(), isNull); expect(log, <Object>[ isMethodCall('selectMultiEntryHistory', arguments: null), IsRouteUpdateCall('/login', true, codec.encode(router.routerDelegate.currentConfiguration)), ]); }); }); group('named routes', () { testWidgets('match home route', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( name: 'home', path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen()), ]; final GoRouter router = await createRouter(routes, tester); router.goNamed('home'); }); testWidgets('match too many routes', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute(name: 'home', path: '/', builder: dummy), GoRoute(name: 'home', path: '/', builder: dummy), ]; await expectLater(() async { await createRouter(routes, tester); }, throwsA(isAssertionError)); }); test('empty name', () { expect(() { GoRoute(name: '', path: '/'); }, throwsA(isAssertionError)); }); testWidgets('match no routes', (WidgetTester tester) async { await expectLater(() async { final List<GoRoute> routes = <GoRoute>[ GoRoute(name: 'home', path: '/', builder: dummy), ]; final GoRouter router = await createRouter(routes, tester); router.goNamed('work'); }, throwsA(isAssertionError)); }); testWidgets('match 2nd top level route', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( name: 'home', path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( name: 'login', path: '/login', builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ]; final GoRouter router = await createRouter(routes, tester); router.goNamed('login'); }); testWidgets('match sub-route', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( name: 'home', path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: <GoRoute>[ GoRoute( name: 'login', path: 'login', builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ], ), ]; final GoRouter router = await createRouter(routes, tester); router.goNamed('login'); }); testWidgets('match w/ params', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( name: 'home', path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: <GoRoute>[ GoRoute( name: 'family', path: 'family/:fid', builder: (BuildContext context, GoRouterState state) => const FamilyScreen('dummy'), routes: <GoRoute>[ GoRoute( name: 'person', path: 'person/:pid', builder: (BuildContext context, GoRouterState state) { expect(state.pathParameters, <String, String>{'fid': 'f2', 'pid': 'p1'}); return const PersonScreen('dummy', 'dummy'); }, ), ], ), ], ), ]; final GoRouter router = await createRouter(routes, tester); router.goNamed('person', pathParameters: <String, String>{'fid': 'f2', 'pid': 'p1'}); }); testWidgets('too few params', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( name: 'home', path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: <GoRoute>[ GoRoute( name: 'family', path: 'family/:fid', builder: (BuildContext context, GoRouterState state) => const FamilyScreen('dummy'), routes: <GoRoute>[ GoRoute( name: 'person', path: 'person/:pid', builder: (BuildContext context, GoRouterState state) => const PersonScreen('dummy', 'dummy'), ), ], ), ], ), ]; await expectLater(() async { final GoRouter router = await createRouter(routes, tester); router.goNamed('person', pathParameters: <String, String>{'fid': 'f2'}); await tester.pump(); }, throwsA(isAssertionError)); }); testWidgets('cannot match case insensitive', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( name: 'home', path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: <GoRoute>[ GoRoute( name: 'family', path: 'family/:fid', builder: (BuildContext context, GoRouterState state) => const FamilyScreen('dummy'), routes: <GoRoute>[ GoRoute( name: 'PeRsOn', path: 'person/:pid', builder: (BuildContext context, GoRouterState state) { expect(state.pathParameters, <String, String>{'fid': 'f2', 'pid': 'p1'}); return const PersonScreen('dummy', 'dummy'); }, ), ], ), ], ), ]; final GoRouter router = await createRouter(routes, tester); expect( () { router.goNamed( 'person', pathParameters: <String, String>{'fid': 'f2', 'pid': 'p1'}, ); }, throwsAssertionError, ); }); testWidgets('too few params', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( name: 'family', path: '/family/:fid', builder: (BuildContext context, GoRouterState state) => const FamilyScreen('dummy'), ), ]; await expectLater(() async { final GoRouter router = await createRouter(routes, tester); router.goNamed('family'); }, throwsA(isAssertionError)); }); testWidgets('too many params', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( name: 'family', path: '/family/:fid', builder: (BuildContext context, GoRouterState state) => const FamilyScreen('dummy'), ), ]; await expectLater(() async { final GoRouter router = await createRouter(routes, tester); router.goNamed('family', pathParameters: <String, String>{'fid': 'f2', 'pid': 'p1'}); }, throwsA(isAssertionError)); }); testWidgets('sparsely named routes', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: dummy, redirect: (_, __) => '/family/f2', ), GoRoute( path: '/family/:fid', builder: (BuildContext context, GoRouterState state) => FamilyScreen( state.pathParameters['fid']!, ), routes: <GoRoute>[ GoRoute( name: 'person', path: 'person:pid', builder: (BuildContext context, GoRouterState state) => PersonScreen( state.pathParameters['fid']!, state.pathParameters['pid']!, ), ), ], ), ]; final GoRouter router = await createRouter(routes, tester); router.goNamed('person', pathParameters: <String, String>{'fid': 'f2', 'pid': 'p1'}); await tester.pumpAndSettle(); expect(find.byType(PersonScreen), findsOneWidget); }); testWidgets('preserve path param spaces and slashes', (WidgetTester tester) async { const String param1 = 'param w/ spaces and slashes'; final List<GoRoute> routes = <GoRoute>[ GoRoute( name: 'page1', path: '/page1/:param1', builder: (BuildContext c, GoRouterState s) { expect(s.pathParameters['param1'], param1); return const DummyScreen(); }, ), ]; final GoRouter router = await createRouter(routes, tester); final String loc = router.namedLocation('page1', pathParameters: <String, String>{'param1': param1}); router.go(loc); await tester.pumpAndSettle(); final RouteMatchList matches = router.routerDelegate.currentConfiguration; expect(find.byType(DummyScreen), findsOneWidget); expect(matches.pathParameters['param1'], param1); }); testWidgets('preserve query param spaces and slashes', (WidgetTester tester) async { const String param1 = 'param w/ spaces and slashes'; final List<GoRoute> routes = <GoRoute>[ GoRoute( name: 'page1', path: '/page1', builder: (BuildContext c, GoRouterState s) { expect(s.uri.queryParameters['param1'], param1); return const DummyScreen(); }, ), ]; final GoRouter router = await createRouter(routes, tester); final String loc = router.namedLocation('page1', queryParameters: <String, String>{'param1': param1}); router.go(loc); await tester.pumpAndSettle(); final RouteMatchList matches = router.routerDelegate.currentConfiguration; expect(find.byType(DummyScreen), findsOneWidget); expect(matches.uri.queryParameters['param1'], param1); }); }); group('redirects', () { testWidgets('top-level redirect', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: <GoRoute>[ GoRoute( path: 'dummy', builder: (BuildContext context, GoRouterState state) => const DummyScreen()), GoRoute( path: 'login', builder: (BuildContext context, GoRouterState state) => const LoginScreen()), ], ), ]; bool redirected = false; final GoRouter router = await createRouter(routes, tester, redirect: (BuildContext context, GoRouterState state) { redirected = true; return state.matchedLocation == '/login' ? null : '/login'; }); expect( router.routerDelegate.currentConfiguration.uri.toString(), '/login'); expect(redirected, isTrue); redirected = false; // Directly set the url through platform message. await sendPlatformUrl('/dummy', tester); await tester.pumpAndSettle(); expect( router.routerDelegate.currentConfiguration.uri.toString(), '/login'); expect(redirected, isTrue); }); testWidgets('redirect can redirect to same path', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: <GoRoute>[ GoRoute( path: 'dummy', // Return same location. redirect: (_, GoRouterState state) => state.uri.toString(), builder: (BuildContext context, GoRouterState state) => const DummyScreen()), ], ), ]; final GoRouter router = await createRouter(routes, tester, redirect: (BuildContext context, GoRouterState state) { // Return same location. return state.uri.toString(); }); expect(router.routerDelegate.currentConfiguration.uri.toString(), '/'); // Directly set the url through platform message. await sendPlatformUrl('/dummy', tester); await tester.pumpAndSettle(); expect( router.routerDelegate.currentConfiguration.uri.toString(), '/dummy'); }); testWidgets('top-level redirect w/ named routes', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( name: 'home', path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: <GoRoute>[ GoRoute( name: 'dummy', path: 'dummy', builder: (BuildContext context, GoRouterState state) => const DummyScreen(), ), GoRoute( name: 'login', path: 'login', builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ], ), ]; final GoRouter router = await createRouter( routes, tester, redirect: (BuildContext context, GoRouterState state) => state.matchedLocation == '/login' ? null : state.namedLocation('login'), ); expect( router.routerDelegate.currentConfiguration.uri.toString(), '/login'); }); testWidgets('route-level redirect', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: <GoRoute>[ GoRoute( path: 'dummy', builder: (BuildContext context, GoRouterState state) => const DummyScreen(), redirect: (BuildContext context, GoRouterState state) => '/login', ), GoRoute( path: 'login', builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ], ), ]; final GoRouter router = await createRouter(routes, tester); router.go('/dummy'); await tester.pump(); expect( router.routerDelegate.currentConfiguration.uri.toString(), '/login'); }); testWidgets('top-level redirect take priority over route level', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: <GoRoute>[ GoRoute( path: 'dummy', builder: (BuildContext context, GoRouterState state) => const DummyScreen(), redirect: (BuildContext context, GoRouterState state) { // should never be reached. assert(false); return '/dummy2'; }), GoRoute( path: 'dummy2', builder: (BuildContext context, GoRouterState state) => const DummyScreen()), GoRoute( path: 'login', builder: (BuildContext context, GoRouterState state) => const LoginScreen()), ], ), ]; bool redirected = false; final GoRouter router = await createRouter(routes, tester, redirect: (BuildContext context, GoRouterState state) { redirected = true; return state.matchedLocation == '/login' ? null : '/login'; }); redirected = false; // Directly set the url through platform message. await sendPlatformUrl('/dummy', tester); await tester.pumpAndSettle(); expect( router.routerDelegate.currentConfiguration.uri.toString(), '/login'); expect(redirected, isTrue); }); testWidgets('route-level redirect w/ named routes', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( name: 'home', path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: <GoRoute>[ GoRoute( name: 'dummy', path: 'dummy', builder: (BuildContext context, GoRouterState state) => const DummyScreen(), redirect: (BuildContext context, GoRouterState state) => state.namedLocation('login'), ), GoRoute( name: 'login', path: 'login', builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ], ), ]; final GoRouter router = await createRouter(routes, tester); router.go('/dummy'); await tester.pump(); expect( router.routerDelegate.currentConfiguration.uri.toString(), '/login'); }); testWidgets('multiple mixed redirect', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: <GoRoute>[ GoRoute( path: 'dummy1', builder: (BuildContext context, GoRouterState state) => const DummyScreen(), ), GoRoute( path: 'dummy2', builder: (BuildContext context, GoRouterState state) => const DummyScreen(), redirect: (BuildContext context, GoRouterState state) => '/', ), ], ), ]; final GoRouter router = await createRouter(routes, tester, redirect: (BuildContext context, GoRouterState state) => state.matchedLocation == '/dummy1' ? '/dummy2' : null); router.go('/dummy1'); await tester.pump(); expect(router.routerDelegate.currentConfiguration.uri.toString(), '/'); }); testWidgets('top-level redirect loop', (WidgetTester tester) async { final GoRouter router = await createRouter( <GoRoute>[], tester, redirect: (BuildContext context, GoRouterState state) => state.matchedLocation == '/' ? '/login' : state.matchedLocation == '/login' ? '/' : null, errorBuilder: (BuildContext context, GoRouterState state) => TestErrorScreen(state.error!), ); final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(0)); expect(find.byType(TestErrorScreen), findsOneWidget); final TestErrorScreen screen = tester.widget<TestErrorScreen>(find.byType(TestErrorScreen)); expect(screen.ex, isNotNull); }); testWidgets('route-level redirect loop', (WidgetTester tester) async { final GoRouter router = await createRouter( <GoRoute>[ GoRoute( path: '/', builder: dummy, redirect: (BuildContext context, GoRouterState state) => '/login', ), GoRoute( path: '/login', builder: dummy, redirect: (BuildContext context, GoRouterState state) => '/', ), ], tester, errorBuilder: (BuildContext context, GoRouterState state) => TestErrorScreen(state.error!), ); final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(0)); expect(find.byType(TestErrorScreen), findsOneWidget); final TestErrorScreen screen = tester.widget<TestErrorScreen>(find.byType(TestErrorScreen)); expect(screen.ex, isNotNull); }); testWidgets('mixed redirect loop', (WidgetTester tester) async { final GoRouter router = await createRouter( <GoRoute>[ GoRoute( path: '/login', builder: dummy, redirect: (BuildContext context, GoRouterState state) => '/', ), ], tester, redirect: (BuildContext context, GoRouterState state) => state.matchedLocation == '/' ? '/login' : null, errorBuilder: (BuildContext context, GoRouterState state) => TestErrorScreen(state.error!), ); final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(0)); expect(find.byType(TestErrorScreen), findsOneWidget); final TestErrorScreen screen = tester.widget<TestErrorScreen>(find.byType(TestErrorScreen)); expect(screen.ex, isNotNull); }); testWidgets('top-level redirect loop w/ query params', (WidgetTester tester) async { final GoRouter router = await createRouter( <GoRoute>[], tester, redirect: (BuildContext context, GoRouterState state) => state.matchedLocation == '/' ? '/login?from=${state.uri}' : state.matchedLocation == '/login' ? '/' : null, errorBuilder: (BuildContext context, GoRouterState state) => TestErrorScreen(state.error!), ); final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(0)); expect(find.byType(TestErrorScreen), findsOneWidget); final TestErrorScreen screen = tester.widget<TestErrorScreen>(find.byType(TestErrorScreen)); expect(screen.ex, isNotNull); }); testWidgets('expect null path/fullPath on top-level redirect', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/dummy', builder: dummy, redirect: (BuildContext context, GoRouterState state) => '/', ), ]; final GoRouter router = await createRouter( routes, tester, initialLocation: '/dummy', ); expect(router.routerDelegate.currentConfiguration.uri.toString(), '/'); }); testWidgets('top-level redirect state', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/login', builder: (BuildContext context, GoRouterState state) => const LoginScreen(), ), ]; final GoRouter router = await createRouter( routes, tester, initialLocation: '/login?from=/', redirect: (BuildContext context, GoRouterState state) { expect(Uri.parse(state.uri.toString()).queryParameters, isNotEmpty); expect(Uri.parse(state.matchedLocation).queryParameters, isEmpty); expect(state.path, isNull); expect(state.fullPath, '/login'); expect(state.pathParameters.length, 0); expect(state.uri.queryParameters.length, 1); expect(state.uri.queryParameters['from'], '/'); return null; }, ); final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(1)); expect(find.byType(LoginScreen), findsOneWidget); }); testWidgets('top-level redirect state contains path parameters', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => const DummyScreen(), routes: <RouteBase>[ GoRoute( path: ':id', builder: (BuildContext context, GoRouterState state) => const DummyScreen(), ), ]), ]; final GoRouter router = await createRouter( routes, tester, initialLocation: '/123', redirect: (BuildContext context, GoRouterState state) { expect(state.path, isNull); expect(state.fullPath, '/:id'); expect(state.pathParameters.length, 1); expect(state.pathParameters['id'], '123'); return null; }, ); final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(2)); }); testWidgets('route-level redirect state', (WidgetTester tester) async { const String loc = '/book/0'; final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/book/:bookId', redirect: (BuildContext context, GoRouterState state) { expect(state.uri.toString(), loc); expect(state.matchedLocation, loc); expect(state.path, '/book/:bookId'); expect(state.fullPath, '/book/:bookId'); expect(state.pathParameters, <String, String>{'bookId': '0'}); expect(state.uri.queryParameters.length, 0); return null; }, builder: (BuildContext c, GoRouterState s) => const HomeScreen(), ), ]; final GoRouter router = await createRouter( routes, tester, initialLocation: loc, ); final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(1)); expect(find.byType(HomeScreen), findsOneWidget); }); testWidgets('sub-sub-route-level redirect params', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext c, GoRouterState s) => const HomeScreen(), routes: <GoRoute>[ GoRoute( path: 'family/:fid', builder: (BuildContext c, GoRouterState s) => FamilyScreen(s.pathParameters['fid']!), routes: <GoRoute>[ GoRoute( path: 'person/:pid', redirect: (BuildContext context, GoRouterState s) { expect(s.pathParameters['fid'], 'f2'); expect(s.pathParameters['pid'], 'p1'); return null; }, builder: (BuildContext c, GoRouterState s) => PersonScreen( s.pathParameters['fid']!, s.pathParameters['pid']!, ), ), ], ), ], ), ]; final GoRouter router = await createRouter( routes, tester, initialLocation: '/family/f2/person/p1', ); final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches; expect(matches.length, 3); expect(find.byType(HomeScreen, skipOffstage: false), findsOneWidget); expect(find.byType(FamilyScreen, skipOffstage: false), findsOneWidget); final PersonScreen page = tester.widget<PersonScreen>(find.byType(PersonScreen)); expect(page.fid, 'f2'); expect(page.pid, 'p1'); }); testWidgets('redirect limit', (WidgetTester tester) async { final GoRouter router = await createRouter( <GoRoute>[], tester, redirect: (BuildContext context, GoRouterState state) => '/${state.uri}+', errorBuilder: (BuildContext context, GoRouterState state) => TestErrorScreen(state.error!), redirectLimit: 10, ); final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(0)); expect(find.byType(TestErrorScreen), findsOneWidget); final TestErrorScreen screen = tester.widget<TestErrorScreen>(find.byType(TestErrorScreen)); expect(screen.ex, isNotNull); }); testWidgets('can push error page', (WidgetTester tester) async { final GoRouter router = await createRouter( <GoRoute>[ GoRoute(path: '/', builder: (_, __) => const Text('/')), ], tester, errorBuilder: (_, GoRouterState state) { return Text(state.uri.toString()); }, ); expect(find.text('/'), findsOneWidget); router.push('/error1'); await tester.pumpAndSettle(); expect(find.text('/'), findsNothing); expect(find.text('/error1'), findsOneWidget); router.push('/error2'); await tester.pumpAndSettle(); expect(find.text('/'), findsNothing); expect(find.text('/error1'), findsNothing); expect(find.text('/error2'), findsOneWidget); router.pop(); await tester.pumpAndSettle(); expect(find.text('/'), findsNothing); expect(find.text('/error1'), findsOneWidget); expect(find.text('/error2'), findsNothing); router.pop(); await tester.pumpAndSettle(); expect(find.text('/'), findsOneWidget); expect(find.text('/error1'), findsNothing); expect(find.text('/error2'), findsNothing); }); testWidgets('extra not null in redirect', (WidgetTester tester) async { bool isCallTopRedirect = false; bool isCallRouteRedirect = false; final List<GoRoute> routes = <GoRoute>[ GoRoute( name: 'home', path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: <GoRoute>[ GoRoute( name: 'login', path: 'login', builder: (BuildContext context, GoRouterState state) { return const LoginScreen(); }, redirect: (BuildContext context, GoRouterState state) { isCallRouteRedirect = true; expect(state.extra, isNotNull); return null; }, routes: const <GoRoute>[], ), ], ), ]; final GoRouter router = await createRouter( routes, tester, redirect: (BuildContext context, GoRouterState state) { if (state.uri.toString() == '/login') { isCallTopRedirect = true; expect(state.extra, isNotNull); } return null; }, ); router.go('/login', extra: 1); await tester.pump(); expect(isCallTopRedirect, true); expect(isCallRouteRedirect, true); }); testWidgets('parent route level redirect take priority over child', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: <GoRoute>[ GoRoute( path: 'dummy', builder: (BuildContext context, GoRouterState state) => const DummyScreen(), redirect: (BuildContext context, GoRouterState state) => '/other', routes: <GoRoute>[ GoRoute( path: 'dummy2', builder: (BuildContext context, GoRouterState state) => const DummyScreen(), redirect: (BuildContext context, GoRouterState state) { assert(false); return '/other2'; }, ), ]), GoRoute( path: 'other', builder: (BuildContext context, GoRouterState state) => const DummyScreen()), GoRoute( path: 'other2', builder: (BuildContext context, GoRouterState state) => const DummyScreen()), ], ), ]; final GoRouter router = await createRouter(routes, tester); // Directly set the url through platform message. await sendPlatformUrl('/dummy/dummy2', tester); await tester.pumpAndSettle(); expect( router.routerDelegate.currentConfiguration.uri.toString(), '/other'); }); }); group('initial location', () { testWidgets('initial location', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: <GoRoute>[ GoRoute( path: 'dummy', builder: (BuildContext context, GoRouterState state) => const DummyScreen(), ), ], ), ]; final GoRouter router = await createRouter( routes, tester, initialLocation: '/dummy', ); expect( router.routerDelegate.currentConfiguration.uri.toString(), '/dummy'); }); testWidgets('initial location with extra', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: <GoRoute>[ GoRoute( path: 'dummy', builder: (BuildContext context, GoRouterState state) { return DummyScreen(key: ValueKey<Object?>(state.extra)); }, ), ], ), ]; final GoRouter router = await createRouter( routes, tester, initialLocation: '/dummy', initialExtra: 'extra', ); expect( router.routerDelegate.currentConfiguration.uri.toString(), '/dummy'); expect(find.byKey(const ValueKey<Object?>('extra')), findsOneWidget); }); testWidgets('initial location w/ redirection', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/dummy', builder: dummy, redirect: (BuildContext context, GoRouterState state) => '/', ), ]; final GoRouter router = await createRouter( routes, tester, initialLocation: '/dummy', ); expect(router.routerDelegate.currentConfiguration.uri.toString(), '/'); }); testWidgets( 'does not take precedence over platformDispatcher.defaultRouteName', (WidgetTester tester) async { TestWidgetsFlutterBinding .instance.platformDispatcher.defaultRouteNameTestValue = '/dummy'; final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), routes: <GoRoute>[ GoRoute( path: 'dummy', builder: (BuildContext context, GoRouterState state) => const DummyScreen(), ), ], ), ]; final GoRouter router = await createRouter( routes, tester, ); expect(router.routeInformationProvider.value.uri.path, '/dummy'); TestWidgetsFlutterBinding.instance.platformDispatcher .clearDefaultRouteNameTestValue(); }); test('throws assertion if initialExtra is set w/o initialLocation', () { expect( () => GoRouter( routes: const <GoRoute>[], initialExtra: 1, ), throwsA( isA<AssertionError>().having( (AssertionError e) => e.message, 'error message', 'initialLocation must be set in order to use initialExtra', ), ), ); }); }); group('_effectiveInitialLocation()', () { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), ]; testWidgets( 'When platformDispatcher.defaultRouteName is deep-link Uri with ' 'scheme, authority, no path', (WidgetTester tester) async { TestWidgetsFlutterBinding.instance.platformDispatcher .defaultRouteNameTestValue = 'https://domain.com'; final GoRouter router = await createRouter( routes, tester, ); expect(router.routeInformationProvider.value.uri.path, '/'); TestWidgetsFlutterBinding.instance.platformDispatcher .clearDefaultRouteNameTestValue(); }); testWidgets( 'When platformDispatcher.defaultRouteName is deep-link Uri with ' 'scheme, authority, no path, but trailing slash', (WidgetTester tester) async { TestWidgetsFlutterBinding.instance.platformDispatcher .defaultRouteNameTestValue = 'https://domain.com/'; final GoRouter router = await createRouter( routes, tester, ); expect(router.routeInformationProvider.value.uri.path, '/'); TestWidgetsFlutterBinding.instance.platformDispatcher .clearDefaultRouteNameTestValue(); }); testWidgets( 'When platformDispatcher.defaultRouteName is deep-link Uri with ' 'scheme, authority, no path, and query parameters', (WidgetTester tester) async { TestWidgetsFlutterBinding.instance.platformDispatcher .defaultRouteNameTestValue = 'https://domain.com?param=1'; final GoRouter router = await createRouter( routes, tester, ); expect(router.routeInformationProvider.value.uri.toString(), '/?param=1'); TestWidgetsFlutterBinding.instance.platformDispatcher .clearDefaultRouteNameTestValue(); }); }); group('params', () { testWidgets('preserve path param case', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/family/:fid', builder: (BuildContext context, GoRouterState state) => FamilyScreen(state.pathParameters['fid']!), ), ]; final GoRouter router = await createRouter(routes, tester); for (final String fid in <String>['f2', 'F2']) { final String loc = '/family/$fid'; router.go(loc); await tester.pumpAndSettle(); final RouteMatchList matches = router.routerDelegate.currentConfiguration; expect(router.routerDelegate.currentConfiguration.uri.toString(), loc); expect(matches.matches, hasLength(1)); expect(find.byType(FamilyScreen), findsOneWidget); expect(matches.pathParameters['fid'], fid); } }); testWidgets('preserve query param case', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/family', builder: (BuildContext context, GoRouterState state) => FamilyScreen( state.uri.queryParameters['fid']!, ), ), ]; final GoRouter router = await createRouter(routes, tester); for (final String fid in <String>['f2', 'F2']) { final String loc = '/family?fid=$fid'; router.go(loc); await tester.pumpAndSettle(); final RouteMatchList matches = router.routerDelegate.currentConfiguration; expect(router.routerDelegate.currentConfiguration.uri.toString(), loc); expect(matches.matches, hasLength(1)); expect(find.byType(FamilyScreen), findsOneWidget); expect(matches.uri.queryParameters['fid'], fid); } }); testWidgets('preserve path param spaces and slashes', (WidgetTester tester) async { const String param1 = 'param w/ spaces and slashes'; final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/page1/:param1', builder: (BuildContext c, GoRouterState s) { expect(s.pathParameters['param1'], param1); return const DummyScreen(); }, ), ]; final GoRouter router = await createRouter(routes, tester); final String loc = '/page1/${Uri.encodeComponent(param1)}'; router.go(loc); await tester.pumpAndSettle(); final RouteMatchList matches = router.routerDelegate.currentConfiguration; expect(find.byType(DummyScreen), findsOneWidget); expect(matches.pathParameters['param1'], param1); }); testWidgets('preserve query param spaces and slashes', (WidgetTester tester) async { const String param1 = 'param w/ spaces and slashes'; final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/page1', builder: (BuildContext c, GoRouterState s) { expect(s.uri.queryParameters['param1'], param1); return const DummyScreen(); }, ), ]; final GoRouter router = await createRouter(routes, tester); router.go('/page1?param1=$param1'); await tester.pumpAndSettle(); final RouteMatchList matches = router.routerDelegate.currentConfiguration; expect(find.byType(DummyScreen), findsOneWidget); expect(matches.uri.queryParameters['param1'], param1); final String loc = '/page1?param1=${Uri.encodeQueryComponent(param1)}'; router.go(loc); await tester.pumpAndSettle(); final RouteMatchList matches2 = router.routerDelegate.currentConfiguration; expect(find.byType(DummyScreen), findsOneWidget); expect(matches2.uri.queryParameters['param1'], param1); }); test('error: duplicate path param', () { try { GoRouter( routes: <GoRoute>[ GoRoute( path: '/:id/:blah/:bam/:id/:blah', builder: dummy, ), ], errorBuilder: (BuildContext context, GoRouterState state) => TestErrorScreen(state.error!), initialLocation: '/0/1/2/0/1', ); expect(false, true); } on Exception catch (ex) { log.info(ex); } }); testWidgets('duplicate query param', (WidgetTester tester) async { final GoRouter router = await createRouter( <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) { log.info('id= ${state.pathParameters['id']}'); expect(state.pathParameters.length, 0); expect(state.uri.queryParameters.length, 1); expect(state.uri.queryParameters['id'], anyOf('0', '1')); return const HomeScreen(); }, ), ], tester, initialLocation: '/?id=0&id=1', ); final RouteMatchList matches = router.routerDelegate.currentConfiguration; expect(matches.matches, hasLength(1)); expect(matches.fullPath, '/'); expect(find.byType(HomeScreen), findsOneWidget); }); testWidgets('duplicate path + query param', (WidgetTester tester) async { final GoRouter router = await createRouter( <GoRoute>[ GoRoute( path: '/:id', builder: (BuildContext context, GoRouterState state) { expect(state.pathParameters, <String, String>{'id': '0'}); expect(state.uri.queryParameters, <String, String>{'id': '1'}); return const HomeScreen(); }, ), ], tester, ); router.go('/0?id=1'); await tester.pumpAndSettle(); final RouteMatchList matches = router.routerDelegate.currentConfiguration; expect(matches.matches, hasLength(1)); expect(matches.fullPath, '/:id'); expect(find.byType(HomeScreen), findsOneWidget); }); testWidgets('push + query param', (WidgetTester tester) async { final GoRouter router = await createRouter( <GoRoute>[ GoRoute(path: '/', builder: dummy), GoRoute( path: '/family', builder: (BuildContext context, GoRouterState state) => FamilyScreen( state.uri.queryParameters['fid']!, ), ), GoRoute( path: '/person', builder: (BuildContext context, GoRouterState state) => PersonScreen( state.uri.queryParameters['fid']!, state.uri.queryParameters['pid']!, ), ), ], tester, ); router.go('/family?fid=f2'); await tester.pumpAndSettle(); router.push('/person?fid=f2&pid=p1'); await tester.pumpAndSettle(); final FamilyScreen page1 = tester .widget<FamilyScreen>(find.byType(FamilyScreen, skipOffstage: false)); expect(page1.fid, 'f2'); final PersonScreen page2 = tester.widget<PersonScreen>(find.byType(PersonScreen)); expect(page2.fid, 'f2'); expect(page2.pid, 'p1'); }); testWidgets('push + extra param', (WidgetTester tester) async { final GoRouter router = await createRouter( <GoRoute>[ GoRoute(path: '/', builder: dummy), GoRoute( path: '/family', builder: (BuildContext context, GoRouterState state) => FamilyScreen( (state.extra! as Map<String, String>)['fid']!, ), ), GoRoute( path: '/person', builder: (BuildContext context, GoRouterState state) => PersonScreen( (state.extra! as Map<String, String>)['fid']!, (state.extra! as Map<String, String>)['pid']!, ), ), ], tester, ); router.go('/family', extra: <String, String>{'fid': 'f2'}); await tester.pumpAndSettle(); router.push('/person', extra: <String, String>{'fid': 'f2', 'pid': 'p1'}); await tester.pumpAndSettle(); final FamilyScreen page1 = tester .widget<FamilyScreen>(find.byType(FamilyScreen, skipOffstage: false)); expect(page1.fid, 'f2'); final PersonScreen page2 = tester.widget<PersonScreen>(find.byType(PersonScreen)); expect(page2.fid, 'f2'); expect(page2.pid, 'p1'); }); testWidgets('keep param in nested route', (WidgetTester tester) async { final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( path: '/family/:fid', builder: (BuildContext context, GoRouterState state) => FamilyScreen(state.pathParameters['fid']!), routes: <GoRoute>[ GoRoute( path: 'person/:pid', builder: (BuildContext context, GoRouterState state) { final String fid = state.pathParameters['fid']!; final String pid = state.pathParameters['pid']!; return PersonScreen(fid, pid); }, ), ], ), ]; final GoRouter router = await createRouter(routes, tester); const String fid = 'f1'; const String pid = 'p2'; const String loc = '/family/$fid/person/$pid'; router.push(loc); await tester.pumpAndSettle(); final RouteMatchList matches = router.routerDelegate.currentConfiguration; expect(matches.matches, hasLength(2)); expect(find.byType(PersonScreen), findsOneWidget); final ImperativeRouteMatch imperativeRouteMatch = matches.matches.last as ImperativeRouteMatch; expect(imperativeRouteMatch.matches.uri.toString(), loc); expect(imperativeRouteMatch.matches.pathParameters['fid'], fid); expect(imperativeRouteMatch.matches.pathParameters['pid'], pid); }); testWidgets('StatefulShellRoute supports nested routes with params', (WidgetTester tester) async { StatefulNavigationShell? routeState; final List<RouteBase> routes = <RouteBase>[ StatefulShellRoute.indexedStack( builder: (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) { routeState = navigationShell; return navigationShell; }, branches: <StatefulShellBranch>[ StatefulShellBranch( routes: <RouteBase>[ GoRoute( path: '/a', builder: (BuildContext context, GoRouterState state) => const Text('Screen A'), ), ], ), StatefulShellBranch( routes: <RouteBase>[ GoRoute( path: '/family', builder: (BuildContext context, GoRouterState state) => const Text('Families'), routes: <RouteBase>[ GoRoute( path: ':fid', builder: (BuildContext context, GoRouterState state) => FamilyScreen(state.pathParameters['fid']!), routes: <GoRoute>[ GoRoute( path: 'person/:pid', builder: (BuildContext context, GoRouterState state) { final String fid = state.pathParameters['fid']!; final String pid = state.pathParameters['pid']!; return PersonScreen(fid, pid); }, ), ], ) ]), ], ), ], ), ]; final GoRouter router = await createRouter(routes, tester, initialLocation: '/a'); const String fid = 'f1'; const String pid = 'p2'; const String loc = '/family/$fid/person/$pid'; router.go(loc); await tester.pumpAndSettle(); RouteMatchList matches = router.routerDelegate.currentConfiguration; expect(router.routerDelegate.currentConfiguration.uri.toString(), loc); expect(matches.matches, hasLength(1)); final ShellRouteMatch shellRouteMatch = matches.matches.first as ShellRouteMatch; expect(shellRouteMatch.matches, hasLength(3)); expect(find.byType(PersonScreen), findsOneWidget); expect(matches.pathParameters['fid'], fid); expect(matches.pathParameters['pid'], pid); routeState?.goBranch(0); await tester.pumpAndSettle(); expect(find.text('Screen A'), findsOneWidget); expect(find.byType(PersonScreen), findsNothing); routeState?.goBranch(1); await tester.pumpAndSettle(); expect(find.text('Screen A'), findsNothing); expect(find.byType(PersonScreen), findsOneWidget); matches = router.routerDelegate.currentConfiguration; expect(matches.pathParameters['fid'], fid); expect(matches.pathParameters['pid'], pid); }); testWidgets('StatefulShellRoute preserve extra when switching branch', (WidgetTester tester) async { StatefulNavigationShell? routeState; Object? latestExtra; final List<RouteBase> routes = <RouteBase>[ StatefulShellRoute.indexedStack( builder: (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) { routeState = navigationShell; return navigationShell; }, branches: <StatefulShellBranch>[ StatefulShellBranch( routes: <RouteBase>[ GoRoute( path: '/a', builder: (BuildContext context, GoRouterState state) => const Text('Screen A'), ), ], ), StatefulShellBranch( routes: <RouteBase>[ GoRoute( path: '/b', builder: (BuildContext context, GoRouterState state) { latestExtra = state.extra; return const DummyScreen(); }), ], ), ], ), ]; final Object expectedExtra = Object(); await createRouter(routes, tester, initialLocation: '/b', initialExtra: expectedExtra); expect(latestExtra, expectedExtra); routeState!.goBranch(0); await tester.pumpAndSettle(); routeState!.goBranch(1); await tester.pumpAndSettle(); expect(latestExtra, expectedExtra); }); testWidgets('goNames should allow dynamics values for queryParams', (WidgetTester tester) async { const Map<String, dynamic> queryParametersAll = <String, List<dynamic>>{ 'q1': <String>['v1'], 'q2': <String>['v2', 'v3'], }; void expectLocationWithQueryParams(String location) { final Uri uri = Uri.parse(location); expect(uri.path, '/page'); expect(uri.queryParametersAll, queryParametersAll); } final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( name: 'page', path: '/page', builder: (BuildContext context, GoRouterState state) { expect(state.uri.queryParametersAll, queryParametersAll); expectLocationWithQueryParams(state.uri.toString()); return DummyScreen( queryParametersAll: state.uri.queryParametersAll, ); }, ), ]; final GoRouter router = await createRouter(routes, tester); router.goNamed('page', queryParameters: const <String, dynamic>{ 'q1': 'v1', 'q2': <String>['v2', 'v3'], }); await tester.pumpAndSettle(); final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(1)); expectLocationWithQueryParams( router.routerDelegate.currentConfiguration.uri.toString()); expect( tester.widget<DummyScreen>(find.byType(DummyScreen)), isA<DummyScreen>().having( (DummyScreen screen) => screen.queryParametersAll, 'screen.queryParametersAll', queryParametersAll, ), ); }); }); testWidgets('go should preserve the query parameters when navigating', (WidgetTester tester) async { const Map<String, dynamic> queryParametersAll = <String, List<dynamic>>{ 'q1': <String>['v1'], 'q2': <String>['v2', 'v3'], }; void expectLocationWithQueryParams(String location) { final Uri uri = Uri.parse(location); expect(uri.path, '/page'); expect(uri.queryParametersAll, queryParametersAll); } final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( name: 'page', path: '/page', builder: (BuildContext context, GoRouterState state) { expect(state.uri.queryParametersAll, queryParametersAll); expectLocationWithQueryParams(state.uri.toString()); return DummyScreen( queryParametersAll: state.uri.queryParametersAll, ); }, ), ]; final GoRouter router = await createRouter(routes, tester); router.go('/page?q1=v1&q2=v2&q2=v3'); await tester.pumpAndSettle(); final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(1)); expectLocationWithQueryParams( router.routerDelegate.currentConfiguration.uri.toString()); expect( tester.widget<DummyScreen>(find.byType(DummyScreen)), isA<DummyScreen>().having( (DummyScreen screen) => screen.queryParametersAll, 'screen.queryParametersAll', queryParametersAll, ), ); }); testWidgets('goRouter should rebuild widget if ', (WidgetTester tester) async { const Map<String, dynamic> queryParametersAll = <String, List<dynamic>>{ 'q1': <String>['v1'], 'q2': <String>['v2', 'v3'], }; void expectLocationWithQueryParams(String location) { final Uri uri = Uri.parse(location); expect(uri.path, '/page'); expect(uri.queryParametersAll, queryParametersAll); } final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => const HomeScreen(), ), GoRoute( name: 'page', path: '/page', builder: (BuildContext context, GoRouterState state) { expect(state.uri.queryParametersAll, queryParametersAll); expectLocationWithQueryParams(state.uri.toString()); return DummyScreen( queryParametersAll: state.uri.queryParametersAll, ); }, ), ]; final GoRouter router = await createRouter(routes, tester); router.go('/page?q1=v1&q2=v2&q2=v3'); await tester.pumpAndSettle(); final List<RouteMatchBase> matches = router.routerDelegate.currentConfiguration.matches; expect(matches, hasLength(1)); expectLocationWithQueryParams( router.routerDelegate.currentConfiguration.uri.toString()); expect( tester.widget<DummyScreen>(find.byType(DummyScreen)), isA<DummyScreen>().having( (DummyScreen screen) => screen.queryParametersAll, 'screen.queryParametersAll', queryParametersAll, ), ); }); group('GoRouterHelper extensions', () { final GlobalKey<DummyStatefulWidgetState> key = GlobalKey<DummyStatefulWidgetState>(); final List<GoRoute> routes = <GoRoute>[ GoRoute( path: '/', name: 'home', builder: (BuildContext context, GoRouterState state) => DummyStatefulWidget(key: key), ), GoRoute( path: '/page1', name: 'page1', builder: (BuildContext context, GoRouterState state) => const Page1Screen(), ), ]; const String name = 'page1'; final Map<String, String> params = <String, String>{ 'a-param-key': 'a-param-value', }; final Map<String, String> queryParams = <String, String>{ 'a-query-key': 'a-query-value', }; const String location = '/page1'; const String extra = 'Hello'; testWidgets('calls [namedLocation] on closest GoRouter', (WidgetTester tester) async { final GoRouterNamedLocationSpy router = GoRouterNamedLocationSpy(routes: routes); addTearDown(router.dispose); await tester.pumpWidget( MaterialApp.router( routerConfig: router, title: 'GoRouter Example', ), ); key.currentContext!.namedLocation( name, pathParameters: params, queryParameters: queryParams, ); expect(router.name, name); expect(router.pathParameters, params); expect(router.queryParameters, queryParams); }); testWidgets('calls [go] on closest GoRouter', (WidgetTester tester) async { final GoRouterGoSpy router = GoRouterGoSpy(routes: routes); addTearDown(router.dispose); await tester.pumpWidget( MaterialApp.router( routerConfig: router, title: 'GoRouter Example', ), ); key.currentContext!.go( location, extra: extra, ); expect(router.myLocation, location); expect(router.extra, extra); }); testWidgets('calls [goNamed] on closest GoRouter', (WidgetTester tester) async { final GoRouterGoNamedSpy router = GoRouterGoNamedSpy(routes: routes); addTearDown(router.dispose); await tester.pumpWidget( MaterialApp.router( routerConfig: router, title: 'GoRouter Example', ), ); key.currentContext!.goNamed( name, pathParameters: params, queryParameters: queryParams, extra: extra, ); expect(router.name, name); expect(router.pathParameters, params); expect(router.queryParameters, queryParams); expect(router.extra, extra); }); testWidgets('calls [push] on closest GoRouter', (WidgetTester tester) async { final GoRouterPushSpy router = GoRouterPushSpy(routes: routes); addTearDown(router.dispose); await tester.pumpWidget( MaterialApp.router( routerConfig: router, title: 'GoRouter Example', ), ); key.currentContext!.push( location, extra: extra, ); expect(router.myLocation, location); expect(router.extra, extra); }); testWidgets('calls [push] on closest GoRouter and waits for result', (WidgetTester tester) async { final GoRouterPushSpy router = GoRouterPushSpy(routes: routes); addTearDown(router.dispose); await tester.pumpWidget( MaterialApp.router( routeInformationProvider: router.routeInformationProvider, routeInformationParser: router.routeInformationParser, routerDelegate: router.routerDelegate, title: 'GoRouter Example', ), ); final String? result = await router.push<String>( location, extra: extra, ); expect(result, extra); expect(router.myLocation, location); expect(router.extra, extra); }); testWidgets('calls [pushNamed] on closest GoRouter', (WidgetTester tester) async { final GoRouterPushNamedSpy router = GoRouterPushNamedSpy(routes: routes); addTearDown(router.dispose); await tester.pumpWidget( MaterialApp.router( routerConfig: router, title: 'GoRouter Example', ), ); key.currentContext!.pushNamed( name, pathParameters: params, queryParameters: queryParams, extra: extra, ); expect(router.name, name); expect(router.pathParameters, params); expect(router.queryParameters, queryParams); expect(router.extra, extra); }); testWidgets('calls [pushNamed] on closest GoRouter and waits for result', (WidgetTester tester) async { final GoRouterPushNamedSpy router = GoRouterPushNamedSpy(routes: routes); addTearDown(router.dispose); await tester.pumpWidget( MaterialApp.router( routeInformationProvider: router.routeInformationProvider, routeInformationParser: router.routeInformationParser, routerDelegate: router.routerDelegate, title: 'GoRouter Example', ), ); final String? result = await router.pushNamed<String>( name, pathParameters: params, queryParameters: queryParams, extra: extra, ); expect(result, extra); expect(router.extra, extra); expect(router.name, name); expect(router.pathParameters, params); expect(router.queryParameters, queryParams); }); testWidgets('calls [pop] on closest GoRouter', (WidgetTester tester) async { final GoRouterPopSpy router = GoRouterPopSpy(routes: routes); addTearDown(router.dispose); await tester.pumpWidget( MaterialApp.router( routerConfig: router, title: 'GoRouter Example', ), ); key.currentContext!.pop(); expect(router.popped, true); expect(router.poppedResult, null); }); testWidgets('calls [pop] on closest GoRouter with result', (WidgetTester tester) async { final GoRouterPopSpy router = GoRouterPopSpy(routes: routes); addTearDown(router.dispose); await tester.pumpWidget( MaterialApp.router( routerConfig: router, title: 'GoRouter Example', ), ); key.currentContext!.pop('result'); expect(router.popped, true); expect(router.poppedResult, 'result'); }); }); group('ShellRoute', () { testWidgets('defaultRoute', (WidgetTester tester) async { final List<RouteBase> routes = <RouteBase>[ ShellRoute( builder: (BuildContext context, GoRouterState state, Widget child) { return Scaffold( body: child, ); }, routes: <RouteBase>[ GoRoute( path: '/a', builder: (BuildContext context, GoRouterState state) { return const Scaffold( body: Text('Screen A'), ); }, ), GoRoute( path: '/b', builder: (BuildContext context, GoRouterState state) { return const Scaffold( body: Text('Screen B'), ); }, ), ], ), ]; await createRouter(routes, tester, initialLocation: '/b'); expect(find.text('Screen B'), findsOneWidget); }); testWidgets( 'Pops from the correct Navigator when the Android back button is pressed', (WidgetTester tester) async { final List<RouteBase> routes = <RouteBase>[ ShellRoute( builder: (BuildContext context, GoRouterState state, Widget child) { return Scaffold( body: Column( children: <Widget>[ const Text('Screen A'), Expanded(child: child), ], ), ); }, routes: <RouteBase>[ GoRoute( path: '/b', builder: (BuildContext context, GoRouterState state) { return const Scaffold( body: Text('Screen B'), ); }, routes: <RouteBase>[ GoRoute( path: 'c', builder: (BuildContext context, GoRouterState state) { return const Scaffold( body: Text('Screen C'), ); }, ), ], ), ], ), ]; await createRouter(routes, tester, initialLocation: '/b/c'); expect(find.text('Screen A'), findsOneWidget); expect(find.text('Screen B'), findsNothing); expect(find.text('Screen C'), findsOneWidget); await simulateAndroidBackButton(tester); await tester.pumpAndSettle(); expect(find.text('Screen A'), findsOneWidget); expect(find.text('Screen B'), findsOneWidget); expect(find.text('Screen C'), findsNothing); }); testWidgets( 'Pops from the correct navigator when a sub-route is placed on ' 'the root Navigator', (WidgetTester tester) async { final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>(); final GlobalKey<NavigatorState> shellNavigatorKey = GlobalKey<NavigatorState>(); final List<RouteBase> routes = <RouteBase>[ ShellRoute( navigatorKey: shellNavigatorKey, builder: (BuildContext context, GoRouterState state, Widget child) { return Scaffold( body: Column( children: <Widget>[ const Text('Screen A'), Expanded(child: child), ], ), ); }, routes: <RouteBase>[ GoRoute( path: '/b', builder: (BuildContext context, GoRouterState state) { return const Scaffold( body: Text('Screen B'), ); }, routes: <RouteBase>[ GoRoute( path: 'c', parentNavigatorKey: rootNavigatorKey, builder: (BuildContext context, GoRouterState state) { return const Scaffold( body: Text('Screen C'), ); }, ), ], ), ], ), ]; await createRouter(routes, tester, initialLocation: '/b/c', navigatorKey: rootNavigatorKey); expect(find.text('Screen A'), findsNothing); expect(find.text('Screen B'), findsNothing); expect(find.text('Screen C'), findsOneWidget); await simulateAndroidBackButton(tester); await tester.pumpAndSettle(); expect(find.text('Screen A'), findsOneWidget); expect(find.text('Screen B'), findsOneWidget); expect(find.text('Screen C'), findsNothing); }); testWidgets('Builds StatefulShellRoute', (WidgetTester tester) async { final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>(); final List<RouteBase> routes = <RouteBase>[ StatefulShellRoute.indexedStack( builder: (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) => navigationShell, branches: <StatefulShellBranch>[ StatefulShellBranch(routes: <GoRoute>[ GoRoute( path: '/a', builder: (BuildContext context, GoRouterState state) => const Text('Screen A'), ), ]), StatefulShellBranch(routes: <GoRoute>[ GoRoute( path: '/b', builder: (BuildContext context, GoRouterState state) => const Text('Screen B'), ), ]), ], ), ]; final GoRouter router = await createRouter(routes, tester, initialLocation: '/a', navigatorKey: rootNavigatorKey); expect(find.text('Screen A'), findsOneWidget); expect(find.text('Screen B'), findsNothing); router.go('/b'); await tester.pumpAndSettle(); expect(find.text('Screen A'), findsNothing); expect(find.text('Screen B'), findsOneWidget); }); testWidgets('Builds StatefulShellRoute as a sub-route', (WidgetTester tester) async { final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>(); final List<RouteBase> routes = <RouteBase>[ GoRoute( path: '/root', builder: (BuildContext context, GoRouterState state) => const Text('Root'), routes: <RouteBase>[ StatefulShellRoute.indexedStack( builder: (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) => navigationShell, branches: <StatefulShellBranch>[ StatefulShellBranch(routes: <GoRoute>[ GoRoute( path: 'a', builder: (BuildContext context, GoRouterState state) => const Text('Screen A'), ), ]), StatefulShellBranch(routes: <GoRoute>[ GoRoute( path: 'b', builder: (BuildContext context, GoRouterState state) => const Text('Screen B'), ), ]), ], ), ], ), ]; final GoRouter router = await createRouter(routes, tester, initialLocation: '/root/a', navigatorKey: rootNavigatorKey); expect(find.text('Screen A'), findsOneWidget); expect(find.text('Screen B'), findsNothing); router.go('/root/b'); await tester.pumpAndSettle(); expect(find.text('Screen A'), findsNothing); expect(find.text('Screen B'), findsOneWidget); }); testWidgets( 'Navigation with goBranch is correctly handled in StatefulShellRoute', (WidgetTester tester) async { final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>(); final GlobalKey<DummyStatefulWidgetState> statefulWidgetKey = GlobalKey<DummyStatefulWidgetState>(); StatefulNavigationShell? routeState; final List<RouteBase> routes = <RouteBase>[ StatefulShellRoute.indexedStack( builder: (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) { routeState = navigationShell; return navigationShell; }, branches: <StatefulShellBranch>[ StatefulShellBranch( routes: <RouteBase>[ GoRoute( path: '/a', builder: (BuildContext context, GoRouterState state) => const Text('Screen A'), ), ], ), StatefulShellBranch( routes: <RouteBase>[ GoRoute( path: '/b', builder: (BuildContext context, GoRouterState state) => const Text('Screen B'), ), ], ), StatefulShellBranch( routes: <RouteBase>[ GoRoute( path: '/c', builder: (BuildContext context, GoRouterState state) => const Text('Screen C'), ), ], ), StatefulShellBranch( routes: <RouteBase>[ GoRoute( path: '/d', builder: (BuildContext context, GoRouterState state) => const Text('Screen D'), ), ], ), ], ), ]; await createRouter(routes, tester, initialLocation: '/a', navigatorKey: rootNavigatorKey); statefulWidgetKey.currentState?.increment(); expect(find.text('Screen A'), findsOneWidget); expect(find.text('Screen B'), findsNothing); expect(find.text('Screen C'), findsNothing); expect(find.text('Screen D'), findsNothing); routeState!.goBranch(1); await tester.pumpAndSettle(); expect(find.text('Screen A'), findsNothing); expect(find.text('Screen B'), findsOneWidget); expect(find.text('Screen C'), findsNothing); expect(find.text('Screen D'), findsNothing); routeState!.goBranch(2); await tester.pumpAndSettle(); expect(find.text('Screen A'), findsNothing); expect(find.text('Screen B'), findsNothing); expect(find.text('Screen C'), findsOneWidget); expect(find.text('Screen D'), findsNothing); routeState!.goBranch(3); await tester.pumpAndSettle(); expect(find.text('Screen A'), findsNothing); expect(find.text('Screen B'), findsNothing); expect(find.text('Screen C'), findsNothing); expect(find.text('Screen D'), findsOneWidget); expect(() { // Verify that navigation to unknown index fails routeState!.goBranch(4); }, throwsA(isA<Error>())); }); testWidgets( 'Navigates to correct nested navigation tree in StatefulShellRoute ' 'and maintains state', (WidgetTester tester) async { final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>(); final GlobalKey<DummyStatefulWidgetState> statefulWidgetKey = GlobalKey<DummyStatefulWidgetState>(); StatefulNavigationShell? routeState; final List<RouteBase> routes = <RouteBase>[ StatefulShellRoute.indexedStack( builder: (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) { routeState = navigationShell; return navigationShell; }, branches: <StatefulShellBranch>[ StatefulShellBranch(routes: <GoRoute>[ GoRoute( path: '/a', builder: (BuildContext context, GoRouterState state) => const Text('Screen A'), routes: <RouteBase>[ GoRoute( path: 'detailA', builder: (BuildContext context, GoRouterState state) => Column(children: <Widget>[ const Text('Screen A Detail'), DummyStatefulWidget(key: statefulWidgetKey), ]), ), ], ), ]), StatefulShellBranch(routes: <GoRoute>[ GoRoute( path: '/b', builder: (BuildContext context, GoRouterState state) => const Text('Screen B'), ), ]), ], ), ]; final GoRouter router = await createRouter(routes, tester, initialLocation: '/a/detailA', navigatorKey: rootNavigatorKey); statefulWidgetKey.currentState?.increment(); expect(find.text('Screen A'), findsNothing); expect(find.text('Screen A Detail'), findsOneWidget); expect(find.text('Screen B'), findsNothing); routeState!.goBranch(1); await tester.pumpAndSettle(); expect(find.text('Screen A'), findsNothing); expect(find.text('Screen A Detail'), findsNothing); expect(find.text('Screen B'), findsOneWidget); routeState!.goBranch(0); await tester.pumpAndSettle(); expect(statefulWidgetKey.currentState?.counter, equals(1)); router.go('/a'); await tester.pumpAndSettle(); expect(find.text('Screen A'), findsOneWidget); expect(find.text('Screen A Detail'), findsNothing); router.go('/a/detailA'); await tester.pumpAndSettle(); expect(statefulWidgetKey.currentState?.counter, equals(0)); }); testWidgets('Maintains state for nested StatefulShellRoute', (WidgetTester tester) async { final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>(); final GlobalKey<DummyStatefulWidgetState> statefulWidgetKey = GlobalKey<DummyStatefulWidgetState>(); StatefulNavigationShell? routeState1; StatefulNavigationShell? routeState2; final List<RouteBase> routes = <RouteBase>[ StatefulShellRoute.indexedStack( builder: (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) { routeState1 = navigationShell; return navigationShell; }, branches: <StatefulShellBranch>[ StatefulShellBranch(routes: <RouteBase>[ StatefulShellRoute.indexedStack( builder: (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) { routeState2 = navigationShell; return navigationShell; }, branches: <StatefulShellBranch>[ StatefulShellBranch(routes: <RouteBase>[ GoRoute( path: '/a', builder: (BuildContext context, GoRouterState state) => const Text('Screen A'), routes: <RouteBase>[ GoRoute( path: 'detailA', builder: (BuildContext context, GoRouterState state) => Column(children: <Widget>[ const Text('Screen A Detail'), DummyStatefulWidget(key: statefulWidgetKey), ]), ), ], ), ]), StatefulShellBranch(routes: <RouteBase>[ GoRoute( path: '/b', builder: (BuildContext context, GoRouterState state) => const Text('Screen B'), ), ]), StatefulShellBranch(routes: <RouteBase>[ GoRoute( path: '/c', builder: (BuildContext context, GoRouterState state) => const Text('Screen C'), ), ]), ]), ]), StatefulShellBranch(routes: <GoRoute>[ GoRoute( path: '/d', builder: (BuildContext context, GoRouterState state) => const Text('Screen D'), ), ]), ], ), ]; await createRouter(routes, tester, initialLocation: '/a/detailA', navigatorKey: rootNavigatorKey); statefulWidgetKey.currentState?.increment(); expect(find.text('Screen A Detail'), findsOneWidget); routeState2!.goBranch(1); await tester.pumpAndSettle(); expect(find.text('Screen B'), findsOneWidget); routeState1!.goBranch(1); await tester.pumpAndSettle(); expect(find.text('Screen D'), findsOneWidget); routeState1!.goBranch(0); await tester.pumpAndSettle(); expect(find.text('Screen B'), findsOneWidget); routeState2!.goBranch(2); await tester.pumpAndSettle(); expect(find.text('Screen C'), findsOneWidget); routeState2!.goBranch(0); await tester.pumpAndSettle(); expect(find.text('Screen A Detail'), findsOneWidget); expect(statefulWidgetKey.currentState?.counter, equals(1)); }); testWidgets( 'Pops from the correct Navigator in a StatefulShellRoute when the ' 'Android back button is pressed', (WidgetTester tester) async { final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>(); final GlobalKey<NavigatorState> sectionANavigatorKey = GlobalKey<NavigatorState>(); final GlobalKey<NavigatorState> sectionBNavigatorKey = GlobalKey<NavigatorState>(); StatefulNavigationShell? routeState; final List<RouteBase> routes = <RouteBase>[ StatefulShellRoute.indexedStack( builder: (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) { routeState = navigationShell; return navigationShell; }, branches: <StatefulShellBranch>[ StatefulShellBranch( navigatorKey: sectionANavigatorKey, routes: <GoRoute>[ GoRoute( path: '/a', builder: (BuildContext context, GoRouterState state) => const Text('Screen A'), routes: <RouteBase>[ GoRoute( path: 'detailA', builder: (BuildContext context, GoRouterState state) => const Text('Screen A Detail'), ), ], ), ]), StatefulShellBranch( navigatorKey: sectionBNavigatorKey, routes: <GoRoute>[ GoRoute( path: '/b', builder: (BuildContext context, GoRouterState state) => const Text('Screen B'), routes: <RouteBase>[ GoRoute( path: 'detailB', builder: (BuildContext context, GoRouterState state) => const Text('Screen B Detail'), ), ], ), ]), ], ), ]; final GoRouter router = await createRouter(routes, tester, initialLocation: '/a/detailA', navigatorKey: rootNavigatorKey); expect(find.text('Screen A'), findsNothing); expect(find.text('Screen A Detail'), findsOneWidget); expect(find.text('Screen B'), findsNothing); expect(find.text('Screen B Detail'), findsNothing); router.go('/b/detailB'); await tester.pumpAndSettle(); expect(find.text('Screen A'), findsNothing); expect(find.text('Screen A Detail'), findsNothing); expect(find.text('Screen B'), findsNothing); expect(find.text('Screen B Detail'), findsOneWidget); await simulateAndroidBackButton(tester); await tester.pumpAndSettle(); expect(find.text('Screen A'), findsNothing); expect(find.text('Screen A Detail'), findsNothing); expect(find.text('Screen B'), findsOneWidget); expect(find.text('Screen B Detail'), findsNothing); routeState!.goBranch(0); await tester.pumpAndSettle(); expect(find.text('Screen A'), findsNothing); expect(find.text('Screen A Detail'), findsOneWidget); await simulateAndroidBackButton(tester); await tester.pumpAndSettle(); expect(find.text('Screen A'), findsOneWidget); expect(find.text('Screen A Detail'), findsNothing); }); testWidgets( 'Maintains extra navigation information when navigating ' 'between branches in StatefulShellRoute', (WidgetTester tester) async { final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>(); StatefulNavigationShell? routeState; final List<RouteBase> routes = <RouteBase>[ StatefulShellRoute.indexedStack( builder: (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) { routeState = navigationShell; return navigationShell; }, branches: <StatefulShellBranch>[ StatefulShellBranch(routes: <GoRoute>[ GoRoute( path: '/a', builder: (BuildContext context, GoRouterState state) => const Text('Screen A'), ), ]), StatefulShellBranch(routes: <GoRoute>[ GoRoute( path: '/b', builder: (BuildContext context, GoRouterState state) => Text('Screen B - ${state.extra}'), ), ]), ], ), ]; final GoRouter router = await createRouter(routes, tester, initialLocation: '/a', navigatorKey: rootNavigatorKey); expect(find.text('Screen A'), findsOneWidget); router.go('/b', extra: 'X'); await tester.pumpAndSettle(); expect(find.text('Screen A'), findsNothing); expect(find.text('Screen B - X'), findsOneWidget); routeState!.goBranch(0); await tester.pumpAndSettle(); expect(find.text('Screen A'), findsOneWidget); expect(find.text('Screen B - X'), findsNothing); routeState!.goBranch(1); await tester.pumpAndSettle(); expect(find.text('Screen A'), findsNothing); expect(find.text('Screen B - X'), findsOneWidget); }); testWidgets( 'Pushed non-descendant routes are correctly restored when ' 'navigating between branches in StatefulShellRoute', (WidgetTester tester) async { final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>(); StatefulNavigationShell? routeState; final List<RouteBase> routes = <RouteBase>[ GoRoute( path: '/common', builder: (BuildContext context, GoRouterState state) => Text('Common - ${state.extra}'), ), StatefulShellRoute.indexedStack( builder: (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) { routeState = navigationShell; return navigationShell; }, branches: <StatefulShellBranch>[ StatefulShellBranch(routes: <GoRoute>[ GoRoute( path: '/a', builder: (BuildContext context, GoRouterState state) => const Text('Screen A'), ), ]), StatefulShellBranch(routes: <GoRoute>[ GoRoute( path: '/b', builder: (BuildContext context, GoRouterState state) => const Text('Screen B'), ), ]), ], ), ]; final GoRouter router = await createRouter(routes, tester, initialLocation: '/a', navigatorKey: rootNavigatorKey); expect(find.text('Screen A'), findsOneWidget); router.go('/b'); await tester.pumpAndSettle(); expect(find.text('Screen A'), findsNothing); expect(find.text('Screen B'), findsOneWidget); // This push '/common' on top of entire stateful shell route page. router.push('/common', extra: 'X'); await tester.pumpAndSettle(); expect(find.text('Screen A'), findsNothing); expect(find.text('Screen B'), findsNothing); expect(find.text('Common - X'), findsOneWidget); routeState!.goBranch(0); await tester.pumpAndSettle(); expect(find.text('Screen A'), findsOneWidget); routeState!.goBranch(1); await tester.pumpAndSettle(); expect(find.text('Screen A'), findsNothing); expect(find.text('Screen B'), findsOneWidget); }); testWidgets( 'Redirects are correctly handled when switching branch in a ' 'StatefulShellRoute', (WidgetTester tester) async { final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>(); StatefulNavigationShell? routeState; final List<RouteBase> routes = <RouteBase>[ StatefulShellRoute.indexedStack( builder: (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) { routeState = navigationShell; return navigationShell; }, branches: <StatefulShellBranch>[ StatefulShellBranch(routes: <GoRoute>[ GoRoute( path: '/a', builder: (BuildContext context, GoRouterState state) => const Text('Screen A'), ), ]), StatefulShellBranch(routes: <GoRoute>[ GoRoute( path: '/b', builder: (BuildContext context, GoRouterState state) => const Text('Screen B'), routes: <RouteBase>[ GoRoute( path: 'details1', builder: (BuildContext context, GoRouterState state) => const Text('Screen B Detail1'), ), GoRoute( path: 'details2', builder: (BuildContext context, GoRouterState state) => const Text('Screen B Detail2'), ), ], ), ]), StatefulShellBranch(routes: <GoRoute>[ GoRoute( path: '/c', redirect: (_, __) => '/c/main2', ), GoRoute( path: '/c/main1', builder: (BuildContext context, GoRouterState state) => const Text('Screen C1'), ), GoRoute( path: '/c/main2', builder: (BuildContext context, GoRouterState state) => const Text('Screen C2'), ), ]), ], ), ]; String redirectDestinationBranchB = '/b/details1'; await createRouter( routes, tester, initialLocation: '/a', navigatorKey: rootNavigatorKey, redirect: (_, GoRouterState state) { if (state.uri.toString().startsWith('/b')) { return redirectDestinationBranchB; } return null; }, ); expect(find.text('Screen A'), findsOneWidget); expect(find.text('Screen B Detail'), findsNothing); routeState!.goBranch(1); await tester.pumpAndSettle(); expect(find.text('Screen A'), findsNothing); expect(find.text('Screen B Detail1'), findsOneWidget); routeState!.goBranch(2); await tester.pumpAndSettle(); expect(find.text('Screen A'), findsNothing); expect(find.text('Screen B Detail1'), findsNothing); expect(find.text('Screen C2'), findsOneWidget); redirectDestinationBranchB = '/b/details2'; routeState!.goBranch(1); await tester.pumpAndSettle(); expect(find.text('Screen A'), findsNothing); expect(find.text('Screen B Detail2'), findsOneWidget); expect(find.text('Screen C2'), findsNothing); }); testWidgets( 'Pushed top-level route is correctly handled by StatefulShellRoute', (WidgetTester tester) async { final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>(); final GlobalKey<NavigatorState> nestedNavigatorKey = GlobalKey<NavigatorState>(); StatefulNavigationShell? routeState; final List<RouteBase> routes = <RouteBase>[ // First level shell StatefulShellRoute.indexedStack( builder: (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) { routeState = navigationShell; return navigationShell; }, branches: <StatefulShellBranch>[ StatefulShellBranch(routes: <GoRoute>[ GoRoute( path: '/a', builder: (BuildContext context, GoRouterState state) => const Text('Screen A'), ), ]), StatefulShellBranch(routes: <RouteBase>[ // Second level / nested shell StatefulShellRoute.indexedStack( builder: (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) => navigationShell, branches: <StatefulShellBranch>[ StatefulShellBranch(routes: <GoRoute>[ GoRoute( path: '/b1', builder: (BuildContext context, GoRouterState state) => const Text('Screen B1'), ), ]), StatefulShellBranch( navigatorKey: nestedNavigatorKey, routes: <GoRoute>[ GoRoute( path: '/b2', builder: (BuildContext context, GoRouterState state) => const Text('Screen B2'), ), GoRoute( path: '/b2-modal', // We pass an explicit parentNavigatorKey here, to // properly test the logic in RouteBuilder, i.e. // routes with parentNavigatorKeys under the shell // should not be stripped. parentNavigatorKey: nestedNavigatorKey, builder: (BuildContext context, GoRouterState state) => const Text('Nested Modal'), ), ]), ], ), ]), ], ), GoRoute( path: '/top-modal', parentNavigatorKey: rootNavigatorKey, builder: (BuildContext context, GoRouterState state) => const Text('Top Modal'), ), ]; final GoRouter router = await createRouter(routes, tester, initialLocation: '/a', navigatorKey: rootNavigatorKey); expect(find.text('Screen A'), findsOneWidget); routeState!.goBranch(1); await tester.pumpAndSettle(); expect(find.text('Screen B1'), findsOneWidget); // Navigate nested (second level) shell to second branch router.go('/b2'); await tester.pumpAndSettle(); expect(find.text('Screen B2'), findsOneWidget); // Push route over second branch of nested (second level) shell router.push('/b2-modal'); await tester.pumpAndSettle(); expect(find.text('Nested Modal'), findsOneWidget); // Push top-level route while on second branch router.push('/top-modal'); await tester.pumpAndSettle(); expect(find.text('Top Modal'), findsOneWidget); // Return to shell and first branch router.go('/a'); await tester.pumpAndSettle(); expect(find.text('Screen A'), findsOneWidget); // Switch to second branch, which should only contain 'Nested Modal' // (in the nested shell) routeState!.goBranch(1); await tester.pumpAndSettle(); expect(find.text('Screen A'), findsNothing); expect(find.text('Screen B1'), findsNothing); expect(find.text('Screen B2'), findsNothing); expect(find.text('Top Modal'), findsNothing); expect(find.text('Nested Modal'), findsOneWidget); }); }); group('Imperative navigation', () { group('canPop', () { testWidgets( 'It should return false if Navigator.canPop() returns false.', (WidgetTester tester) async { final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); final GoRouter router = GoRouter( initialLocation: '/', navigatorKey: navigatorKey, routes: <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, _) { return Scaffold( body: TextButton( onPressed: () async { navigatorKey.currentState!.push( MaterialPageRoute<void>( builder: (BuildContext context) { return const Scaffold( body: Text('pageless route'), ); }, ), ); }, child: const Text('Push'), ), ); }, ), GoRoute(path: '/a', builder: (_, __) => const DummyScreen()), ], ); addTearDown(router.dispose); await tester.pumpWidget( MaterialApp.router( routeInformationProvider: router.routeInformationProvider, routeInformationParser: router.routeInformationParser, routerDelegate: router.routerDelegate), ); expect(router.canPop(), false); await tester.tap(find.text('Push')); await tester.pumpAndSettle(); expect( find.text('pageless route', skipOffstage: false), findsOneWidget); expect(router.canPop(), true); }, ); testWidgets( 'It checks if ShellRoute navigators can pop', (WidgetTester tester) async { final GlobalKey<NavigatorState> shellNavigatorKey = GlobalKey<NavigatorState>(); final GoRouter router = GoRouter( initialLocation: '/a', routes: <RouteBase>[ ShellRoute( navigatorKey: shellNavigatorKey, builder: (BuildContext context, GoRouterState state, Widget child) { return Scaffold( appBar: AppBar(title: const Text('Shell')), body: child, ); }, routes: <GoRoute>[ GoRoute( path: '/a', builder: (BuildContext context, _) { return Scaffold( body: TextButton( onPressed: () async { shellNavigatorKey.currentState!.push( MaterialPageRoute<void>( builder: (BuildContext context) { return const Scaffold( body: Text('pageless route'), ); }, ), ); }, child: const Text('Push'), ), ); }, ), ], ), ], ); addTearDown(router.dispose); await tester.pumpWidget( MaterialApp.router( routeInformationProvider: router.routeInformationProvider, routeInformationParser: router.routeInformationParser, routerDelegate: router.routerDelegate), ); expect(router.canPop(), false); expect(find.text('Push'), findsOneWidget); await tester.tap(find.text('Push')); await tester.pumpAndSettle(); expect( find.text('pageless route', skipOffstage: false), findsOneWidget); expect(router.canPop(), true); }, ); testWidgets( 'It checks if StatefulShellRoute navigators can pop', (WidgetTester tester) async { final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>(); final GoRouter router = GoRouter( navigatorKey: rootNavigatorKey, initialLocation: '/a', routes: <RouteBase>[ StatefulShellRoute.indexedStack( builder: mockStackedShellBuilder, branches: <StatefulShellBranch>[ StatefulShellBranch(routes: <GoRoute>[ GoRoute( path: '/a', builder: (BuildContext context, _) { return const Scaffold( body: Text('Screen A'), ); }, ), ]), StatefulShellBranch(routes: <GoRoute>[ GoRoute( path: '/b', builder: (BuildContext context, _) { return const Scaffold( body: Text('Screen B'), ); }, routes: <RouteBase>[ GoRoute( path: 'detail', builder: (BuildContext context, _) { return const Scaffold( body: Text('Screen B detail'), ); }, ), ], ), ]), ], ), ], ); addTearDown(router.dispose); await tester.pumpWidget( MaterialApp.router( routeInformationProvider: router.routeInformationProvider, routeInformationParser: router.routeInformationParser, routerDelegate: router.routerDelegate), ); expect(router.canPop(), false); router.go('/b/detail'); await tester.pumpAndSettle(); expect(find.text('Screen B detail', skipOffstage: false), findsOneWidget); expect(router.canPop(), true); // Verify that it is actually the StatefulShellRoute that reports // canPop = true expect(rootNavigatorKey.currentState?.canPop(), false); }, ); testWidgets('Pageless route should include in can pop', (WidgetTester tester) async { final GlobalKey<NavigatorState> root = GlobalKey<NavigatorState>(debugLabel: 'root'); final GlobalKey<NavigatorState> shell = GlobalKey<NavigatorState>(debugLabel: 'shell'); final GoRouter router = GoRouter( navigatorKey: root, routes: <RouteBase>[ ShellRoute( navigatorKey: shell, builder: (BuildContext context, GoRouterState state, Widget child) { return Scaffold( body: Center( child: Column( children: <Widget>[ const Text('Shell'), Expanded(child: child), ], ), ), ); }, routes: <RouteBase>[ GoRoute( path: '/', builder: (_, __) => const Text('A Screen'), ), ], ), ], ); addTearDown(router.dispose); await tester.pumpWidget(MaterialApp.router(routerConfig: router)); expect(router.canPop(), isFalse); expect(find.text('A Screen'), findsOneWidget); expect(find.text('Shell'), findsOneWidget); showDialog<void>( context: root.currentContext!, builder: (_) => const Text('A dialog')); await tester.pumpAndSettle(); expect(find.text('A dialog'), findsOneWidget); expect(router.canPop(), isTrue); }); }); group('pop', () { testWidgets( 'Should pop from the correct navigator when parentNavigatorKey is set', (WidgetTester tester) async { final GlobalKey<NavigatorState> root = GlobalKey<NavigatorState>(debugLabel: 'root'); final GlobalKey<NavigatorState> shell = GlobalKey<NavigatorState>(debugLabel: 'shell'); final GoRouter router = GoRouter( initialLocation: '/a/b', navigatorKey: root, routes: <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, _) { return const Scaffold( body: Text('Home'), ); }, routes: <RouteBase>[ ShellRoute( navigatorKey: shell, builder: (BuildContext context, GoRouterState state, Widget child) { return Scaffold( body: Center( child: Column( children: <Widget>[ const Text('Shell'), Expanded(child: child), ], ), ), ); }, routes: <RouteBase>[ GoRoute( path: 'a', builder: (_, __) => const Text('A Screen'), routes: <RouteBase>[ GoRoute( parentNavigatorKey: root, path: 'b', builder: (_, __) => const Text('B Screen'), ), ], ), ], ), ], ), ], ); addTearDown(router.dispose); await tester.pumpWidget( MaterialApp.router( routeInformationProvider: router.routeInformationProvider, routeInformationParser: router.routeInformationParser, routerDelegate: router.routerDelegate), ); expect(router.canPop(), isTrue); expect(find.text('B Screen'), findsOneWidget); expect(find.text('A Screen'), findsNothing); expect(find.text('Shell'), findsNothing); expect(find.text('Home'), findsNothing); router.pop(); await tester.pumpAndSettle(); expect(find.text('A Screen'), findsOneWidget); expect(find.text('Shell'), findsOneWidget); expect(router.canPop(), isTrue); router.pop(); await tester.pumpAndSettle(); expect(find.text('Home'), findsOneWidget); expect(find.text('Shell'), findsNothing); }, ); testWidgets('Should pop dialog if it is present', (WidgetTester tester) async { final GlobalKey<NavigatorState> root = GlobalKey<NavigatorState>(debugLabel: 'root'); final GlobalKey<NavigatorState> shell = GlobalKey<NavigatorState>(debugLabel: 'shell'); final GoRouter router = GoRouter( initialLocation: '/a', navigatorKey: root, routes: <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, _) { return const Scaffold( body: Text('Home'), ); }, routes: <RouteBase>[ ShellRoute( navigatorKey: shell, builder: (BuildContext context, GoRouterState state, Widget child) { return Scaffold( body: Center( child: Column( children: <Widget>[ const Text('Shell'), Expanded(child: child), ], ), ), ); }, routes: <RouteBase>[ GoRoute( path: 'a', builder: (_, __) => const Text('A Screen'), ), ], ), ], ), ], ); addTearDown(router.dispose); await tester.pumpWidget(MaterialApp.router(routerConfig: router)); expect(router.canPop(), isTrue); expect(find.text('A Screen'), findsOneWidget); expect(find.text('Shell'), findsOneWidget); expect(find.text('Home'), findsNothing); final Future<bool?> resultFuture = showDialog<bool>( context: root.currentContext!, builder: (_) => const Text('A dialog')); await tester.pumpAndSettle(); expect(find.text('A dialog'), findsOneWidget); expect(router.canPop(), isTrue); router.pop<bool>(true); await tester.pumpAndSettle(); expect(find.text('A Screen'), findsOneWidget); expect(find.text('Shell'), findsOneWidget); expect(find.text('A dialog'), findsNothing); final bool? result = await resultFuture; expect(result, isTrue); }); testWidgets('Triggers a Hero inside a ShellRoute', (WidgetTester tester) async { final UniqueKey heroKey = UniqueKey(); const String kHeroTag = 'hero'; final List<RouteBase> routes = <RouteBase>[ ShellRoute( builder: (BuildContext context, GoRouterState state, Widget child) { return child; }, routes: <GoRoute>[ GoRoute( path: '/a', builder: (BuildContext context, _) { return Hero( tag: kHeroTag, child: Container(), flightShuttleBuilder: (_, __, ___, ____, _____) { return Container(key: heroKey); }, ); }), GoRoute( path: '/b', builder: (BuildContext context, _) { return Hero( tag: kHeroTag, child: Container(), ); }), ], ) ]; final GoRouter router = await createRouter(routes, tester, initialLocation: '/a'); // check that flightShuttleBuilder widget is not yet present expect(find.byKey(heroKey), findsNothing); // start navigation router.go('/b'); await tester.pump(); await tester.pump(const Duration(milliseconds: 10)); // check that flightShuttleBuilder widget is visible expect(find.byKey(heroKey), isOnstage); // // Waits for the animation finishes. await tester.pumpAndSettle(); expect(find.byKey(heroKey), findsNothing); }); }); }); group('of', () { testWidgets( 'It should return the go router instance of the widget tree', (WidgetTester tester) async { const Key key = Key('key'); final List<RouteBase> routes = <RouteBase>[ GoRoute( path: '/', builder: (_, __) => const SizedBox(key: key), ), ]; final GoRouter router = await createRouter(routes, tester); final Element context = tester.element(find.byKey(key)); final GoRouter foundRouter = GoRouter.of(context); expect(foundRouter, router); }, ); testWidgets( 'It should throw if there is no go router in the widget tree', (WidgetTester tester) async { const Key key = Key('key'); await tester.pumpWidget(const SizedBox(key: key)); final Element context = tester.element(find.byKey(key)); expect(() => GoRouter.of(context), throwsA(anything)); }, ); }); group('maybeOf', () { testWidgets( 'It should return the go router instance of the widget tree', (WidgetTester tester) async { const Key key = Key('key'); final List<RouteBase> routes = <RouteBase>[ GoRoute( path: '/', builder: (_, __) => const SizedBox(key: key), ), ]; final GoRouter router = await createRouter(routes, tester); final Element context = tester.element(find.byKey(key)); final GoRouter? foundRouter = GoRouter.maybeOf(context); expect(foundRouter, router); }, ); testWidgets( 'It should return null if there is no go router in the widget tree', (WidgetTester tester) async { const Key key = Key('key'); await tester.pumpWidget(const SizedBox(key: key)); final Element context = tester.element(find.byKey(key)); expect(GoRouter.maybeOf(context), isNull); }, ); }); group('state restoration', () { testWidgets('Restores state correctly', (WidgetTester tester) async { final GlobalKey<DummyRestorableStatefulWidgetState> statefulWidgetKeyA = GlobalKey<DummyRestorableStatefulWidgetState>(); final List<RouteBase> routes = <RouteBase>[ GoRoute( path: '/a', pageBuilder: createPageBuilder( restorationId: 'screenA', child: const Text('Screen A')), routes: <RouteBase>[ GoRoute( path: 'detail', pageBuilder: createPageBuilder( restorationId: 'screenADetail', child: Column(children: <Widget>[ const Text('Screen A Detail'), DummyRestorableStatefulWidget( key: statefulWidgetKeyA, restorationId: 'counterA'), ])), ), ], ), ]; await createRouter(routes, tester, initialLocation: '/a/detail', restorationScopeId: 'test'); await tester.pumpAndSettle(); statefulWidgetKeyA.currentState?.increment(); expect(statefulWidgetKeyA.currentState?.counter, equals(1)); await tester.pumpAndSettle(); // Give state change time to persist await tester.restartAndRestore(); await tester.pumpAndSettle(); expect(find.text('Screen A Detail'), findsOneWidget); expect(statefulWidgetKeyA.currentState?.counter, equals(1)); }); testWidgets('Restores state of branches in StatefulShellRoute correctly', (WidgetTester tester) async { final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>(); final GlobalKey<DummyRestorableStatefulWidgetState> statefulWidgetKeyA = GlobalKey<DummyRestorableStatefulWidgetState>(); final GlobalKey<DummyRestorableStatefulWidgetState> statefulWidgetKeyB = GlobalKey<DummyRestorableStatefulWidgetState>(); final GlobalKey<DummyRestorableStatefulWidgetState> statefulWidgetKeyC = GlobalKey<DummyRestorableStatefulWidgetState>(); StatefulNavigationShell? routeState; final List<RouteBase> routes = <RouteBase>[ StatefulShellRoute.indexedStack( restorationScopeId: 'shell', pageBuilder: (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) { routeState = navigationShell; return MaterialPage<dynamic>( restorationId: 'shellWidget', child: navigationShell); }, branches: <StatefulShellBranch>[ StatefulShellBranch( restorationScopeId: 'branchA', routes: <GoRoute>[ GoRoute( path: '/a', pageBuilder: createPageBuilder( restorationId: 'screenA', child: const Text('Screen A')), routes: <RouteBase>[ GoRoute( path: 'detailA', pageBuilder: createPageBuilder( restorationId: 'screenADetail', child: Column(children: <Widget>[ const Text('Screen A Detail'), DummyRestorableStatefulWidget( key: statefulWidgetKeyA, restorationId: 'counterA'), ])), ), ], ), ]), StatefulShellBranch( restorationScopeId: 'branchB', routes: <GoRoute>[ GoRoute( path: '/b', pageBuilder: createPageBuilder( restorationId: 'screenB', child: const Text('Screen B')), routes: <RouteBase>[ GoRoute( path: 'detailB', pageBuilder: createPageBuilder( restorationId: 'screenBDetail', child: Column(children: <Widget>[ const Text('Screen B Detail'), DummyRestorableStatefulWidget( key: statefulWidgetKeyB, restorationId: 'counterB'), ])), ), ], ), ]), StatefulShellBranch(routes: <GoRoute>[ GoRoute( path: '/c', pageBuilder: createPageBuilder( restorationId: 'screenC', child: const Text('Screen C')), routes: <RouteBase>[ GoRoute( path: 'detailC', pageBuilder: createPageBuilder( restorationId: 'screenCDetail', child: Column(children: <Widget>[ const Text('Screen C Detail'), DummyRestorableStatefulWidget( key: statefulWidgetKeyC, restorationId: 'counterC'), ])), ), ], ), ]), ], ), ]; final GoRouter router = await createRouter(routes, tester, initialLocation: '/a/detailA', navigatorKey: rootNavigatorKey, restorationScopeId: 'test'); await tester.pumpAndSettle(); statefulWidgetKeyA.currentState?.increment(); expect(statefulWidgetKeyA.currentState?.counter, equals(1)); router.go('/b/detailB'); await tester.pumpAndSettle(); statefulWidgetKeyB.currentState?.increment(); expect(statefulWidgetKeyB.currentState?.counter, equals(1)); router.go('/c/detailC'); await tester.pumpAndSettle(); statefulWidgetKeyC.currentState?.increment(); expect(statefulWidgetKeyC.currentState?.counter, equals(1)); routeState!.goBranch(0); await tester.pumpAndSettle(); expect(find.text('Screen A Detail'), findsOneWidget); await tester.restartAndRestore(); await tester.pumpAndSettle(); expect(find.text('Screen A Detail'), findsOneWidget); expect(statefulWidgetKeyA.currentState?.counter, equals(1)); routeState!.goBranch(1); await tester.pumpAndSettle(); expect(find.text('Screen B Detail'), findsOneWidget); expect(statefulWidgetKeyB.currentState?.counter, equals(1)); routeState!.goBranch(2); await tester.pumpAndSettle(); expect(find.text('Screen C Detail'), findsOneWidget); // State of branch C should not have been restored expect(statefulWidgetKeyC.currentState?.counter, equals(0)); }); testWidgets( 'Restores state of imperative routes in StatefulShellRoute correctly', (WidgetTester tester) async { final GlobalKey<NavigatorState> rootNavigatorKey = GlobalKey<NavigatorState>(); final GlobalKey<DummyRestorableStatefulWidgetState> statefulWidgetKeyA = GlobalKey<DummyRestorableStatefulWidgetState>(); final GlobalKey<DummyRestorableStatefulWidgetState> statefulWidgetKeyB = GlobalKey<DummyRestorableStatefulWidgetState>(); StatefulNavigationShell? routeStateRoot; StatefulNavigationShell? routeStateNested; final List<RouteBase> routes = <RouteBase>[ StatefulShellRoute.indexedStack( restorationScopeId: 'shell', pageBuilder: (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) { routeStateRoot = navigationShell; return MaterialPage<dynamic>( restorationId: 'shellWidget', child: navigationShell); }, branches: <StatefulShellBranch>[ StatefulShellBranch( restorationScopeId: 'branchA', routes: <GoRoute>[ GoRoute( path: '/a', pageBuilder: createPageBuilder( restorationId: 'screenA', child: const Text('Screen A')), routes: <RouteBase>[ GoRoute( path: 'detailA', pageBuilder: createPageBuilder( restorationId: 'screenADetail', child: Column(children: <Widget>[ const Text('Screen A Detail'), DummyRestorableStatefulWidget( key: statefulWidgetKeyA, restorationId: 'counterA'), ])), ), ], ), ]), StatefulShellBranch( restorationScopeId: 'branchB', routes: <RouteBase>[ StatefulShellRoute.indexedStack( restorationScopeId: 'branchB-nested-shell', pageBuilder: (BuildContext context, GoRouterState state, StatefulNavigationShell navigationShell) { routeStateNested = navigationShell; return MaterialPage<dynamic>( restorationId: 'shellWidget-nested', child: navigationShell); }, branches: <StatefulShellBranch>[ StatefulShellBranch( restorationScopeId: 'branchB-nested', routes: <GoRoute>[ GoRoute( path: '/b', pageBuilder: createPageBuilder( restorationId: 'screenB', child: const Text('Screen B')), routes: <RouteBase>[ GoRoute( path: 'detailB', pageBuilder: createPageBuilder( restorationId: 'screenBDetail', child: Column(children: <Widget>[ const Text('Screen B Detail'), DummyRestorableStatefulWidget( key: statefulWidgetKeyB, restorationId: 'counterB'), ])), ), ], ), ]), StatefulShellBranch( restorationScopeId: 'branchC-nested', routes: <GoRoute>[ GoRoute( path: '/c', pageBuilder: createPageBuilder( restorationId: 'screenC', child: const Text('Screen C')), ), ]), ]) ]), ], ), ]; final GoRouter router = await createRouter(routes, tester, initialLocation: '/a/detailA', navigatorKey: rootNavigatorKey, restorationScopeId: 'test'); await tester.pumpAndSettle(); statefulWidgetKeyA.currentState?.increment(); expect(statefulWidgetKeyA.currentState?.counter, equals(1)); routeStateRoot!.goBranch(1); await tester.pumpAndSettle(); router.go('/b/detailB'); await tester.pumpAndSettle(); statefulWidgetKeyB.currentState?.increment(); expect(statefulWidgetKeyB.currentState?.counter, equals(1)); routeStateRoot!.goBranch(0); await tester.pumpAndSettle(); expect(find.text('Screen A Detail'), findsOneWidget); expect(find.text('Screen B'), findsNothing); expect(find.text('Screen B Pushed Detail'), findsNothing); await tester.restartAndRestore(); await tester.pumpAndSettle(); expect(find.text('Screen A Detail'), findsOneWidget); expect(find.text('Screen B'), findsNothing); expect(find.text('Screen B Pushed Detail'), findsNothing); expect(statefulWidgetKeyA.currentState?.counter, equals(1)); routeStateRoot!.goBranch(1); await tester.pumpAndSettle(); expect(find.text('Screen A Detail'), findsNothing); expect(find.text('Screen B'), findsNothing); expect(find.text('Screen B Detail'), findsOneWidget); expect(statefulWidgetKeyB.currentState?.counter, equals(1)); routeStateNested!.goBranch(1); await tester.pumpAndSettle(); routeStateNested!.goBranch(0); await tester.pumpAndSettle(); expect(find.text('Screen B Detail'), findsOneWidget); expect(statefulWidgetKeyB.currentState?.counter, equals(1)); }); }); ///Regression tests for https://github.com/flutter/flutter/issues/132557 group('overridePlatformDefaultLocation', () { test('No initial location provided', () { expect( () => GoRouter( overridePlatformDefaultLocation: true, routes: <RouteBase>[ GoRoute( path: '/a', builder: (BuildContext context, GoRouterState state) => const Placeholder(), ), GoRoute( path: '/b', builder: (BuildContext context, GoRouterState state) => const Placeholder(), ), ], ), throwsA(const TypeMatcher<AssertionError>())); }); testWidgets('Test override using routeInformationProvider', (WidgetTester tester) async { tester.binding.platformDispatcher.defaultRouteNameTestValue = '/some-route'; final String platformRoute = WidgetsBinding.instance.platformDispatcher.defaultRouteName; const String expectedInitialRoute = '/kyc'; expect(platformRoute != expectedInitialRoute, isTrue); final List<RouteBase> routes = <RouteBase>[ GoRoute( path: '/abc', builder: (BuildContext context, GoRouterState state) => const Placeholder(), ), GoRoute( path: '/bcd', builder: (BuildContext context, GoRouterState state) => const Placeholder(), ), ]; final GoRouter router = await createRouter( routes, tester, overridePlatformDefaultLocation: true, initialLocation: expectedInitialRoute, ); expect(router.routeInformationProvider.value.uri.toString(), expectedInitialRoute); }); }); testWidgets( 'test the pathParameters in redirect when the Router is recreated', (WidgetTester tester) async { final GoRouter router = GoRouter( initialLocation: '/foo', routes: <RouteBase>[ GoRoute( path: '/foo', builder: dummy, routes: <GoRoute>[ GoRoute( path: ':id', redirect: (_, GoRouterState state) { expect(state.pathParameters['id'], isNotNull); return null; }, builder: dummy, ), ], ), ], ); await tester.pumpWidget( MaterialApp.router( key: UniqueKey(), routerConfig: router, ), ); router.push('/foo/123'); await tester.pump(); // wait reportRouteInformation await tester.pumpWidget( MaterialApp.router( key: UniqueKey(), routerConfig: router, ), ); }); } class TestInheritedNotifier extends InheritedNotifier<ValueNotifier<String>> { const TestInheritedNotifier({ super.key, required super.notifier, required super.child, }); } class IsRouteUpdateCall extends Matcher { const IsRouteUpdateCall(this.uri, this.replace, this.state); final String uri; final bool replace; final Object? state; @override bool matches(dynamic item, Map<dynamic, dynamic> matchState) { if (item is! MethodCall) { return false; } if (item.method != 'routeInformationUpdated') { return false; } if (item.arguments is! Map) { return false; } final Map<String, dynamic> arguments = item.arguments as Map<String, dynamic>; // TODO(chunhtai): update this when minimum flutter version includes // https://github.com/flutter/flutter/pull/119968. // https://github.com/flutter/flutter/issues/124045. if (arguments['uri'] != uri && arguments['location'] != uri) { return false; } if (!const DeepCollectionEquality().equals(arguments['state'], state)) { return false; } return arguments['replace'] == replace; } @override Description describe(Description description) { return description .add("has method name: 'routeInformationUpdated'") .add(' with uri: ') .addDescriptionOf(uri) .add(' with state: ') .addDescriptionOf(state) .add(' with replace: ') .addDescriptionOf(replace); } }
packages/packages/go_router/test/go_router_test.dart/0
{ "file_path": "packages/packages/go_router/test/go_router_test.dart", "repo_id": "packages", "token_count": 88356 }
1,002
// Copyright 2013 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:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import 'test_helpers.dart'; void main() { testWidgets('routing config works', (WidgetTester tester) async { final ValueNotifier<RoutingConfig> config = ValueNotifier<RoutingConfig>( RoutingConfig( routes: <RouteBase>[ GoRoute(path: '/', builder: (_, __) => const Text('home')), ], redirect: (_, __) => '/', ), ); addTearDown(config.dispose); final GoRouter router = await createRouterWithRoutingConfig(config, tester); expect(find.text('home'), findsOneWidget); router.go('/abcd'); // should be redirected to home await tester.pumpAndSettle(); expect(find.text('home'), findsOneWidget); }); testWidgets('routing config works after builder changes', (WidgetTester tester) async { final ValueNotifier<RoutingConfig> config = ValueNotifier<RoutingConfig>( RoutingConfig( routes: <RouteBase>[ GoRoute(path: '/', builder: (_, __) => const Text('home')), ], ), ); addTearDown(config.dispose); await createRouterWithRoutingConfig(config, tester); expect(find.text('home'), findsOneWidget); config.value = RoutingConfig( routes: <RouteBase>[ GoRoute(path: '/', builder: (_, __) => const Text('home1')), ], ); await tester.pumpAndSettle(); expect(find.text('home1'), findsOneWidget); }); testWidgets('routing config works after routing changes', (WidgetTester tester) async { final ValueNotifier<RoutingConfig> config = ValueNotifier<RoutingConfig>( RoutingConfig( routes: <RouteBase>[ GoRoute(path: '/', builder: (_, __) => const Text('home')), ], ), ); addTearDown(config.dispose); final GoRouter router = await createRouterWithRoutingConfig( config, tester, errorBuilder: (_, __) => const Text('error'), ); expect(find.text('home'), findsOneWidget); // Sanity check. router.go('/abc'); await tester.pumpAndSettle(); expect(find.text('error'), findsOneWidget); config.value = RoutingConfig( routes: <RouteBase>[ GoRoute(path: '/', builder: (_, __) => const Text('home')), GoRoute(path: '/abc', builder: (_, __) => const Text('/abc')), ], ); await tester.pumpAndSettle(); expect(find.text('/abc'), findsOneWidget); }); testWidgets('routing config works after routing changes case 2', (WidgetTester tester) async { final ValueNotifier<RoutingConfig> config = ValueNotifier<RoutingConfig>( RoutingConfig( routes: <RouteBase>[ GoRoute(path: '/', builder: (_, __) => const Text('home')), GoRoute(path: '/abc', builder: (_, __) => const Text('/abc')), ], ), ); addTearDown(config.dispose); final GoRouter router = await createRouterWithRoutingConfig( config, tester, errorBuilder: (_, __) => const Text('error'), ); expect(find.text('home'), findsOneWidget); // Sanity check. router.go('/abc'); await tester.pumpAndSettle(); expect(find.text('/abc'), findsOneWidget); config.value = RoutingConfig( routes: <RouteBase>[ GoRoute(path: '/', builder: (_, __) => const Text('home')), ], ); await tester.pumpAndSettle(); expect(find.text('error'), findsOneWidget); }); testWidgets('routing config works with named route', (WidgetTester tester) async { final ValueNotifier<RoutingConfig> config = ValueNotifier<RoutingConfig>( RoutingConfig( routes: <RouteBase>[ GoRoute(path: '/', builder: (_, __) => const Text('home')), GoRoute( path: '/abc', name: 'abc', builder: (_, __) => const Text('/abc')), ], ), ); addTearDown(config.dispose); final GoRouter router = await createRouterWithRoutingConfig( config, tester, errorBuilder: (_, __) => const Text('error'), ); expect(find.text('home'), findsOneWidget); // Sanity check. router.goNamed('abc'); await tester.pumpAndSettle(); expect(find.text('/abc'), findsOneWidget); config.value = RoutingConfig( routes: <RouteBase>[ GoRoute( path: '/', name: 'home', builder: (_, __) => const Text('home')), GoRoute( path: '/abc', name: 'def', builder: (_, __) => const Text('def')), ], ); await tester.pumpAndSettle(); expect(find.text('def'), findsOneWidget); router.goNamed('home'); await tester.pumpAndSettle(); expect(find.text('home'), findsOneWidget); router.goNamed('def'); await tester.pumpAndSettle(); expect(find.text('def'), findsOneWidget); }); }
packages/packages/go_router/test/routing_config_test.dart/0
{ "file_path": "packages/packages/go_router/test/routing_config_test.dart", "repo_id": "packages", "token_count": 2016 }
1,003
# Configuration for https://pub.dev/packages/build_config # In general, this file is NOT needed when using go_router_builder # It is included in this case to suppress lints that are enforced in the source # repository but not this builder. targets: $default: builders: source_gen|combining_builder: options: ignore_for_file: - always_specify_types - public_member_api_docs
packages/packages/go_router_builder/example/build.yaml/0
{ "file_path": "packages/packages/go_router_builder/example/build.yaml", "repo_id": "packages", "token_count": 151 }
1,004
// GENERATED CODE - DO NOT MODIFY BY HAND // ignore_for_file: always_specify_types, public_member_api_docs part of 'simple_example.dart'; // ************************************************************************** // GoRouterGenerator // ************************************************************************** List<RouteBase> get $appRoutes => [ $homeRoute, ]; RouteBase get $homeRoute => GoRouteData.$route( path: '/', name: 'Home', factory: $HomeRouteExtension._fromState, routes: [ GoRouteData.$route( path: 'family/:familyId', factory: $FamilyRouteExtension._fromState, ), ], ); extension $HomeRouteExtension on HomeRoute { static HomeRoute _fromState(GoRouterState state) => const HomeRoute(); String get location => GoRouteData.$location( '/', ); void go(BuildContext context) => context.go(location); Future<T?> push<T>(BuildContext context) => context.push<T>(location); void pushReplacement(BuildContext context) => context.pushReplacement(location); void replace(BuildContext context) => context.replace(location); } extension $FamilyRouteExtension on FamilyRoute { static FamilyRoute _fromState(GoRouterState state) => FamilyRoute( state.pathParameters['familyId']!, ); String get location => GoRouteData.$location( '/family/${Uri.encodeComponent(familyId)}', ); void go(BuildContext context) => context.go(location); Future<T?> push<T>(BuildContext context) => context.push<T>(location); void pushReplacement(BuildContext context) => context.pushReplacement(location); void replace(BuildContext context) => context.replace(location); }
packages/packages/go_router_builder/example/lib/simple_example.g.dart/0
{ "file_path": "packages/packages/go_router_builder/example/lib/simple_example.g.dart", "repo_id": "packages", "token_count": 565 }
1,005
// Copyright 2013 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. final RegExp _parameterRegExp = RegExp(r':(\w+)(\((?:\\.|[^\\()])+\))?'); /// Extracts the path parameters from a [pattern] such as `/user/:id`. /// /// The path parameters can be specified by prefixing them with `:`. /// /// For example: /// /// ```dart /// final pattern = '/user/:id/book/:bookId'; /// final pathParameters = pathParametersFromPattern(pattern); // {'id', 'bookId'} /// ``` Set<String> pathParametersFromPattern(String pattern) => <String>{ for (final RegExpMatch match in _parameterRegExp.allMatches(pattern)) match[1]!, }; /// Reconstructs the full path from a [pattern] and path parameters. /// /// For example: /// /// ```dart /// final pattern = '/family/:id'; /// final path = patternToPath(pattern, {'id': 'family-id'}); // '/family/family-id' /// ``` String patternToPath(String pattern, Map<String, String> pathParameters) { final StringBuffer buffer = StringBuffer(); int start = 0; for (final RegExpMatch match in _parameterRegExp.allMatches(pattern)) { if (match.start > start) { buffer.write(pattern.substring(start, match.start)); } final String name = match[1]!; buffer.write(pathParameters[name]); start = match.end; } if (start < pattern.length) { buffer.write(pattern.substring(start)); } return buffer.toString(); }
packages/packages/go_router_builder/lib/src/path_utils.dart/0
{ "file_path": "packages/packages/go_router_builder/lib/src/path_utils.dart", "repo_id": "packages", "token_count": 492 }
1,006
RouteBase get $iterableWithEnumRoute => GoRouteData.$route( path: '/iterable-with-enum', factory: $IterableWithEnumRouteExtension._fromState, ); extension $IterableWithEnumRouteExtension on IterableWithEnumRoute { static IterableWithEnumRoute _fromState(GoRouterState state) => IterableWithEnumRoute( param: state.uri.queryParametersAll['param'] ?.map(_$EnumOnlyUsedInIterableEnumMap._$fromName), ); String get location => GoRouteData.$location( '/iterable-with-enum', queryParams: { if (param != null) 'param': param?.map((e) => _$EnumOnlyUsedInIterableEnumMap[e]).toList(), }, ); void go(BuildContext context) => context.go(location); Future<T?> push<T>(BuildContext context) => context.push<T>(location); void pushReplacement(BuildContext context) => context.pushReplacement(location); void replace(BuildContext context) => context.replace(location); } const _$EnumOnlyUsedInIterableEnumMap = { EnumOnlyUsedInIterable.a: 'a', EnumOnlyUsedInIterable.b: 'b', EnumOnlyUsedInIterable.c: 'c', }; extension<T extends Enum> on Map<T, String> { T _$fromName(String value) => entries.singleWhere((element) => element.value == value).key; }
packages/packages/go_router_builder/test_inputs/iterable_with_enum.dart.expect/0
{ "file_path": "packages/packages/go_router_builder/test_inputs/iterable_with_enum.dart.expect", "repo_id": "packages", "token_count": 505 }
1,007
RouteBase get $nullableRequiredParamNotInPath => GoRouteData.$route( path: 'bob', factory: $NullableRequiredParamNotInPathExtension._fromState, ); extension $NullableRequiredParamNotInPathExtension on NullableRequiredParamNotInPath { static NullableRequiredParamNotInPath _fromState(GoRouterState state) => NullableRequiredParamNotInPath( id: _$convertMapValue('id', state.uri.queryParameters, int.parse), ); String get location => GoRouteData.$location( 'bob', queryParams: { if (id != null) 'id': id!.toString(), }, ); void go(BuildContext context) => context.go(location); Future<T?> push<T>(BuildContext context) => context.push<T>(location); void pushReplacement(BuildContext context) => context.pushReplacement(location); void replace(BuildContext context) => context.replace(location); } T? _$convertMapValue<T>( String key, Map<String, String> map, T Function(String) converter, ) { final value = map[key]; return value == null ? null : converter(value); }
packages/packages/go_router_builder/test_inputs/required_parameters_not_in_path_can_be_null.dart.expect/0
{ "file_path": "packages/packages/go_router_builder/test_inputs/required_parameters_not_in_path_can_be_null.dart.expect", "repo_id": "packages", "token_count": 382 }
1,008
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:js_interop'; import 'package:web/web.dart' as web; import 'js_interop/load_callback.dart'; import 'js_interop/package_web_tweaks.dart'; // The URL from which the script should be downloaded. const String _url = 'https://accounts.google.com/gsi/client'; // The default TrustedPolicy name that will be used to inject the script. const String _defaultTrustedPolicyName = 'gis-dart'; /// Loads the GIS SDK for web, using Trusted Types API when available. Future<void> loadWebSdk({ web.HTMLElement? target, String trustedTypePolicyName = _defaultTrustedPolicyName, }) { final Completer<void> completer = Completer<void>(); onGoogleLibraryLoad = () => completer.complete(); // If TrustedTypes are available, prepare a trusted URL. web.TrustedScriptURL? trustedUrl; if (web.window.nullableTrustedTypes != null) { web.console.debug( 'TrustedTypes available. Creating policy: $trustedTypePolicyName'.toJS, ); try { final web.TrustedTypePolicy policy = web.window.trustedTypes.createPolicy( trustedTypePolicyName, web.TrustedTypePolicyOptions( createScriptURL: ((JSString url) => _url).toJS, )); trustedUrl = policy.createScriptURLNoArgs(_url); } catch (e) { throw TrustedTypesException(e.toString()); } } final web.HTMLScriptElement script = web.document.createElement('script') as web.HTMLScriptElement ..async = true ..defer = true; if (trustedUrl != null) { script.trustedSrc = trustedUrl; } else { script.src = _url; } (target ?? web.document.head!).appendChild(script); return completer.future; } /// Exception thrown if the Trusted Types feature is supported, enabled, and it /// has prevented this loader from injecting the JS SDK. class TrustedTypesException implements Exception { /// TrustedTypesException(this.message); /// The message of the exception final String message; @override String toString() => 'TrustedTypesException: $message'; }
packages/packages/google_identity_services_web/lib/src/js_loader.dart/0
{ "file_path": "packages/packages/google_identity_services_web/lib/src/js_loader.dart", "repo_id": "packages", "token_count": 734 }
1,009
// Copyright 2013 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:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart'; import 'fake_google_maps_flutter_platform.dart'; void main() { late FakeGoogleMapsFlutterPlatform platform; setUp(() { platform = FakeGoogleMapsFlutterPlatform(); GoogleMapsFlutterPlatform.instance = platform; }); testWidgets('Initial camera position', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), ), ), ); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.widgetConfiguration.initialCameraPosition, const CameraPosition(target: LatLng(10.0, 15.0))); }); testWidgets('Initial camera position change is a no-op', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), ), ), ); await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 16.0)), ), ), ); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.widgetConfiguration.initialCameraPosition, const CameraPosition(target: LatLng(10.0, 15.0))); }); testWidgets('Can update compassEnabled', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), compassEnabled: false, ), ), ); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.mapConfiguration.compassEnabled, false); await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), ), ), ); expect(map.mapConfiguration.compassEnabled, true); }); testWidgets('Can update mapToolbarEnabled', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), mapToolbarEnabled: false, ), ), ); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.mapConfiguration.mapToolbarEnabled, false); await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), ), ), ); expect(map.mapConfiguration.mapToolbarEnabled, true); }); testWidgets('Can update cameraTargetBounds', (WidgetTester tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), cameraTargetBounds: CameraTargetBounds( LatLngBounds( southwest: const LatLng(10.0, 20.0), northeast: const LatLng(30.0, 40.0), ), ), ), ), ); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect( map.mapConfiguration.cameraTargetBounds, CameraTargetBounds( LatLngBounds( southwest: const LatLng(10.0, 20.0), northeast: const LatLng(30.0, 40.0), ), )); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), cameraTargetBounds: CameraTargetBounds( LatLngBounds( southwest: const LatLng(16.0, 20.0), northeast: const LatLng(30.0, 40.0), ), ), ), ), ); expect( map.mapConfiguration.cameraTargetBounds, CameraTargetBounds( LatLngBounds( southwest: const LatLng(16.0, 20.0), northeast: const LatLng(30.0, 40.0), ), )); }); testWidgets('Can update mapType', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), mapType: MapType.hybrid, ), ), ); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.mapConfiguration.mapType, MapType.hybrid); await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), mapType: MapType.satellite, ), ), ); expect(map.mapConfiguration.mapType, MapType.satellite); }); testWidgets('Can update minMaxZoom', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), minMaxZoomPreference: MinMaxZoomPreference(1.0, 3.0), ), ), ); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.mapConfiguration.minMaxZoomPreference, const MinMaxZoomPreference(1.0, 3.0)); await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), ), ), ); expect(map.mapConfiguration.minMaxZoomPreference, MinMaxZoomPreference.unbounded); }); testWidgets('Can update rotateGesturesEnabled', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), rotateGesturesEnabled: false, ), ), ); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.mapConfiguration.rotateGesturesEnabled, false); await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), ), ), ); expect(map.mapConfiguration.rotateGesturesEnabled, true); }); testWidgets('Can update scrollGesturesEnabled', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), scrollGesturesEnabled: false, ), ), ); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.mapConfiguration.scrollGesturesEnabled, false); await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), ), ), ); expect(map.mapConfiguration.scrollGesturesEnabled, true); }); testWidgets('Can update tiltGesturesEnabled', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), tiltGesturesEnabled: false, ), ), ); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.mapConfiguration.tiltGesturesEnabled, false); await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), ), ), ); expect(map.mapConfiguration.tiltGesturesEnabled, true); }); testWidgets('Can update trackCameraPosition', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), ), ), ); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.mapConfiguration.trackCameraPosition, false); await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), onCameraMove: (CameraPosition position) {}, ), ), ); expect(map.mapConfiguration.trackCameraPosition, true); }); testWidgets('Can update zoomGesturesEnabled', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), zoomGesturesEnabled: false, ), ), ); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.mapConfiguration.zoomGesturesEnabled, false); await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), ), ), ); expect(map.mapConfiguration.zoomGesturesEnabled, true); }); testWidgets('Can update zoomControlsEnabled', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), zoomControlsEnabled: false, ), ), ); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.mapConfiguration.zoomControlsEnabled, false); await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), ), ), ); expect(map.mapConfiguration.zoomControlsEnabled, true); }); testWidgets('Can update myLocationEnabled', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), ), ), ); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.mapConfiguration.myLocationEnabled, false); await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), myLocationEnabled: true, ), ), ); expect(map.mapConfiguration.myLocationEnabled, true); }); testWidgets('Can update myLocationButtonEnabled', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), ), ), ); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.mapConfiguration.myLocationButtonEnabled, true); await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), myLocationButtonEnabled: false, ), ), ); expect(map.mapConfiguration.myLocationButtonEnabled, false); }); testWidgets('Is default padding 0', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), ), ), ); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.mapConfiguration.padding, EdgeInsets.zero); }); testWidgets('Can update padding', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), ), ), ); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.mapConfiguration.padding, EdgeInsets.zero); await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), padding: EdgeInsets.fromLTRB(10, 20, 30, 40), ), ), ); expect(map.mapConfiguration.padding, const EdgeInsets.fromLTRB(10, 20, 30, 40)); await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), padding: EdgeInsets.fromLTRB(50, 60, 70, 80), ), ), ); expect(map.mapConfiguration.padding, const EdgeInsets.fromLTRB(50, 60, 70, 80)); }); testWidgets('Can update traffic', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), ), ), ); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.mapConfiguration.trafficEnabled, false); await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), trafficEnabled: true, ), ), ); expect(map.mapConfiguration.trafficEnabled, true); }); testWidgets('Can update buildings', (WidgetTester tester) async { await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), buildingsEnabled: false, ), ), ); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.mapConfiguration.buildingsEnabled, false); await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), ), ), ); expect(map.mapConfiguration.buildingsEnabled, true); }); testWidgets('Can update style', (WidgetTester tester) async { const String initialStyle = '[]'; await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), style: initialStyle, ), ), ); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.mapConfiguration.style, initialStyle); await tester.pumpWidget( const Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: CameraPosition(target: LatLng(10.0, 15.0)), ), ), ); expect(map.mapConfiguration.style, ''); }); }
packages/packages/google_maps_flutter/google_maps_flutter/test/google_map_test.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter/test/google_map_test.dart", "repo_id": "packages", "token_count": 6894 }
1,010
// Copyright 2013 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. package io.flutter.plugins.googlemaps; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.model.Circle; import com.google.android.gms.maps.model.CircleOptions; import io.flutter.plugin.common.MethodChannel; import java.util.HashMap; import java.util.List; import java.util.Map; class CirclesController { private final Map<String, CircleController> circleIdToController; private final Map<String, String> googleMapsCircleIdToDartCircleId; private final MethodChannel methodChannel; private final float density; private GoogleMap googleMap; CirclesController(MethodChannel methodChannel, float density) { this.circleIdToController = new HashMap<>(); this.googleMapsCircleIdToDartCircleId = new HashMap<>(); this.methodChannel = methodChannel; this.density = density; } void setGoogleMap(GoogleMap googleMap) { this.googleMap = googleMap; } void addCircles(List<Object> circlesToAdd) { if (circlesToAdd != null) { for (Object circleToAdd : circlesToAdd) { addCircle(circleToAdd); } } } void changeCircles(List<Object> circlesToChange) { if (circlesToChange != null) { for (Object circleToChange : circlesToChange) { changeCircle(circleToChange); } } } void removeCircles(List<Object> circleIdsToRemove) { if (circleIdsToRemove == null) { return; } for (Object rawCircleId : circleIdsToRemove) { if (rawCircleId == null) { continue; } String circleId = (String) rawCircleId; final CircleController circleController = circleIdToController.remove(circleId); if (circleController != null) { circleController.remove(); googleMapsCircleIdToDartCircleId.remove(circleController.getGoogleMapsCircleId()); } } } boolean onCircleTap(String googleCircleId) { String circleId = googleMapsCircleIdToDartCircleId.get(googleCircleId); if (circleId == null) { return false; } methodChannel.invokeMethod("circle#onTap", Convert.circleIdToJson(circleId)); CircleController circleController = circleIdToController.get(circleId); if (circleController != null) { return circleController.consumeTapEvents(); } return false; } private void addCircle(Object circle) { if (circle == null) { return; } CircleBuilder circleBuilder = new CircleBuilder(density); String circleId = Convert.interpretCircleOptions(circle, circleBuilder); CircleOptions options = circleBuilder.build(); addCircle(circleId, options, circleBuilder.consumeTapEvents()); } private void addCircle(String circleId, CircleOptions circleOptions, boolean consumeTapEvents) { final Circle circle = googleMap.addCircle(circleOptions); CircleController controller = new CircleController(circle, consumeTapEvents, density); circleIdToController.put(circleId, controller); googleMapsCircleIdToDartCircleId.put(circle.getId(), circleId); } private void changeCircle(Object circle) { if (circle == null) { return; } String circleId = getCircleId(circle); CircleController circleController = circleIdToController.get(circleId); if (circleController != null) { Convert.interpretCircleOptions(circle, circleController); } } @SuppressWarnings("unchecked") private static String getCircleId(Object circle) { Map<String, Object> circleMap = (Map<String, Object>) circle; return (String) circleMap.get("circleId"); } }
packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/CirclesController.java/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/CirclesController.java", "repo_id": "packages", "token_count": 1246 }
1,011
// Copyright 2013 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. package io.flutter.plugins.googlemaps; import com.google.android.gms.maps.model.LatLng; import java.util.List; /** Receiver of Polygon configuration options. */ interface PolygonOptionsSink { void setConsumeTapEvents(boolean consumetapEvents); void setFillColor(int color); void setStrokeColor(int color); void setGeodesic(boolean geodesic); void setPoints(List<LatLng> points); void setHoles(List<List<LatLng>> holes); void setVisible(boolean visible); void setStrokeWidth(float width); void setZIndex(float zIndex); }
packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/PolygonOptionsSink.java/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/PolygonOptionsSink.java", "repo_id": "packages", "token_count": 220 }
1,012
// Copyright 2013 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. package io.flutter.plugins.googlemaps; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugin.common.MethodCodec; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; import org.mockito.Mockito; public class MarkersControllerTest { @Test public void controller_OnMarkerDragStart() { final MethodChannel methodChannel = spy(new MethodChannel(mock(BinaryMessenger.class), "no-name", mock(MethodCodec.class))); final MarkersController controller = new MarkersController(methodChannel); final GoogleMap googleMap = mock(GoogleMap.class); controller.setGoogleMap(googleMap); final Marker marker = mock(Marker.class); final String googleMarkerId = "abc123"; when(marker.getId()).thenReturn(googleMarkerId); when(googleMap.addMarker(any(MarkerOptions.class))).thenReturn(marker); final LatLng latLng = new LatLng(1.1, 2.2); final Map<String, String> markerOptions = new HashMap<>(); markerOptions.put("markerId", googleMarkerId); final List<Object> markers = Arrays.<Object>asList(markerOptions); controller.addMarkers(markers); controller.onMarkerDragStart(googleMarkerId, latLng); final List<Double> points = new ArrayList<>(); points.add(latLng.latitude); points.add(latLng.longitude); final Map<String, Object> data = new HashMap<>(); data.put("markerId", googleMarkerId); data.put("position", points); Mockito.verify(methodChannel).invokeMethod("marker#onDragStart", data); } @Test public void controller_OnMarkerDragEnd() { final MethodChannel methodChannel = spy(new MethodChannel(mock(BinaryMessenger.class), "no-name", mock(MethodCodec.class))); final MarkersController controller = new MarkersController(methodChannel); final GoogleMap googleMap = mock(GoogleMap.class); controller.setGoogleMap(googleMap); final Marker marker = mock(Marker.class); final String googleMarkerId = "abc123"; when(marker.getId()).thenReturn(googleMarkerId); when(googleMap.addMarker(any(MarkerOptions.class))).thenReturn(marker); final LatLng latLng = new LatLng(1.1, 2.2); final Map<String, String> markerOptions = new HashMap<>(); markerOptions.put("markerId", googleMarkerId); final List<Object> markers = Arrays.<Object>asList(markerOptions); controller.addMarkers(markers); controller.onMarkerDragEnd(googleMarkerId, latLng); final List<Double> points = new ArrayList<>(); points.add(latLng.latitude); points.add(latLng.longitude); final Map<String, Object> data = new HashMap<>(); data.put("markerId", googleMarkerId); data.put("position", points); Mockito.verify(methodChannel).invokeMethod("marker#onDragEnd", data); } @Test public void controller_OnMarkerDrag() { final MethodChannel methodChannel = spy(new MethodChannel(mock(BinaryMessenger.class), "no-name", mock(MethodCodec.class))); final MarkersController controller = new MarkersController(methodChannel); final GoogleMap googleMap = mock(GoogleMap.class); controller.setGoogleMap(googleMap); final Marker marker = mock(Marker.class); final String googleMarkerId = "abc123"; when(marker.getId()).thenReturn(googleMarkerId); when(googleMap.addMarker(any(MarkerOptions.class))).thenReturn(marker); final LatLng latLng = new LatLng(1.1, 2.2); final Map<String, String> markerOptions = new HashMap<>(); markerOptions.put("markerId", googleMarkerId); final List<Object> markers = Arrays.<Object>asList(markerOptions); controller.addMarkers(markers); controller.onMarkerDrag(googleMarkerId, latLng); final List<Double> points = new ArrayList<>(); points.add(latLng.latitude); points.add(latLng.longitude); final Map<String, Object> data = new HashMap<>(); data.put("markerId", googleMarkerId); data.put("position", points); Mockito.verify(methodChannel).invokeMethod("marker#onDrag", data); } }
packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/test/java/io/flutter/plugins/googlemaps/MarkersControllerTest.java/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/test/java/io/flutter/plugins/googlemaps/MarkersControllerTest.java", "repo_id": "packages", "token_count": 1616 }
1,013
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="io.flutter.plugins.googlemapsexample"> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <application android:label="google_maps_flutter_example" android:icon="@mipmap/ic_launcher"> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> <!-- Update this value to your google maps api key. --> <meta-data android:name="com.google.android.geo.API_KEY" android:value="${mapsApiKey}" /> <activity android:name="io.flutter.embedding.android.FlutterActivity" android:theme="@style/LaunchTheme" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale" android:hardwareAccelerated="true" android:windowSoftInputMode="adjustResize"> <meta-data android:name="io.flutter.app.android.SplashScreenUntilFirstFrame" android:value="true" /> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> <meta-data android:name="flutterEmbedding" android:value="2"/> </application> </manifest>
packages/packages/google_maps_flutter/google_maps_flutter_android/example/android/app/src/main/AndroidManifest.xml/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/example/android/app/src/main/AndroidManifest.xml", "repo_id": "packages", "token_count": 632 }
1,014
// Copyright 2013 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. // ignore_for_file: public_member_api_docs import 'package:flutter/material.dart'; import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart'; import 'example_google_map.dart'; import 'page.dart'; class PlaceCirclePage extends GoogleMapExampleAppPage { const PlaceCirclePage({Key? key}) : super(const Icon(Icons.linear_scale), 'Place circle', key: key); @override Widget build(BuildContext context) { return const PlaceCircleBody(); } } class PlaceCircleBody extends StatefulWidget { const PlaceCircleBody({super.key}); @override State<StatefulWidget> createState() => PlaceCircleBodyState(); } class PlaceCircleBodyState extends State<PlaceCircleBody> { PlaceCircleBodyState(); ExampleGoogleMapController? controller; Map<CircleId, Circle> circles = <CircleId, Circle>{}; int _circleIdCounter = 1; CircleId? selectedCircle; // Values when toggling circle color int fillColorsIndex = 0; int strokeColorsIndex = 0; List<Color> colors = <Color>[ Colors.purple, Colors.red, Colors.green, Colors.pink, ]; // Values when toggling circle stroke width int widthsIndex = 0; List<int> widths = <int>[10, 20, 5]; // ignore: use_setters_to_change_properties void _onMapCreated(ExampleGoogleMapController controller) { this.controller = controller; } @override void dispose() { super.dispose(); } void _onCircleTapped(CircleId circleId) { setState(() { selectedCircle = circleId; }); } void _remove(CircleId circleId) { setState(() { if (circles.containsKey(circleId)) { circles.remove(circleId); } if (circleId == selectedCircle) { selectedCircle = null; } }); } void _add() { final int circleCount = circles.length; if (circleCount == 12) { return; } final String circleIdVal = 'circle_id_$_circleIdCounter'; _circleIdCounter++; final CircleId circleId = CircleId(circleIdVal); final Circle circle = Circle( circleId: circleId, consumeTapEvents: true, strokeColor: Colors.orange, fillColor: Colors.green, strokeWidth: 5, center: _createCenter(), radius: 50000, onTap: () { _onCircleTapped(circleId); }, ); setState(() { circles[circleId] = circle; }); } void _toggleVisible(CircleId circleId) { final Circle circle = circles[circleId]!; setState(() { circles[circleId] = circle.copyWith( visibleParam: !circle.visible, ); }); } void _changeFillColor(CircleId circleId) { final Circle circle = circles[circleId]!; setState(() { circles[circleId] = circle.copyWith( fillColorParam: colors[++fillColorsIndex % colors.length], ); }); } void _changeStrokeColor(CircleId circleId) { final Circle circle = circles[circleId]!; setState(() { circles[circleId] = circle.copyWith( strokeColorParam: colors[++strokeColorsIndex % colors.length], ); }); } void _changeStrokeWidth(CircleId circleId) { final Circle circle = circles[circleId]!; setState(() { circles[circleId] = circle.copyWith( strokeWidthParam: widths[++widthsIndex % widths.length], ); }); } @override Widget build(BuildContext context) { final CircleId? selectedId = selectedCircle; return Column( mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ Center( child: SizedBox( width: 350.0, height: 300.0, child: ExampleGoogleMap( initialCameraPosition: const CameraPosition( target: LatLng(52.4478, -3.5402), zoom: 7.0, ), circles: Set<Circle>.of(circles.values), onMapCreated: _onMapCreated, ), ), ), Expanded( child: SingleChildScrollView( child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: <Widget>[ Row( children: <Widget>[ Column( children: <Widget>[ TextButton( onPressed: _add, child: const Text('add'), ), TextButton( onPressed: (selectedId == null) ? null : () => _remove(selectedId), child: const Text('remove'), ), TextButton( onPressed: (selectedId == null) ? null : () => _toggleVisible(selectedId), child: const Text('toggle visible'), ), ], ), Column( children: <Widget>[ TextButton( onPressed: (selectedId == null) ? null : () => _changeStrokeWidth(selectedId), child: const Text('change stroke width'), ), TextButton( onPressed: (selectedId == null) ? null : () => _changeStrokeColor(selectedId), child: const Text('change stroke color'), ), TextButton( onPressed: (selectedId == null) ? null : () => _changeFillColor(selectedId), child: const Text('change fill color'), ), ], ) ], ) ], ), ), ), ], ); } LatLng _createCenter() { final double offset = _circleIdCounter.ceilToDouble(); return _createLatLng(51.4816 + offset * 0.2, -3.1791); } LatLng _createLatLng(double lat, double lng) { return LatLng(lat, lng); } }
packages/packages/google_maps_flutter/google_maps_flutter_android/example/lib/place_circle.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/example/lib/place_circle.dart", "repo_id": "packages", "token_count": 3265 }
1,015
// Copyright 2013 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 "GoogleMapPolygonController.h" #import "FLTGoogleMapJSONConversions.h" @interface FLTGoogleMapPolygonController () @property(strong, nonatomic) GMSPolygon *polygon; @property(weak, nonatomic) GMSMapView *mapView; @end @implementation FLTGoogleMapPolygonController - (instancetype)initPolygonWithPath:(GMSMutablePath *)path identifier:(NSString *)identifier mapView:(GMSMapView *)mapView { self = [super init]; if (self) { _polygon = [GMSPolygon polygonWithPath:path]; _mapView = mapView; _polygon.userData = @[ identifier ]; } return self; } - (void)removePolygon { self.polygon.map = nil; } - (void)setConsumeTapEvents:(BOOL)consumes { self.polygon.tappable = consumes; } - (void)setVisible:(BOOL)visible { self.polygon.map = visible ? self.mapView : nil; } - (void)setZIndex:(int)zIndex { self.polygon.zIndex = zIndex; } - (void)setPoints:(NSArray<CLLocation *> *)points { GMSMutablePath *path = [GMSMutablePath path]; for (CLLocation *location in points) { [path addCoordinate:location.coordinate]; } self.polygon.path = path; } - (void)setHoles:(NSArray<NSArray<CLLocation *> *> *)rawHoles { NSMutableArray<GMSMutablePath *> *holes = [[NSMutableArray<GMSMutablePath *> alloc] init]; for (NSArray<CLLocation *> *points in rawHoles) { GMSMutablePath *path = [GMSMutablePath path]; for (CLLocation *location in points) { [path addCoordinate:location.coordinate]; } [holes addObject:path]; } self.polygon.holes = holes; } - (void)setFillColor:(UIColor *)color { self.polygon.fillColor = color; } - (void)setStrokeColor:(UIColor *)color { self.polygon.strokeColor = color; } - (void)setStrokeWidth:(CGFloat)width { self.polygon.strokeWidth = width; } - (void)interpretPolygonOptions:(NSDictionary *)data registrar:(NSObject<FlutterPluginRegistrar> *)registrar { NSNumber *consumeTapEvents = data[@"consumeTapEvents"]; if (consumeTapEvents && consumeTapEvents != (id)[NSNull null]) { [self setConsumeTapEvents:[consumeTapEvents boolValue]]; } NSNumber *visible = data[@"visible"]; if (visible && visible != (id)[NSNull null]) { [self setVisible:[visible boolValue]]; } NSNumber *zIndex = data[@"zIndex"]; if (zIndex && zIndex != (id)[NSNull null]) { [self setZIndex:[zIndex intValue]]; } NSArray *points = data[@"points"]; if (points && points != (id)[NSNull null]) { [self setPoints:[FLTGoogleMapJSONConversions pointsFromLatLongs:points]]; } NSArray *holes = data[@"holes"]; if (holes && holes != (id)[NSNull null]) { [self setHoles:[FLTGoogleMapJSONConversions holesFromPointsArray:holes]]; } NSNumber *fillColor = data[@"fillColor"]; if (fillColor && fillColor != (id)[NSNull null]) { [self setFillColor:[FLTGoogleMapJSONConversions colorFromRGBA:fillColor]]; } NSNumber *strokeColor = data[@"strokeColor"]; if (strokeColor && strokeColor != (id)[NSNull null]) { [self setStrokeColor:[FLTGoogleMapJSONConversions colorFromRGBA:strokeColor]]; } NSNumber *strokeWidth = data[@"strokeWidth"]; if (strokeWidth && strokeWidth != (id)[NSNull null]) { [self setStrokeWidth:[strokeWidth intValue]]; } } @end @interface FLTPolygonsController () @property(strong, nonatomic) NSMutableDictionary *polygonIdentifierToController; @property(strong, nonatomic) FlutterMethodChannel *methodChannel; @property(weak, nonatomic) NSObject<FlutterPluginRegistrar> *registrar; @property(weak, nonatomic) GMSMapView *mapView; @end @implementation FLTPolygonsController - (instancetype)init:(FlutterMethodChannel *)methodChannel mapView:(GMSMapView *)mapView registrar:(NSObject<FlutterPluginRegistrar> *)registrar { self = [super init]; if (self) { _methodChannel = methodChannel; _mapView = mapView; _polygonIdentifierToController = [NSMutableDictionary dictionaryWithCapacity:1]; _registrar = registrar; } return self; } - (void)addPolygons:(NSArray *)polygonsToAdd { for (NSDictionary *polygon in polygonsToAdd) { GMSMutablePath *path = [FLTPolygonsController getPath:polygon]; NSString *identifier = polygon[@"polygonId"]; FLTGoogleMapPolygonController *controller = [[FLTGoogleMapPolygonController alloc] initPolygonWithPath:path identifier:identifier mapView:self.mapView]; [controller interpretPolygonOptions:polygon registrar:self.registrar]; self.polygonIdentifierToController[identifier] = controller; } } - (void)changePolygons:(NSArray *)polygonsToChange { for (NSDictionary *polygon in polygonsToChange) { NSString *identifier = polygon[@"polygonId"]; FLTGoogleMapPolygonController *controller = self.polygonIdentifierToController[identifier]; if (!controller) { continue; } [controller interpretPolygonOptions:polygon registrar:self.registrar]; } } - (void)removePolygonWithIdentifiers:(NSArray *)identifiers { for (NSString *identifier in identifiers) { FLTGoogleMapPolygonController *controller = self.polygonIdentifierToController[identifier]; if (!controller) { continue; } [controller removePolygon]; [self.polygonIdentifierToController removeObjectForKey:identifier]; } } - (void)didTapPolygonWithIdentifier:(NSString *)identifier { if (!identifier) { return; } FLTGoogleMapPolygonController *controller = self.polygonIdentifierToController[identifier]; if (!controller) { return; } [self.methodChannel invokeMethod:@"polygon#onTap" arguments:@{@"polygonId" : identifier}]; } - (bool)hasPolygonWithIdentifier:(NSString *)identifier { if (!identifier) { return false; } return self.polygonIdentifierToController[identifier] != nil; } + (GMSMutablePath *)getPath:(NSDictionary *)polygon { NSArray *pointArray = polygon[@"points"]; NSArray<CLLocation *> *points = [FLTGoogleMapJSONConversions pointsFromLatLongs:pointArray]; GMSMutablePath *path = [GMSMutablePath path]; for (CLLocation *location in points) { [path addCoordinate:location.coordinate]; } return path; } @end
packages/packages/google_maps_flutter/google_maps_flutter_ios/ios/Classes/GoogleMapPolygonController.m/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_ios/ios/Classes/GoogleMapPolygonController.m", "repo_id": "packages", "token_count": 2376 }
1,016
// Copyright 2013 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:flutter/widgets.dart'; import '../../google_maps_flutter_platform_interface.dart'; /// Configuration options for the GoogleMaps user interface. @immutable class MapConfiguration { /// Creates a new configuration instance with the given options. /// /// Any options that aren't passed will be null, which allows this to serve /// as either a full configuration selection, or an update to an existing /// configuration where only non-null values are updated. const MapConfiguration({ this.webGestureHandling, this.compassEnabled, this.mapToolbarEnabled, this.cameraTargetBounds, this.mapType, this.minMaxZoomPreference, this.rotateGesturesEnabled, this.scrollGesturesEnabled, this.tiltGesturesEnabled, this.fortyFiveDegreeImageryEnabled, this.trackCameraPosition, this.zoomControlsEnabled, this.zoomGesturesEnabled, this.liteModeEnabled, this.myLocationEnabled, this.myLocationButtonEnabled, this.padding, this.indoorViewEnabled, this.trafficEnabled, this.buildingsEnabled, this.cloudMapId, this.style, }); /// This setting controls how the API handles gestures on the map. Web only. /// /// See [WebGestureHandling] for more details. final WebGestureHandling? webGestureHandling; /// True if the compass UI should be shown. final bool? compassEnabled; /// True if the map toolbar should be shown. final bool? mapToolbarEnabled; /// The bounds to display. final CameraTargetBounds? cameraTargetBounds; /// The type of the map. final MapType? mapType; /// The preferred zoom range. final MinMaxZoomPreference? minMaxZoomPreference; /// True if rotate gestures should be enabled. final bool? rotateGesturesEnabled; /// True if scroll gestures should be enabled. /// /// Android/iOS only. For web, see [webGestureHandling]. final bool? scrollGesturesEnabled; /// True if tilt gestures should be enabled. final bool? tiltGesturesEnabled; /// True if 45 degree imagery should be enabled. /// /// Web only. final bool? fortyFiveDegreeImageryEnabled; /// True if camera position changes should trigger notifications. final bool? trackCameraPosition; /// True if zoom controls should be displayed. final bool? zoomControlsEnabled; /// True if zoom gestures should be enabled. /// /// Android/iOS only. For web, see [webGestureHandling]. final bool? zoomGesturesEnabled; /// True if the map should use Lite Mode, showing a limited-interactivity /// bitmap, on supported platforms. final bool? liteModeEnabled; /// True if the current location should be tracked and displayed. final bool? myLocationEnabled; /// True if the control to jump to the current location should be displayed. final bool? myLocationButtonEnabled; /// The padding for the map display. final EdgeInsets? padding; /// True if indoor map views should be enabled. final bool? indoorViewEnabled; /// True if the traffic overlay should be enabled. final bool? trafficEnabled; /// True if 3D building display should be enabled. final bool? buildingsEnabled; /// Identifier that's associated with a specific cloud-based map style. /// /// See https://developers.google.com/maps/documentation/get-map-id /// for more details. final String? cloudMapId; /// Locally configured JSON style. /// /// To clear a previously set style, set this to an empty string. final String? style; /// Returns a new options object containing only the values of this instance /// that are different from [other]. MapConfiguration diffFrom(MapConfiguration other) { return MapConfiguration( webGestureHandling: webGestureHandling != other.webGestureHandling ? webGestureHandling : null, compassEnabled: compassEnabled != other.compassEnabled ? compassEnabled : null, mapToolbarEnabled: mapToolbarEnabled != other.mapToolbarEnabled ? mapToolbarEnabled : null, cameraTargetBounds: cameraTargetBounds != other.cameraTargetBounds ? cameraTargetBounds : null, mapType: mapType != other.mapType ? mapType : null, minMaxZoomPreference: minMaxZoomPreference != other.minMaxZoomPreference ? minMaxZoomPreference : null, rotateGesturesEnabled: rotateGesturesEnabled != other.rotateGesturesEnabled ? rotateGesturesEnabled : null, scrollGesturesEnabled: scrollGesturesEnabled != other.scrollGesturesEnabled ? scrollGesturesEnabled : null, tiltGesturesEnabled: tiltGesturesEnabled != other.tiltGesturesEnabled ? tiltGesturesEnabled : null, fortyFiveDegreeImageryEnabled: fortyFiveDegreeImageryEnabled != other.fortyFiveDegreeImageryEnabled ? fortyFiveDegreeImageryEnabled : null, trackCameraPosition: trackCameraPosition != other.trackCameraPosition ? trackCameraPosition : null, zoomControlsEnabled: zoomControlsEnabled != other.zoomControlsEnabled ? zoomControlsEnabled : null, zoomGesturesEnabled: zoomGesturesEnabled != other.zoomGesturesEnabled ? zoomGesturesEnabled : null, liteModeEnabled: liteModeEnabled != other.liteModeEnabled ? liteModeEnabled : null, myLocationEnabled: myLocationEnabled != other.myLocationEnabled ? myLocationEnabled : null, myLocationButtonEnabled: myLocationButtonEnabled != other.myLocationButtonEnabled ? myLocationButtonEnabled : null, padding: padding != other.padding ? padding : null, indoorViewEnabled: indoorViewEnabled != other.indoorViewEnabled ? indoorViewEnabled : null, trafficEnabled: trafficEnabled != other.trafficEnabled ? trafficEnabled : null, buildingsEnabled: buildingsEnabled != other.buildingsEnabled ? buildingsEnabled : null, cloudMapId: cloudMapId != other.cloudMapId ? cloudMapId : null, style: style != other.style ? style : null, ); } /// Returns a copy of this instance with any non-null settings form [diff] /// replacing the previous values. MapConfiguration applyDiff(MapConfiguration diff) { return MapConfiguration( webGestureHandling: diff.webGestureHandling ?? webGestureHandling, compassEnabled: diff.compassEnabled ?? compassEnabled, mapToolbarEnabled: diff.mapToolbarEnabled ?? mapToolbarEnabled, cameraTargetBounds: diff.cameraTargetBounds ?? cameraTargetBounds, mapType: diff.mapType ?? mapType, minMaxZoomPreference: diff.minMaxZoomPreference ?? minMaxZoomPreference, rotateGesturesEnabled: diff.rotateGesturesEnabled ?? rotateGesturesEnabled, scrollGesturesEnabled: diff.scrollGesturesEnabled ?? scrollGesturesEnabled, tiltGesturesEnabled: diff.tiltGesturesEnabled ?? tiltGesturesEnabled, fortyFiveDegreeImageryEnabled: diff.fortyFiveDegreeImageryEnabled ?? fortyFiveDegreeImageryEnabled, trackCameraPosition: diff.trackCameraPosition ?? trackCameraPosition, zoomControlsEnabled: diff.zoomControlsEnabled ?? zoomControlsEnabled, zoomGesturesEnabled: diff.zoomGesturesEnabled ?? zoomGesturesEnabled, liteModeEnabled: diff.liteModeEnabled ?? liteModeEnabled, myLocationEnabled: diff.myLocationEnabled ?? myLocationEnabled, myLocationButtonEnabled: diff.myLocationButtonEnabled ?? myLocationButtonEnabled, padding: diff.padding ?? padding, indoorViewEnabled: diff.indoorViewEnabled ?? indoorViewEnabled, trafficEnabled: diff.trafficEnabled ?? trafficEnabled, buildingsEnabled: diff.buildingsEnabled ?? buildingsEnabled, cloudMapId: diff.cloudMapId ?? cloudMapId, style: diff.style ?? style, ); } /// True if no options are set. bool get isEmpty => webGestureHandling == null && compassEnabled == null && mapToolbarEnabled == null && cameraTargetBounds == null && mapType == null && minMaxZoomPreference == null && rotateGesturesEnabled == null && scrollGesturesEnabled == null && tiltGesturesEnabled == null && fortyFiveDegreeImageryEnabled == null && trackCameraPosition == null && zoomControlsEnabled == null && zoomGesturesEnabled == null && liteModeEnabled == null && myLocationEnabled == null && myLocationButtonEnabled == null && padding == null && indoorViewEnabled == null && trafficEnabled == null && buildingsEnabled == null && cloudMapId == null && style == null; @override bool operator ==(Object other) { if (identical(this, other)) { return true; } if (other.runtimeType != runtimeType) { return false; } return other is MapConfiguration && webGestureHandling == other.webGestureHandling && compassEnabled == other.compassEnabled && mapToolbarEnabled == other.mapToolbarEnabled && cameraTargetBounds == other.cameraTargetBounds && mapType == other.mapType && minMaxZoomPreference == other.minMaxZoomPreference && rotateGesturesEnabled == other.rotateGesturesEnabled && scrollGesturesEnabled == other.scrollGesturesEnabled && tiltGesturesEnabled == other.tiltGesturesEnabled && fortyFiveDegreeImageryEnabled == other.fortyFiveDegreeImageryEnabled && trackCameraPosition == other.trackCameraPosition && zoomControlsEnabled == other.zoomControlsEnabled && zoomGesturesEnabled == other.zoomGesturesEnabled && liteModeEnabled == other.liteModeEnabled && myLocationEnabled == other.myLocationEnabled && myLocationButtonEnabled == other.myLocationButtonEnabled && padding == other.padding && indoorViewEnabled == other.indoorViewEnabled && trafficEnabled == other.trafficEnabled && buildingsEnabled == other.buildingsEnabled && cloudMapId == other.cloudMapId && style == other.style; } @override int get hashCode => Object.hashAll(<Object?>[ webGestureHandling, compassEnabled, mapToolbarEnabled, cameraTargetBounds, mapType, minMaxZoomPreference, rotateGesturesEnabled, scrollGesturesEnabled, tiltGesturesEnabled, fortyFiveDegreeImageryEnabled, trackCameraPosition, zoomControlsEnabled, zoomGesturesEnabled, liteModeEnabled, myLocationEnabled, myLocationButtonEnabled, padding, indoorViewEnabled, trafficEnabled, buildingsEnabled, cloudMapId, style, ]); }
packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/map_configuration.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/map_configuration.dart", "repo_id": "packages", "token_count": 3871 }
1,017
// Copyright 2013 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 'types.dart'; /// An interface for a class that provides the tile images for a TileOverlay. abstract class TileProvider { /// Stub tile that is used to indicate that no tile exists for a specific tile coordinate. static const Tile noTile = Tile(-1, -1, null); /// Returns the tile to be used for this tile coordinate. /// /// See [TileOverlay] for the specification of tile coordinates. Future<Tile> getTile(int x, int y, int? zoom); }
packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/tile_provider.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/tile_provider.dart", "repo_id": "packages", "token_count": 167 }
1,018
// Copyright 2013 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:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('$BitmapDescriptor', () { test('toJson / fromJson', () { final BitmapDescriptor descriptor = BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueCyan); final Object json = descriptor.toJson(); // Rehydrate a new bitmap descriptor... final BitmapDescriptor descriptorFromJson = BitmapDescriptor.fromJson(json); expect(descriptorFromJson, isNot(descriptor)); // New instance expect(identical(descriptorFromJson.toJson(), json), isTrue); // Same JSON }); group('fromBytes constructor', () { test('with empty byte array, throws assertion error', () { expect(() { BitmapDescriptor.fromBytes(Uint8List.fromList(<int>[])); }, throwsAssertionError); }); test('with bytes', () { final BitmapDescriptor descriptor = BitmapDescriptor.fromBytes( Uint8List.fromList(<int>[1, 2, 3]), ); expect(descriptor, isA<BitmapDescriptor>()); expect( descriptor.toJson(), equals(<Object>[ 'fromBytes', <int>[1, 2, 3], ])); }); test('with size, not on the web, size is ignored', () { final BitmapDescriptor descriptor = BitmapDescriptor.fromBytes( Uint8List.fromList(<int>[1, 2, 3]), size: const Size(40, 20), ); expect( descriptor.toJson(), equals(<Object>[ 'fromBytes', <int>[1, 2, 3], ])); }, skip: kIsWeb); test('with size, on the web, size is preserved', () { final BitmapDescriptor descriptor = BitmapDescriptor.fromBytes( Uint8List.fromList(<int>[1, 2, 3]), size: const Size(40, 20), ); expect( descriptor.toJson(), equals(<Object>[ 'fromBytes', <int>[1, 2, 3], <int>[40, 20], ])); }, skip: !kIsWeb); }); group('fromJson validation', () { group('type validation', () { test('correct type', () { expect(BitmapDescriptor.fromJson(<dynamic>['defaultMarker']), isA<BitmapDescriptor>()); }); test('wrong type', () { expect(() { BitmapDescriptor.fromJson(<dynamic>['bogusType']); }, throwsAssertionError); }); }); group('defaultMarker', () { test('hue is null', () { expect(BitmapDescriptor.fromJson(<dynamic>['defaultMarker']), isA<BitmapDescriptor>()); }); test('hue is number', () { expect(BitmapDescriptor.fromJson(<dynamic>['defaultMarker', 158]), isA<BitmapDescriptor>()); }); test('hue is not number', () { expect(() { BitmapDescriptor.fromJson(<dynamic>['defaultMarker', 'nope']); }, throwsAssertionError); }); test('hue is out of range', () { expect(() { BitmapDescriptor.fromJson(<dynamic>['defaultMarker', -1]); }, throwsAssertionError); expect(() { BitmapDescriptor.fromJson(<dynamic>['defaultMarker', 361]); }, throwsAssertionError); }); }); group('fromBytes', () { test('with bytes', () { expect( BitmapDescriptor.fromJson(<dynamic>[ 'fromBytes', Uint8List.fromList(<int>[1, 2, 3]) ]), isA<BitmapDescriptor>()); }); test('without bytes', () { expect(() { BitmapDescriptor.fromJson(<dynamic>['fromBytes', null]); }, throwsAssertionError); expect(() { BitmapDescriptor.fromJson(<dynamic>['fromBytes', <dynamic>[]]); }, throwsAssertionError); }); }); group('fromAsset', () { test('name is passed', () { expect( BitmapDescriptor.fromJson( <dynamic>['fromAsset', 'some/path.png']), isA<BitmapDescriptor>()); }); test('name cannot be null or empty', () { expect(() { BitmapDescriptor.fromJson(<dynamic>['fromAsset', null]); }, throwsAssertionError); expect(() { BitmapDescriptor.fromJson(<dynamic>['fromAsset', '']); }, throwsAssertionError); }); test('package is passed', () { expect( BitmapDescriptor.fromJson( <dynamic>['fromAsset', 'some/path.png', 'some_package']), isA<BitmapDescriptor>()); }); test('package cannot be null or empty', () { expect(() { BitmapDescriptor.fromJson( <dynamic>['fromAsset', 'some/path.png', null]); }, throwsAssertionError); expect(() { BitmapDescriptor.fromJson( <dynamic>['fromAsset', 'some/path.png', '']); }, throwsAssertionError); }); }); group('fromAssetImage', () { test('name and dpi passed', () { expect( BitmapDescriptor.fromJson( <dynamic>['fromAssetImage', 'some/path.png', 1.0]), isA<BitmapDescriptor>()); }); test('mipmaps determines dpi', () async { const ImageConfiguration imageConfiguration = ImageConfiguration( devicePixelRatio: 3, ); final BitmapDescriptor mip = await BitmapDescriptor.fromAssetImage( imageConfiguration, 'red_square.png', ); final BitmapDescriptor scaled = await BitmapDescriptor.fromAssetImage( imageConfiguration, 'red_square.png', mipmaps: false, ); expect((mip.toJson() as List<dynamic>)[2], 1); expect((scaled.toJson() as List<dynamic>)[2], 3); }, // TODO(stuartmorgan): Investigate timeout on web. skip: kIsWeb); test('name cannot be null or empty', () { expect(() { BitmapDescriptor.fromJson(<dynamic>['fromAssetImage', null, 1.0]); }, throwsAssertionError); expect(() { BitmapDescriptor.fromJson(<dynamic>['fromAssetImage', '', 1.0]); }, throwsAssertionError); }); test('dpi must be number', () { expect(() { BitmapDescriptor.fromJson( <dynamic>['fromAssetImage', 'some/path.png', null]); }, throwsAssertionError); expect(() { BitmapDescriptor.fromJson( <dynamic>['fromAssetImage', 'some/path.png', 'one']); }, throwsAssertionError); }); test('with optional [width, height] List', () { expect( BitmapDescriptor.fromJson(<dynamic>[ 'fromAssetImage', 'some/path.png', 1.0, <dynamic>[640, 480] ]), isA<BitmapDescriptor>()); }); test( 'optional [width, height] List cannot be null or not contain 2 elements', () { expect(() { BitmapDescriptor.fromJson( <dynamic>['fromAssetImage', 'some/path.png', 1.0, null]); }, throwsAssertionError); expect(() { BitmapDescriptor.fromJson( <dynamic>['fromAssetImage', 'some/path.png', 1.0, <dynamic>[]]); }, throwsAssertionError); expect(() { BitmapDescriptor.fromJson(<dynamic>[ 'fromAssetImage', 'some/path.png', 1.0, <dynamic>[640, 480, 1024] ]); }, throwsAssertionError); }); }); }); }); }
packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/bitmap_test.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/bitmap_test.dart", "repo_id": "packages", "token_count": 4161 }
1,019
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:flutter/foundation.dart' show visibleForTesting; import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart'; import 'src/messages.g.dart'; /// Android implementation of [GoogleSignInPlatform]. class GoogleSignInAndroid extends GoogleSignInPlatform { /// Creates a new plugin implementation instance. GoogleSignInAndroid({ @visibleForTesting GoogleSignInApi? api, }) : _api = api ?? GoogleSignInApi(); final GoogleSignInApi _api; /// Registers this class as the default instance of [GoogleSignInPlatform]. static void registerWith() { GoogleSignInPlatform.instance = GoogleSignInAndroid(); } @override Future<void> init({ List<String> scopes = const <String>[], SignInOption signInOption = SignInOption.standard, String? hostedDomain, String? clientId, }) { return initWithParams(SignInInitParameters( signInOption: signInOption, scopes: scopes, hostedDomain: hostedDomain, clientId: clientId, )); } @override Future<void> initWithParams(SignInInitParameters params) { return _api.init(InitParams( signInType: _signInTypeForOption(params.signInOption), scopes: params.scopes, hostedDomain: params.hostedDomain, clientId: params.clientId, serverClientId: params.serverClientId, forceCodeForRefreshToken: params.forceCodeForRefreshToken, )); } @override Future<GoogleSignInUserData?> signInSilently() { return _api.signInSilently().then(_signInUserDataFromChannelData); } @override Future<GoogleSignInUserData?> signIn() { return _api.signIn().then(_signInUserDataFromChannelData); } @override Future<GoogleSignInTokenData> getTokens( {required String email, bool? shouldRecoverAuth = true}) { return _api .getAccessToken(email, shouldRecoverAuth ?? true) .then((String result) => GoogleSignInTokenData( accessToken: result, )); } @override Future<void> signOut() { return _api.signOut(); } @override Future<void> disconnect() { return _api.disconnect(); } @override Future<bool> isSignedIn() { return _api.isSignedIn(); } @override Future<void> clearAuthCache({required String token}) { return _api.clearAuthCache(token); } @override Future<bool> requestScopes(List<String> scopes) { return _api.requestScopes(scopes); } SignInType _signInTypeForOption(SignInOption option) { switch (option) { case SignInOption.standard: return SignInType.standard; case SignInOption.games: return SignInType.games; } // Handle the case where a new type is added to the platform interface in // the future, and this version of the package is used with it. // ignore: dead_code throw UnimplementedError('Unsupported sign in option: $option'); } GoogleSignInUserData _signInUserDataFromChannelData(UserData data) { return GoogleSignInUserData( email: data.email, id: data.id, displayName: data.displayName, photoUrl: data.photoUrl, idToken: data.idToken, serverAuthCode: data.serverAuthCode, ); } }
packages/packages/google_sign_in/google_sign_in_android/lib/google_sign_in_android.dart/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_android/lib/google_sign_in_android.dart", "repo_id": "packages", "token_count": 1198 }
1,020
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
packages/packages/google_sign_in/google_sign_in_ios/example/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_ios/example/macos/Runner/Configs/Debug.xcconfig", "repo_id": "packages", "token_count": 32 }
1,021
targets: $default: sources: - integration_test/*.dart - lib/$lib$ - $package$ builders: mockito|mockBuilder: generate_for: - integration_test/**
packages/packages/google_sign_in/google_sign_in_web/example/build.yaml/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_web/example/build.yaml", "repo_id": "packages", "token_count": 97 }
1,022
// Copyright 2013 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. package io.flutter.plugins.imagepicker; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.times; import static org.mockito.Mockito.when; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import androidx.core.util.SizeFCompat; import java.io.File; import java.io.IOException; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.MockedStatic; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.robolectric.RobolectricTestRunner; // RobolectricTestRunner always creates a default mock bitmap when reading from file. So we cannot actually test the scaling. // But we can still test whether the original or scaled file is created. @RunWith(RobolectricTestRunner.class) public class ImageResizerTest { ImageResizer resizer; Context mockContext; File imageFile; File svgImageFile; File tallJPG; File wideJPG; File externalDirectory; Bitmap originalImageBitmap; AutoCloseable mockCloseable; @Before public void setUp() throws IOException { mockCloseable = MockitoAnnotations.openMocks(this); imageFile = new File(getClass().getClassLoader().getResource("pngImage.png").getFile()); svgImageFile = new File(getClass().getClassLoader().getResource("flutter_image.svg").getFile()); // tallJPG has height 7px and width 4px. tallJPG = new File(getClass().getClassLoader().getResource("jpgImageTall.jpg").getFile()); // wideJPG has height 7px and width 12px. wideJPG = new File(getClass().getClassLoader().getResource("jpgImageWide.jpg").getFile()); originalImageBitmap = BitmapFactory.decodeFile(imageFile.getPath()); TemporaryFolder temporaryFolder = new TemporaryFolder(); temporaryFolder.create(); externalDirectory = temporaryFolder.newFolder("image_picker_testing_path"); mockContext = mock(Context.class); when(mockContext.getCacheDir()).thenReturn(externalDirectory); resizer = new ImageResizer(mockContext, new ExifDataCopier()); } @After public void tearDown() throws Exception { mockCloseable.close(); } @Test public void onResizeImageIfNeeded_whenQualityIsMax_shouldNotResize_returnTheUnscaledFile() { String outputFile = resizer.resizeImageIfNeeded(imageFile.getPath(), null, null, 100); assertThat(outputFile, equalTo(imageFile.getPath())); } @Test public void onResizeImageIfNeeded_whenQualityIsNotMax_shouldResize_returnResizedFile() { String outputFile = resizer.resizeImageIfNeeded(imageFile.getPath(), null, null, 50); assertThat(outputFile, equalTo(externalDirectory.getPath() + "/scaled_pngImage.png")); } @Test public void onResizeImageIfNeeded_whenWidthIsNotNull_shouldResize_returnResizedFile() { String outputFile = resizer.resizeImageIfNeeded(imageFile.getPath(), 50.0, null, 100); assertThat(outputFile, equalTo(externalDirectory.getPath() + "/scaled_pngImage.png")); } @Test public void onResizeImageIfNeeded_whenHeightIsNotNull_shouldResize_returnResizedFile() { String outputFile = resizer.resizeImageIfNeeded(imageFile.getPath(), null, 50.0, 100); assertThat(outputFile, equalTo(externalDirectory.getPath() + "/scaled_pngImage.png")); } @Test public void onResizeImageIfNeeded_whenImagePathIsNotBitmap_shouldReturnPathAndNotNull() { String nonBitmapImagePath = svgImageFile.getPath(); // Mock the static method try (MockedStatic<BitmapFactory> mockedBitmapFactory = Mockito.mockStatic(BitmapFactory.class)) { // Configure the method to return null when called with a non-bitmap image mockedBitmapFactory .when(() -> BitmapFactory.decodeFile(nonBitmapImagePath, null)) .thenReturn(null); String resizedImagePath = resizer.resizeImageIfNeeded(nonBitmapImagePath, null, null, 100); assertNotNull(resizedImagePath); assertThat(resizedImagePath, equalTo(nonBitmapImagePath)); } } @Test public void onResizeImageIfNeeded_whenResizeIsNotNecessary_shouldOnlyQueryBitmapDimensions() { try (MockedStatic<BitmapFactory> mockBitmapFactory = mockStatic(BitmapFactory.class, Mockito.CALLS_REAL_METHODS)) { String outputFile = resizer.resizeImageIfNeeded(imageFile.getPath(), null, null, 100); ArgumentCaptor<BitmapFactory.Options> argument = ArgumentCaptor.forClass(BitmapFactory.Options.class); mockBitmapFactory.verify(() -> BitmapFactory.decodeFile(anyString(), argument.capture())); BitmapFactory.Options capturedOptions = argument.getValue(); assertTrue(capturedOptions.inJustDecodeBounds); } } @Test public void onResizeImageIfNeeded_whenResizeIsNecessary_shouldDecodeBitmapPixels() { try (MockedStatic<BitmapFactory> mockBitmapFactory = mockStatic(BitmapFactory.class, Mockito.CALLS_REAL_METHODS)) { String outputFile = resizer.resizeImageIfNeeded(imageFile.getPath(), 50.0, 50.0, 100); ArgumentCaptor<BitmapFactory.Options> argument = ArgumentCaptor.forClass(BitmapFactory.Options.class); mockBitmapFactory.verify( () -> BitmapFactory.decodeFile(anyString(), argument.capture()), times(2)); List<BitmapFactory.Options> capturedOptions = argument.getAllValues(); assertTrue(capturedOptions.get(0).inJustDecodeBounds); assertFalse(capturedOptions.get(1).inJustDecodeBounds); } } @Test public void onResizeImageIfNeeded_whenImageIsVertical_WidthIsGreaterThanOriginal_shouldResizeCorrectly() { String outputFile = resizer.resizeImageIfNeeded(tallJPG.getPath(), 5.0, 5.0, 100); SizeFCompat originalSize = resizer.readFileDimensions(externalDirectory.getPath() + "/scaled_jpgImageTall.jpg"); float width = originalSize.getWidth(); float height = originalSize.getHeight(); assertThat(width, equalTo(3.0F)); assertThat(height, equalTo(5.0F)); } @Test public void onResizeImageIfNeeded_whenImageIsVertical_HeightIsGreaterThanOriginal_shouldResizeCorrectly() { String outputFile = resizer.resizeImageIfNeeded(tallJPG.getPath(), 3.0, 10.0, 100); SizeFCompat originalSize = resizer.readFileDimensions(externalDirectory.getPath() + "/scaled_jpgImageTall.jpg"); float width = originalSize.getWidth(); float height = originalSize.getHeight(); assertThat(width, equalTo(3.0F)); assertThat(height, equalTo(5.0F)); } @Test public void onResizeImageIfNeeded_whenImageIsVertical_HeightAndWidthIsGreaterThanOriginal_shouldNotResize() { String outputFile = resizer.resizeImageIfNeeded(tallJPG.getPath(), 10.0, 10.0, 100); SizeFCompat originalSize = resizer.readFileDimensions(externalDirectory.getPath() + "/scaled_jpgImageTall.jpg"); float width = originalSize.getWidth(); float height = originalSize.getHeight(); assertThat(width, equalTo(4.0F)); assertThat(height, equalTo(7.0F)); } @Test public void onResizeImageIfNeeded_whenImageIsHorizontal_WidthIsGreaterThanOriginal_shouldResizeCorrectly() { String outputFile = resizer.resizeImageIfNeeded(wideJPG.getPath(), 10.0, 20.0, 100); SizeFCompat originalSize = resizer.readFileDimensions(externalDirectory.getPath() + "/scaled_jpgImageWide.jpg"); float width = originalSize.getWidth(); float height = originalSize.getHeight(); assertThat(width, equalTo(10.0F)); assertThat(height, equalTo(6.0F)); } @Test public void onResizeImageIfNeeded_whenImageIsHorizontal_HeightIsGreaterThanOriginal_shouldResizeCorrectly() { String outputFile = resizer.resizeImageIfNeeded(wideJPG.getPath(), 10.0, 10.0, 100); SizeFCompat originalSize = resizer.readFileDimensions(externalDirectory.getPath() + "/scaled_jpgImageWide.jpg"); float width = originalSize.getWidth(); float height = originalSize.getHeight(); assertThat(width, equalTo(10.0F)); assertThat(height, equalTo(6.0F)); } @Test public void onResizeImageIfNeeded_whenImageIsHorizontal_HeightAndWidthIsGreaterThanOriginal_shouldNotResize() { String outputFile = resizer.resizeImageIfNeeded(wideJPG.getPath(), 100.0, 100.0, 100); SizeFCompat originalSize = resizer.readFileDimensions(externalDirectory.getPath() + "/scaled_jpgImageWide.jpg"); float width = originalSize.getWidth(); float height = originalSize.getHeight(); assertThat(width, equalTo(12.0F)); assertThat(height, equalTo(7.0F)); } }
packages/packages/image_picker/image_picker_android/android/src/test/java/io/flutter/plugins/imagepicker/ImageResizerTest.java/0
{ "file_path": "packages/packages/image_picker/image_picker_android/android/src/test/java/io/flutter/plugins/imagepicker/ImageResizerTest.java", "repo_id": "packages", "token_count": 3161 }
1,023
// Copyright 2013 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 "FLTImagePickerImageUtil.h" #import <MobileCoreServices/MobileCoreServices.h> @interface GIFInfo () @property(strong, nonatomic, readwrite) NSArray<UIImage *> *images; @property(assign, nonatomic, readwrite) NSTimeInterval interval; @end @implementation GIFInfo - (instancetype)initWithImages:(NSArray<UIImage *> *)images interval:(NSTimeInterval)interval; { self = [super init]; if (self) { self.images = images; self.interval = interval; } return self; } @end @implementation FLTImagePickerImageUtil : NSObject static UIImage *FLTImagePickerDrawScaledImage(UIImage *imageToScale, double width, double height) { UIGraphicsImageRenderer *imageRenderer = [[UIGraphicsImageRenderer alloc] initWithSize:CGSizeMake(width, height) format:imageToScale.imageRendererFormat]; return [imageRenderer imageWithActions:^(UIGraphicsImageRendererContext *rendererContext) { CGContextRef cgContext = rendererContext.CGContext; // Flip vertically to translate between UIKit and Quartz. CGContextTranslateCTM(cgContext, 0, height); CGContextScaleCTM(cgContext, 1, -1); CGContextDrawImage(cgContext, CGRectMake(0, 0, width, height), imageToScale.CGImage); }]; } + (UIImage *)scaledImage:(UIImage *)image maxWidth:(NSNumber *)maxWidth maxHeight:(NSNumber *)maxHeight isMetadataAvailable:(BOOL)isMetadataAvailable { double originalWidth = image.size.width; double originalHeight = image.size.height; BOOL hasMaxWidth = maxWidth != nil; BOOL hasMaxHeight = maxHeight != nil; if ((originalWidth == maxWidth.doubleValue && originalHeight == maxHeight.doubleValue) || (!hasMaxWidth && !hasMaxHeight)) { // Nothing to scale. return image; } double aspectRatio = originalWidth / originalHeight; double width = hasMaxWidth ? MIN(round([maxWidth doubleValue]), originalWidth) : originalWidth; double height = hasMaxHeight ? MIN(round([maxHeight doubleValue]), originalHeight) : originalHeight; bool shouldDownscaleWidth = hasMaxWidth && [maxWidth doubleValue] < originalWidth; bool shouldDownscaleHeight = hasMaxHeight && [maxHeight doubleValue] < originalHeight; bool shouldDownscale = shouldDownscaleWidth || shouldDownscaleHeight; if (shouldDownscale) { double widthForMaxHeight = height * aspectRatio; double heightForMaxWidth = width / aspectRatio; if (heightForMaxWidth > height) { width = round(widthForMaxHeight); } else { height = round(heightForMaxWidth); } } if (!isMetadataAvailable) { UIImage *imageToScale = [UIImage imageWithCGImage:image.CGImage scale:1 orientation:image.imageOrientation]; return FLTImagePickerDrawScaledImage(imageToScale, width, height); } // Scaling the image always rotate itself based on the current imageOrientation of the original // Image. Set to orientationUp for the orignal image before scaling, so the scaled image doesn't // mess up with the pixels. UIImage *imageToScale = [UIImage imageWithCGImage:image.CGImage scale:1 orientation:UIImageOrientationUp]; // The image orientation is manually set to UIImageOrientationUp which swapped the aspect ratio in // some scenarios. For example, when the original image has orientation left, the horizontal // pixels should be scaled to `width` and the vertical pixels should be scaled to `height`. After // setting the orientation to up, we end up scaling the horizontal pixels to `height` and vertical // to `width`. Below swap will solve this issue. if ([image imageOrientation] == UIImageOrientationLeft || [image imageOrientation] == UIImageOrientationRight || [image imageOrientation] == UIImageOrientationLeftMirrored || [image imageOrientation] == UIImageOrientationRightMirrored) { double temp = width; width = height; height = temp; } return FLTImagePickerDrawScaledImage(imageToScale, width, height); } + (GIFInfo *)scaledGIFImage:(NSData *)data maxWidth:(NSNumber *)maxWidth maxHeight:(NSNumber *)maxHeight { NSMutableDictionary<NSString *, id> *options = [NSMutableDictionary dictionary]; options[(NSString *)kCGImageSourceShouldCache] = @YES; options[(NSString *)kCGImageSourceTypeIdentifierHint] = (NSString *)kUTTypeGIF; CGImageSourceRef imageSource = CGImageSourceCreateWithData((__bridge CFDataRef)data, (__bridge CFDictionaryRef)options); size_t numberOfFrames = CGImageSourceGetCount(imageSource); NSMutableArray<UIImage *> *images = [NSMutableArray arrayWithCapacity:numberOfFrames]; NSTimeInterval interval = 0.0; for (size_t index = 0; index < numberOfFrames; index++) { CGImageRef imageRef = CGImageSourceCreateImageAtIndex(imageSource, index, (__bridge CFDictionaryRef)options); NSDictionary *properties = (NSDictionary *)CFBridgingRelease( CGImageSourceCopyPropertiesAtIndex(imageSource, index, NULL)); NSDictionary *gifProperties = properties[(NSString *)kCGImagePropertyGIFDictionary]; NSNumber *delay = gifProperties[(NSString *)kCGImagePropertyGIFUnclampedDelayTime]; if (delay == nil) { delay = gifProperties[(NSString *)kCGImagePropertyGIFDelayTime]; } if (interval == 0.0) { interval = [delay doubleValue]; } UIImage *image = [UIImage imageWithCGImage:imageRef scale:1.0 orientation:UIImageOrientationUp]; image = [self scaledImage:image maxWidth:maxWidth maxHeight:maxHeight isMetadataAvailable:YES]; [images addObject:image]; CGImageRelease(imageRef); } CFRelease(imageSource); GIFInfo *info = [[GIFInfo alloc] initWithImages:images interval:interval]; return info; } @end
packages/packages/image_picker/image_picker_ios/ios/Classes/FLTImagePickerImageUtil.m/0
{ "file_path": "packages/packages/image_picker/image_picker_ios/ios/Classes/FLTImagePickerImageUtil.m", "repo_id": "packages", "token_count": 2102 }
1,024
## 2.9.4 * Updates minimum supported SDK version to Flutter 3.19/Dart 3.3. * Removes a few deprecated API usages. ## 2.9.3 * Updates minimum required plugin_platform_interface version to 2.1.7. ## 2.9.2 * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. * Fixes new lint warnings. ## 2.9.1 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 2.9.0 * Formally deprecates all methods that have been replaced with newer variants. ## 2.8.0 * Adds `getMedia` method. ## 2.7.0 * Adds `CameraDelegatingImagePickerPlatform` as a base class for platform implementations that don't support `ImageSource.camera`, but allow for an- implementation to be provided at the application level via implementation of `CameraDelegatingImagePickerPlatform`. * Adds `supportsImageSource` to check source support at runtime. ## 2.6.4 * Adds compatibility with `http` 1.0. * Updates minimum supported SDK version to Flutter 3.3/Dart 2.18. * Aligns Dart and Flutter SDK constraints. ## 2.6.3 * Updates links for the merge of flutter/plugins into flutter/packages. * Updates minimum Flutter version to 3.0. ## 2.6.2 * Updates imports for `prefer_relative_imports`. * Updates minimum Flutter version to 2.10. * Fixes avoid_redundant_argument_values lint warnings and minor typos. ## 2.6.1 * Exports new types added for `getMultiImageWithOptions` in 2.6.0. ## 2.6.0 * Deprecates `getMultiImage` in favor of a new method `getMultiImageWithOptions`. * Adds `requestFullMetadata` option that allows disabling extra permission requests on certain platforms. * Moves optional image picking parameters to `MultiImagePickerOptions` class. ## 2.5.0 * Deprecates `getImage` in favor of a new method `getImageFromSource`. * Adds `requestFullMetadata` option that allows disabling extra permission requests on certain platforms. * Moves optional image picking parameters to `ImagePickerOptions` class. * Minor fixes for new analysis options. ## 2.4.4 * Internal code cleanup for stricter analysis options. ## 2.4.3 * Removes dependency on `meta`. ## 2.4.2 * Update to use the `verify` method introduced in plugin_platform_interface 2.1.0. ## 2.4.1 * Reverts the changes from 2.4.0, which was a breaking change that was incorrectly marked as a non-breaking change. ## 2.4.0 * Add `forceFullMetadata` option to `pickImage`. * To keep this non-breaking `forceFullMetadata` defaults to `true`, so the plugin tries to get the full image metadata which may require extra permission requests on certain platforms. * If `forceFullMetadata` is set to `false`, the plugin fetches the image in a way that reduces permission requests from the platform (e.g on iOS the plugin won’t ask for the `NSPhotoLibraryUsageDescription` permission). ## 2.3.0 * Updated `LostDataResponse` to include a `files` property, in case more than one file was recovered. ## 2.2.0 * Added new methods that return `XFile` (from `package:cross_file`) * `getImage` (will deprecate `pickImage`) * `getVideo` (will deprecate `pickVideo`) * `getMultiImage` (will deprecate `pickMultiImage`) _`PickedFile` will also be marked as deprecated in an upcoming release._ ## 2.1.0 * Add `pickMultiImage` method. ## 2.0.1 * Update platform_plugin_interface version requirement. ## 2.0.0 * Migrate to null safety. * Breaking Changes: * Removed the deprecated methods: `ImagePickerPlatform.retrieveLostDataAsDartIoFile`,`ImagePickerPlatform.pickImagePath` and `ImagePickerPlatform.pickVideoPath`. * Removed deprecated class: `LostDataResponse`. ## 1.1.6 * Fix test asset file location. ## 1.1.5 * Update Flutter SDK constraint. ## 1.1.4 * Pass `Uri`s to `package:http` methods, instead of strings, in preparation for a major version update in `http`. ## 1.1.3 * Update documentation of `pickImage()` regarding HEIC images. ## 1.1.2 * Update documentation of `pickImage()` regarding compression support for specific image types. ## 1.1.1 * Update documentation of getImage() about Android's disability to preference front/rear camera. ## 1.1.0 * Introduce PickedFile type for the new API. ## 1.0.1 * Update lower bound of dart dependency to 2.1.0. ## 1.0.0 * Initial release.
packages/packages/image_picker/image_picker_platform_interface/CHANGELOG.md/0
{ "file_path": "packages/packages/image_picker/image_picker_platform_interface/CHANGELOG.md", "repo_id": "packages", "token_count": 1327 }
1,025
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; import 'dart:io'; import 'dart:typed_data'; import './base.dart'; /// A PickedFile backed by a dart:io File. class PickedFile extends PickedFileBase { /// Construct a PickedFile object backed by a dart:io File. PickedFile(super.path) : _file = File(path); final File _file; @override String get path { return _file.path; } @override Future<String> readAsString({Encoding encoding = utf8}) { return _file.readAsString(encoding: encoding); } @override Future<Uint8List> readAsBytes() { return _file.readAsBytes(); } @override Stream<Uint8List> openRead([int? start, int? end]) { return _file .openRead(start ?? 0, end) .map((List<int> chunk) => Uint8List.fromList(chunk)); } }
packages/packages/image_picker/image_picker_platform_interface/lib/src/types/picked_file/io.dart/0
{ "file_path": "packages/packages/image_picker/image_picker_platform_interface/lib/src/types/picked_file/io.dart", "repo_id": "packages", "token_count": 335 }
1,026
// Copyright 2013 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:flutter_test/flutter_test.dart'; import 'package:in_app_purchase/in_app_purchase.dart'; import 'package:integration_test/integration_test.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); testWidgets('Can create InAppPurchase instance', (WidgetTester tester) async { final InAppPurchase iapInstance = InAppPurchase.instance; expect(iapInstance, isNotNull); }); }
packages/packages/in_app_purchase/in_app_purchase/example/integration_test/in_app_purchase_test.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase/example/integration_test/in_app_purchase_test.dart", "repo_id": "packages", "token_count": 182 }
1,027
## 0.3.2 * Adds UserChoiceBilling APIs to platform addition. * Updates minimum supported SDK version to Flutter 3.13/Dart 3.1. ## 0.3.1 * Adds alternative-billing-only APIs to InAppPurchaseAndroidPlatformAddition. ## 0.3.0+18 * Adds new getCountryCode() method to InAppPurchaseAndroidPlatformAddition to get a customer's country code. * Updates compileSdk version to 34. ## 0.3.0+17 * Bumps androidx.annotation:annotation from 1.7.0 to 1.7.1. ## 0.3.0+16 * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. * Fixes new lint warnings. ## 0.3.0+15 * Adds missing network error response code to BillingResponse enum. ## 0.3.0+14 * Updates annotations lib to 1.7.0. ## 0.3.0+13 * Updates example code for current versions of Flutter. ## 0.3.0+12 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 0.3.0+11 * Migrates `styleFrom` usage in examples off of deprecated `primary` and `onPrimary` parameters. ## 0.3.0+10 * Bumps com.android.billingclient:billing from 6.0.0 to 6.0.1. ## 0.3.0+9 * Bumps com.android.billingclient:billing from 5.2.0 to 6.0.0. ## 0.3.0+8 * Adds a [guide for migrating](migration_guide.md) to [0.3.0](#0.3.0). ## 0.3.0+7 * Bumps org.mockito:mockito-core from 4.7.0 to 5.3.1. ## 0.3.0+6 * Bumps org.jetbrains.kotlin:kotlin-bom from 1.8.21 to 1.8.22. ## 0.3.0+5 * Bumps org.jetbrains.kotlin:kotlin-bom from 1.8.0 to 1.8.21. ## 0.3.0+4 * Fixes unawaited_futures violations. ## 0.3.0+3 * Fixes Java lint issues. ## 0.3.0+2 * Removes obsolete null checks on non-nullable values. ## 0.3.0+1 * Fixes misaligned method signature strings. ## 0.3.0 * **BREAKING CHANGE**: Removes `launchPriceChangeConfirmationFlow` from `InAppPurchaseAndroidPlatform`. Price changes are now [handled by Google Play](https://developer.android.com/google/play/billing/subscriptions#price-change). * Returns both base plans and offers when `queryProductDetailsAsync` is called. ## 0.2.5+5 * Updates gradle, AGP and fixes some lint errors. ## 0.2.5+4 * Fixes compatibility with AGP versions older than 4.2. ## 0.2.5+3 * Updates com.android.billingclient:billing from 5.1.0 to 5.2.0. ## 0.2.5+2 * Updates androidx.annotation:annotation from 1.5.0 to 1.6.0. ## 0.2.5+1 * Adds a namespace for compatibility with AGP 8.0. ## 0.2.5 * Fixes the management of `BillingClient` connection by handling `BillingResponse.serviceDisconnected`. * Introduces `BillingClientManager`. * Updates minimum Flutter version to 3.3. ## 0.2.4+3 * Clarifies explanation of endorsement in README. * Aligns Dart and Flutter SDK constraints. * Updates compileSdkVersion to 33. ## 0.2.4+2 * Updates links for the merge of flutter/plugins into flutter/packages. ## 0.2.4+1 * Updates Google Play Billing Library to 5.1.0. * Updates androidx.annotation to 1.5.0. ## 0.2.4 * Updates minimum Flutter version to 3.0. * Ignores a lint in the example app for backwards compatibility. ## 0.2.3+9 * Updates `androidx.test.espresso:espresso-core` to 3.5.1. ## 0.2.3+8 * Updates code for stricter lint checks. ## 0.2.3+7 * Updates code for new analysis options. ## 0.2.3+6 * Updates android gradle plugin to 7.3.1. ## 0.2.3+5 * Updates imports for `prefer_relative_imports`. ## 0.2.3+4 * Updates minimum Flutter version to 2.10. * Adds IMMEDIATE_AND_CHARGE_FULL_PRICE to the `ProrationMode`. ## 0.2.3+3 * Fixes avoid_redundant_argument_values lint warnings and minor typos. ## 0.2.3+2 * Fixes incorrect json key in `queryPurchasesAsync` that fixes restore purchases functionality. ## 0.2.3+1 * Updates `json_serializable` to fix warnings in generated code. ## 0.2.3 * Upgrades Google Play Billing Library to 5.0 * Migrates APIs to support breaking changes in new Google Play Billing API * `PurchaseWrapper` and `PurchaseHistoryRecordWrapper` now handles `skus` a list of sku strings. `sku` is deprecated. ## 0.2.2+8 * Ignores deprecation warnings for upcoming styleFrom button API changes. ## 0.2.2+7 * Updates references to the obsolete master branch. ## 0.2.2+6 * Enables mocking models by changing overridden operator == parameter type from `dynamic` to `Object`. ## 0.2.2+5 * Minor fixes for new analysis options. ## 0.2.2+4 * Removes unnecessary imports. * Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors lint warnings. ## 0.2.2+3 * Migrates from `ui.hash*` to `Object.hash*`. * Updates minimum Flutter version to 2.5.0. ## 0.2.2+2 * Internal code cleanup for stricter analysis options. ## 0.2.2+1 * Removes the dependency on `meta`. ## 0.2.2 * Fixes the `purchaseStream` incorrectly reporting `PurchaseStatus.error` when user upgrades subscription by deferred proration mode. ## 0.2.1 * Deprecated the `InAppPurchaseAndroidPlatformAddition.enablePendingPurchases()` method and `InAppPurchaseAndroidPlatformAddition.enablePendingPurchase` property. Since Google Play no longer accepts App submissions that don't support pending purchases it is no longer necessary to acknowledge this through code. * Updates example app Android compileSdkVersion to 31. ## 0.2.0 * BREAKING CHANGE : Refactor to handle new `PurchaseStatus` named `canceled`. This means developers can distinguish between an error and user cancellation. ## 0.1.6 * Require Dart SDK >= 2.14. * Update `json_annotation` dependency to `^4.3.0`. ## 0.1.5+1 * Fix a broken link in the README. ## 0.1.5 * Introduced the `SkuDetailsWrapper.introductoryPriceAmountMicros` field of the correct type (`int`) and deprecated the `SkuDetailsWrapper.introductoryPriceMicros` field. * Update dev_dependency `build_runner` to ^2.0.0 and `json_serializable` to ^5.0.2. ## 0.1.4+7 * Ensure that the `SkuDetailsWrapper.introductoryPriceMicros` is populated correctly. ## 0.1.4+6 * Ensure that purchases correctly indicate whether they are acknowledged or not. The `PurchaseDetails.pendingCompletePurchase` field now correctly indicates if the purchase still needs to be completed. ## 0.1.4+5 * Add `implements` to pubspec. * Updated Android lint settings. ## 0.1.4+4 * Removed dependency on the `test` package. ## 0.1.4+3 * Updated installation instructions in README. ## 0.1.4+2 * Added price currency symbol to SkuDetailsWrapper. ## 0.1.4+1 * Fixed typos. ## 0.1.4 * Added support for launchPriceChangeConfirmationFlow in the BillingClientWrapper and in InAppPurchaseAndroidPlatformAddition. ## 0.1.3+1 * Add payment proxy. ## 0.1.3 * Added support for isFeatureSupported in the BillingClientWrapper and in InAppPurchaseAndroidPlatformAddition. ## 0.1.2 * Added support for the obfuscatedAccountId and obfuscatedProfileId in the PurchaseWrapper. ## 0.1.1 * Added support to request a list of active subscriptions and non-consumed one-time purchases on Android, through the `InAppPurchaseAndroidPlatformAddition.queryPastPurchases` method. ## 0.1.0+1 * Migrate maven repository from jcenter to mavenCentral. ## 0.1.0 * Initial open-source release.
packages/packages/in_app_purchase/in_app_purchase_android/CHANGELOG.md/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/CHANGELOG.md", "repo_id": "packages", "token_count": 2415 }
1,028
// Copyright 2013 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. package io.flutter.plugins.inapppurchase; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import androidx.annotation.NonNull; import com.android.billingclient.api.AccountIdentifiers; import com.android.billingclient.api.BillingClient; import com.android.billingclient.api.BillingResult; import com.android.billingclient.api.ProductDetails; import com.android.billingclient.api.Purchase; import com.android.billingclient.api.PurchaseHistoryRecord; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import org.json.JSONException; import org.junit.Before; import org.junit.Test; public class TranslatorTest { private static final String PURCHASE_EXAMPLE_JSON = "{\"orderId\":\"foo\",\"packageName\":\"bar\",\"productId\":\"consumable\",\"purchaseTime\":11111111,\"purchaseState\":0,\"purchaseToken\":\"baz\",\"developerPayload\":\"dummy payload\",\"isAcknowledged\":\"true\", \"obfuscatedAccountId\":\"Account101\", \"obfuscatedProfileId\":\"Profile105\"}"; private static final String IN_APP_PRODUCT_DETAIL_EXAMPLE_JSON = "{\"title\":\"Example title\",\"description\":\"Example description\",\"productId\":\"Example id\",\"type\":\"inapp\",\"name\":\"Example name\",\"oneTimePurchaseOfferDetails\":{\"priceAmountMicros\":990000,\"priceCurrencyCode\":\"USD\",\"formattedPrice\":\"$0.99\"}}"; private static final String SUBS_PRODUCT_DETAIL_EXAMPLE_JSON = "{\"title\":\"Example title 2\",\"description\":\"Example description 2\",\"productId\":\"Example id 2\",\"type\":\"subs\",\"name\":\"Example name 2\",\"subscriptionOfferDetails\":[{\"offerId\":\"Example offer id\",\"basePlanId\":\"Example base plan id\",\"offerTags\":[\"Example offer tag\"],\"offerIdToken\":\"Example offer token\",\"pricingPhases\":[{\"formattedPrice\":\"$0.99\",\"priceCurrencyCode\":\"USD\",\"priceAmountMicros\":990000,\"billingCycleCount\":4,\"billingPeriod\":\"Example billing period\",\"recurrenceMode\":0}]}]}"; Constructor<ProductDetails> productDetailsConstructor; @Before public void setup() throws NoSuchMethodException { Locale locale = new Locale("en", "us"); Locale.setDefault(locale); productDetailsConstructor = ProductDetails.class.getDeclaredConstructor(String.class); productDetailsConstructor.setAccessible(true); } @Test public void fromInAppProductDetail() throws InvocationTargetException, IllegalAccessException, InstantiationException { final ProductDetails expected = productDetailsConstructor.newInstance(IN_APP_PRODUCT_DETAIL_EXAMPLE_JSON); Map<String, Object> serialized = Translator.fromProductDetail(expected); assertSerialized(expected, serialized); } @Test public void fromSubsProductDetail() throws InvocationTargetException, IllegalAccessException, InstantiationException { final ProductDetails expected = productDetailsConstructor.newInstance(SUBS_PRODUCT_DETAIL_EXAMPLE_JSON); Map<String, Object> serialized = Translator.fromProductDetail(expected); assertSerialized(expected, serialized); } @Test public void fromProductDetailsList() throws InvocationTargetException, IllegalAccessException, InstantiationException { final List<ProductDetails> expected = Arrays.asList( productDetailsConstructor.newInstance(IN_APP_PRODUCT_DETAIL_EXAMPLE_JSON), productDetailsConstructor.newInstance(SUBS_PRODUCT_DETAIL_EXAMPLE_JSON)); final List<HashMap<String, Object>> serialized = Translator.fromProductDetailsList(expected); assertEquals(expected.size(), serialized.size()); assertSerialized(expected.get(0), serialized.get(0)); assertSerialized(expected.get(1), serialized.get(1)); } @Test public void fromProductDetailsList_null() { assertEquals(Collections.emptyList(), Translator.fromProductDetailsList(null)); } @Test public void fromPurchase() throws JSONException { final Purchase expected = new Purchase(PURCHASE_EXAMPLE_JSON, "signature"); assertSerialized(expected, Translator.fromPurchase(expected)); } @Test public void fromPurchaseWithoutAccountIds() throws JSONException { final Purchase expected = new PurchaseWithoutAccountIdentifiers(PURCHASE_EXAMPLE_JSON, "signature"); Map<String, Object> serialized = Translator.fromPurchase(expected); assertNotNull(serialized.get("orderId")); assertNull(serialized.get("obfuscatedProfileId")); assertNull(serialized.get("obfuscatedAccountId")); } @Test public void fromPurchaseHistoryRecord() throws JSONException { final PurchaseHistoryRecord expected = new PurchaseHistoryRecord(PURCHASE_EXAMPLE_JSON, "signature"); assertSerialized(expected, Translator.fromPurchaseHistoryRecord(expected)); } @Test public void fromPurchasesHistoryRecordList() throws JSONException { final String purchase2Json = "{\"orderId\":\"foo2\",\"packageName\":\"bar\",\"productId\":\"consumable\",\"purchaseTime\":11111111,\"purchaseState\":0,\"purchaseToken\":\"baz\",\"developerPayload\":\"dummy payload\",\"isAcknowledged\":\"true\"}"; final String signature = "signature"; final List<PurchaseHistoryRecord> expected = Arrays.asList( new PurchaseHistoryRecord(PURCHASE_EXAMPLE_JSON, signature), new PurchaseHistoryRecord(purchase2Json, signature)); final List<HashMap<String, Object>> serialized = Translator.fromPurchaseHistoryRecordList(expected); assertEquals(expected.size(), serialized.size()); assertSerialized(expected.get(0), serialized.get(0)); assertSerialized(expected.get(1), serialized.get(1)); } @Test public void fromPurchasesHistoryRecordList_null() { assertEquals(Collections.emptyList(), Translator.fromPurchaseHistoryRecordList(null)); } @Test public void fromPurchasesList() throws JSONException { final String purchase2Json = "{\"orderId\":\"foo2\",\"packageName\":\"bar\",\"productId\":\"consumable\",\"purchaseTime\":11111111,\"purchaseState\":0,\"purchaseToken\":\"baz\",\"developerPayload\":\"dummy payload\",\"isAcknowledged\":\"true\"}"; final String signature = "signature"; final List<Purchase> expected = Arrays.asList( new Purchase(PURCHASE_EXAMPLE_JSON, signature), new Purchase(purchase2Json, signature)); final List<HashMap<String, Object>> serialized = Translator.fromPurchasesList(expected); assertEquals(expected.size(), serialized.size()); assertSerialized(expected.get(0), serialized.get(0)); assertSerialized(expected.get(1), serialized.get(1)); } @Test public void fromPurchasesList_null() { assertEquals(Collections.emptyList(), Translator.fromPurchasesList(null)); } @Test public void fromBillingResult() { BillingResult newBillingResult = BillingResult.newBuilder() .setDebugMessage("dummy debug message") .setResponseCode(BillingClient.BillingResponseCode.OK) .build(); Map<String, Object> billingResultMap = Translator.fromBillingResult(newBillingResult); assertEquals(billingResultMap.get("responseCode"), newBillingResult.getResponseCode()); assertEquals(billingResultMap.get("debugMessage"), newBillingResult.getDebugMessage()); } @Test public void fromBillingResult_debugMessageNull() { BillingResult newBillingResult = BillingResult.newBuilder().setResponseCode(BillingClient.BillingResponseCode.OK).build(); Map<String, Object> billingResultMap = Translator.fromBillingResult(newBillingResult); assertEquals(billingResultMap.get("responseCode"), newBillingResult.getResponseCode()); assertEquals(billingResultMap.get("debugMessage"), newBillingResult.getDebugMessage()); } @Test public void currencyCodeFromSymbol() { assertEquals("$", Translator.currencySymbolFromCode("USD")); try { Translator.currencySymbolFromCode("EUROPACOIN"); fail("Translator should throw an exception"); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } private void assertSerialized(ProductDetails expected, Map<String, Object> serialized) { assertEquals(expected.getDescription(), serialized.get("description")); assertEquals(expected.getTitle(), serialized.get("title")); assertEquals(expected.getName(), serialized.get("name")); assertEquals(expected.getProductId(), serialized.get("productId")); assertEquals(expected.getProductType(), serialized.get("productType")); ProductDetails.OneTimePurchaseOfferDetails expectedOneTimePurchaseOfferDetails = expected.getOneTimePurchaseOfferDetails(); Object oneTimePurchaseOfferDetailsObject = serialized.get("oneTimePurchaseOfferDetails"); assertEquals( expectedOneTimePurchaseOfferDetails == null, oneTimePurchaseOfferDetailsObject == null); if (expectedOneTimePurchaseOfferDetails != null && oneTimePurchaseOfferDetailsObject != null) { @SuppressWarnings(value = "unchecked") Map<String, Object> oneTimePurchaseOfferDetailsMap = (Map<String, Object>) oneTimePurchaseOfferDetailsObject; assertSerialized(expectedOneTimePurchaseOfferDetails, oneTimePurchaseOfferDetailsMap); } List<ProductDetails.SubscriptionOfferDetails> expectedSubscriptionOfferDetailsList = expected.getSubscriptionOfferDetails(); Object subscriptionOfferDetailsListObject = serialized.get("subscriptionOfferDetails"); assertEquals( expectedSubscriptionOfferDetailsList == null, subscriptionOfferDetailsListObject == null); if (expectedSubscriptionOfferDetailsList != null && subscriptionOfferDetailsListObject != null) { @SuppressWarnings(value = "unchecked") List<Object> subscriptionOfferDetailsListList = (List<Object>) subscriptionOfferDetailsListObject; assertSerialized(expectedSubscriptionOfferDetailsList, subscriptionOfferDetailsListList); } } private void assertSerialized( ProductDetails.OneTimePurchaseOfferDetails expected, Map<String, Object> serialized) { assertEquals(expected.getPriceAmountMicros(), serialized.get("priceAmountMicros")); assertEquals(expected.getPriceCurrencyCode(), serialized.get("priceCurrencyCode")); assertEquals(expected.getFormattedPrice(), serialized.get("formattedPrice")); } private void assertSerialized( List<ProductDetails.SubscriptionOfferDetails> expected, List<Object> serialized) { assertEquals(expected.size(), serialized.size()); for (int i = 0; i < expected.size(); i++) { @SuppressWarnings(value = "unchecked") Map<String, Object> serializedMap = (Map<String, Object>) serialized.get(i); assertSerialized(expected.get(i), serializedMap); } } private void assertSerialized( ProductDetails.SubscriptionOfferDetails expected, Map<String, Object> serialized) { assertEquals(expected.getBasePlanId(), serialized.get("basePlanId")); assertEquals(expected.getOfferId(), serialized.get("offerId")); assertEquals(expected.getOfferTags(), serialized.get("offerTags")); assertEquals(expected.getOfferToken(), serialized.get("offerIdToken")); @SuppressWarnings(value = "unchecked") List<Object> serializedPricingPhases = (List<Object>) serialized.get("pricingPhases"); assertNotNull(serializedPricingPhases); assertSerialized(expected.getPricingPhases(), serializedPricingPhases); } private void assertSerialized(ProductDetails.PricingPhases expected, List<Object> serialized) { List<ProductDetails.PricingPhase> expectedPhases = expected.getPricingPhaseList(); assertEquals(expectedPhases.size(), serialized.size()); for (int i = 0; i < serialized.size(); i++) { @SuppressWarnings(value = "unchecked") Map<String, Object> pricingPhaseMap = (Map<String, Object>) serialized.get(i); assertSerialized(expectedPhases.get(i), pricingPhaseMap); } expected.getPricingPhaseList(); } private void assertSerialized( ProductDetails.PricingPhase expected, Map<String, Object> serialized) { assertEquals(expected.getFormattedPrice(), serialized.get("formattedPrice")); assertEquals(expected.getPriceCurrencyCode(), serialized.get("priceCurrencyCode")); assertEquals(expected.getPriceAmountMicros(), serialized.get("priceAmountMicros")); assertEquals(expected.getBillingCycleCount(), serialized.get("billingCycleCount")); assertEquals(expected.getBillingPeriod(), serialized.get("billingPeriod")); assertEquals(expected.getRecurrenceMode(), serialized.get("recurrenceMode")); } private void assertSerialized(Purchase expected, Map<String, Object> serialized) { assertEquals(expected.getOrderId(), serialized.get("orderId")); assertEquals(expected.getPackageName(), serialized.get("packageName")); assertEquals(expected.getPurchaseTime(), serialized.get("purchaseTime")); assertEquals(expected.getPurchaseToken(), serialized.get("purchaseToken")); assertEquals(expected.getSignature(), serialized.get("signature")); assertEquals(expected.getOriginalJson(), serialized.get("originalJson")); assertEquals(expected.getProducts(), serialized.get("products")); assertEquals(expected.getDeveloperPayload(), serialized.get("developerPayload")); assertEquals(expected.isAcknowledged(), serialized.get("isAcknowledged")); assertEquals(expected.getPurchaseState(), serialized.get("purchaseState")); assertNotNull(expected.getAccountIdentifiers().getObfuscatedAccountId()); assertEquals( expected.getAccountIdentifiers().getObfuscatedAccountId(), serialized.get("obfuscatedAccountId")); assertNotNull(expected.getAccountIdentifiers().getObfuscatedProfileId()); assertEquals( expected.getAccountIdentifiers().getObfuscatedProfileId(), serialized.get("obfuscatedProfileId")); } private void assertSerialized(PurchaseHistoryRecord expected, Map<String, Object> serialized) { assertEquals(expected.getPurchaseTime(), serialized.get("purchaseTime")); assertEquals(expected.getPurchaseToken(), serialized.get("purchaseToken")); assertEquals(expected.getSignature(), serialized.get("signature")); assertEquals(expected.getOriginalJson(), serialized.get("originalJson")); assertEquals(expected.getProducts(), serialized.get("products")); assertEquals(expected.getDeveloperPayload(), serialized.get("developerPayload")); } } class PurchaseWithoutAccountIdentifiers extends Purchase { public PurchaseWithoutAccountIdentifiers(@NonNull String s, @NonNull String s1) throws JSONException { super(s, s1); } @Override public AccountIdentifiers getAccountIdentifiers() { return null; } }
packages/packages/in_app_purchase/in_app_purchase_android/android/src/test/java/io/flutter/plugins/inapppurchase/TranslatorTest.java/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/android/src/test/java/io/flutter/plugins/inapppurchase/TranslatorTest.java", "repo_id": "packages", "token_count": 4847 }
1,029
mock-maker-inline
packages/packages/in_app_purchase/in_app_purchase_android/example/android/app/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/example/android/app/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker", "repo_id": "packages", "token_count": 7 }
1,030
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'alternative_billing_only_reporting_details_wrapper.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** AlternativeBillingOnlyReportingDetailsWrapper _$AlternativeBillingOnlyReportingDetailsWrapperFromJson(Map json) => AlternativeBillingOnlyReportingDetailsWrapper( responseCode: const BillingResponseConverter() .fromJson(json['responseCode'] as int?), debugMessage: json['debugMessage'] as String? ?? '', externalTransactionToken: json['externalTransactionToken'] as String? ?? '', );
packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/alternative_billing_only_reporting_details_wrapper.g.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/alternative_billing_only_reporting_details_wrapper.g.dart", "repo_id": "packages", "token_count": 228 }
1,031
// Copyright 2013 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:flutter/foundation.dart'; import 'package:json_annotation/json_annotation.dart'; import 'billing_client_wrapper.dart'; import 'product_details_wrapper.dart'; // WARNING: Changes to `@JsonSerializable` classes need to be reflected in the // below generated file. Run `flutter packages pub run build_runner watch` to // rebuild and watch for further changes. part 'subscription_offer_details_wrapper.g.dart'; /// Dart wrapper around [`com.android.billingclient.api.ProductDetails.SubscriptionOfferDetails`](https://developer.android.com/reference/com/android/billingclient/api/ProductDetails.SubscriptionOfferDetails). /// /// Represents the available purchase plans to buy a subscription product. @JsonSerializable() @immutable class SubscriptionOfferDetailsWrapper { /// Creates a [SubscriptionOfferDetailsWrapper]. @visibleForTesting const SubscriptionOfferDetailsWrapper({ required this.basePlanId, this.offerId, required this.offerTags, required this.offerIdToken, required this.pricingPhases, }); /// Factory for creating a [SubscriptionOfferDetailsWrapper] from a [Map] /// with the offer details. factory SubscriptionOfferDetailsWrapper.fromJson(Map<String, dynamic> map) => _$SubscriptionOfferDetailsWrapperFromJson(map); /// The base plan id associated with the subscription product. @JsonKey(defaultValue: '') final String basePlanId; /// The offer id associated with the subscription product. /// /// This field is only set for a discounted offer. Returns null for a regular /// base plan. @JsonKey(defaultValue: null) final String? offerId; /// The offer tags associated with this Subscription Offer. @JsonKey(defaultValue: <String>[]) final List<String> offerTags; /// The offer token required to pass in [BillingClient.launchBillingFlow] to /// purchase the subscription product with these [pricingPhases]. @JsonKey(defaultValue: '') final String offerIdToken; /// The pricing phases for the subscription product. @JsonKey(defaultValue: <PricingPhaseWrapper>[]) final List<PricingPhaseWrapper> pricingPhases; @override bool operator ==(Object other) { if (other.runtimeType != runtimeType) { return false; } return other is SubscriptionOfferDetailsWrapper && other.basePlanId == basePlanId && other.offerId == offerId && listEquals(other.offerTags, offerTags) && other.offerIdToken == offerIdToken && listEquals(other.pricingPhases, pricingPhases); } @override int get hashCode { return Object.hash( basePlanId.hashCode, offerId.hashCode, offerTags.hashCode, offerIdToken.hashCode, pricingPhases.hashCode, ); } } /// Represents a pricing phase, describing how a user pays at a point in time. @JsonSerializable() @RecurrenceModeConverter() @immutable class PricingPhaseWrapper { /// Creates a new [PricingPhaseWrapper] from the supplied info. @visibleForTesting const PricingPhaseWrapper({ required this.billingCycleCount, required this.billingPeriod, required this.formattedPrice, required this.priceAmountMicros, required this.priceCurrencyCode, required this.recurrenceMode, }); /// Factory for creating a [PricingPhaseWrapper] from a [Map] with the phase details. factory PricingPhaseWrapper.fromJson(Map<String, dynamic> map) => _$PricingPhaseWrapperFromJson(map); /// Represents a pricing phase, describing how a user pays at a point in time. @JsonKey(defaultValue: 0) final int billingCycleCount; /// Billing period for which the given price applies, specified in ISO 8601 /// format. @JsonKey(defaultValue: '') final String billingPeriod; /// Returns formatted price for the payment cycle, including its currency /// sign. @JsonKey(defaultValue: '') final String formattedPrice; /// Returns the price for the payment cycle in micro-units, where 1,000,000 /// micro-units equal one unit of the currency. @JsonKey(defaultValue: 0) final int priceAmountMicros; /// Returns ISO 4217 currency code for price. @JsonKey(defaultValue: '') final String priceCurrencyCode; /// Returns [RecurrenceMode] for the pricing phase. @JsonKey(defaultValue: RecurrenceMode.nonRecurring) final RecurrenceMode recurrenceMode; @override bool operator ==(Object other) { if (other.runtimeType != runtimeType) { return false; } return other is PricingPhaseWrapper && other.billingCycleCount == billingCycleCount && other.billingPeriod == billingPeriod && other.formattedPrice == formattedPrice && other.priceAmountMicros == priceAmountMicros && other.priceCurrencyCode == priceCurrencyCode && other.recurrenceMode == recurrenceMode; } @override int get hashCode => Object.hash( billingCycleCount, billingPeriod, formattedPrice, priceAmountMicros, priceCurrencyCode, recurrenceMode, ); }
packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/subscription_offer_details_wrapper.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/subscription_offer_details_wrapper.dart", "repo_id": "packages", "token_count": 1651 }
1,032
name: in_app_purchase_android description: An implementation for the Android platform of the Flutter `in_app_purchase` plugin. This uses the Android BillingClient APIs. repository: https://github.com/flutter/packages/tree/main/packages/in_app_purchase/in_app_purchase_android issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+in_app_purchase%22 version: 0.3.2 environment: sdk: ^3.1.0 flutter: ">=3.13.0" flutter: plugin: implements: in_app_purchase platforms: android: package: io.flutter.plugins.inapppurchase pluginClass: InAppPurchasePlugin dependencies: collection: ^1.15.0 flutter: sdk: flutter in_app_purchase_platform_interface: ^1.3.0 json_annotation: ^4.8.0 dev_dependencies: build_runner: ^2.0.0 flutter_test: sdk: flutter json_serializable: ^6.3.1 mockito: 5.4.4 test: ^1.16.0 topics: - in-app-purchase - payment
packages/packages/in_app_purchase/in_app_purchase_android/pubspec.yaml/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/pubspec.yaml", "repo_id": "packages", "token_count": 388 }
1,033
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import '../messages.g.dart'; InAppPurchaseAPI _hostApi = InAppPurchaseAPI(); // ignore: avoid_classes_with_only_static_members /// This class contains static methods to manage StoreKit receipts. class SKReceiptManager { /// Retrieve the receipt data from your application's main bundle. /// /// The receipt data will be based64 encoded. The structure of the payload is defined using ASN.1. /// You can use the receipt data retrieved by this method to validate users' purchases. /// There are 2 ways to do so. Either validate locally or validate with App Store. /// For more details on how to validate the receipt data, you can refer to Apple's document about [`About Receipt Validation`](https://developer.apple.com/library/archive/releasenotes/General/ValidateAppStoreReceipt/Introduction.html#//apple_ref/doc/uid/TP40010573-CH105-SW1). /// If the receipt is invalid or missing, you can use [SKRequestMaker.startRefreshReceiptRequest] to request a new receipt. static Future<String> retrieveReceiptData() async { return (await _hostApi.retrieveReceiptData()) ?? ''; } }
packages/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_receipt_manager.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_storekit/lib/src/store_kit_wrappers/sk_receipt_manager.dart", "repo_id": "packages", "token_count": 359 }
1,034
// Copyright 2013 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:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:in_app_purchase_storekit/src/messages.g.dart'; import 'package:in_app_purchase_storekit/store_kit_wrappers.dart'; import '../test_api.g.dart'; import 'sk_test_stub_objects.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); final FakeStoreKitPlatform fakeStoreKitPlatform = FakeStoreKitPlatform(); setUpAll(() { TestInAppPurchaseApi.setup(fakeStoreKitPlatform); }); setUp(() {}); tearDown(() { fakeStoreKitPlatform.testReturnNull = false; fakeStoreKitPlatform.queueIsActive = null; fakeStoreKitPlatform.getReceiptFailTest = false; }); group('sk_request_maker', () { test('get products method channel', () async { final SkProductResponseWrapper productResponseWrapper = await SKRequestMaker().startProductRequest(<String>['xxx']); expect( productResponseWrapper.products, isNotEmpty, ); expect( productResponseWrapper.products.first.priceLocale.currencySymbol, r'$', ); expect( productResponseWrapper.products.first.priceLocale.currencySymbol, isNot('A'), ); expect( productResponseWrapper.products.first.priceLocale.currencyCode, 'USD', ); expect( productResponseWrapper.products.first.priceLocale.countryCode, 'US', ); expect( productResponseWrapper.invalidProductIdentifiers, isNotEmpty, ); expect( fakeStoreKitPlatform.startProductRequestParam, <String>['xxx'], ); }); test('get products method channel should throw exception', () async { fakeStoreKitPlatform.getProductRequestFailTest = true; expect( SKRequestMaker().startProductRequest(<String>['xxx']), throwsException, ); fakeStoreKitPlatform.getProductRequestFailTest = false; }); test('refreshed receipt', () async { final int receiptCountBefore = fakeStoreKitPlatform.refreshReceiptCount; await SKRequestMaker().startRefreshReceiptRequest( receiptProperties: <String, dynamic>{'isExpired': true}); expect(fakeStoreKitPlatform.refreshReceiptCount, receiptCountBefore + 1); expect(fakeStoreKitPlatform.refreshReceiptParam, <String, dynamic>{'isExpired': true}); }); test('should get null receipt if any exceptions are raised', () async { fakeStoreKitPlatform.getReceiptFailTest = true; expect(() async => SKReceiptManager.retrieveReceiptData(), throwsA(const TypeMatcher<PlatformException>())); }); }); group('sk_receipt_manager', () { test('should get receipt (faking it by returning a `receipt data` string)', () async { final String receiptData = await SKReceiptManager.retrieveReceiptData(); expect(receiptData, 'receipt data'); }); }); group('sk_payment_queue', () { test('canMakePayment should return true', () async { expect(await SKPaymentQueueWrapper.canMakePayments(), true); }); test('storefront returns valid SKStoreFrontWrapper object', () async { final SKPaymentQueueWrapper queue = SKPaymentQueueWrapper(); expect( await queue.storefront(), SKStorefrontWrapper.fromJson(const <String, dynamic>{ 'countryCode': 'USA', 'identifier': 'unique_identifier', })); }); test('transactions should return a valid list of transactions', () async { expect(await SKPaymentQueueWrapper().transactions(), isNotEmpty); }); test( 'throws if observer is not set for payment queue before adding payment', () async { expect(SKPaymentQueueWrapper().addPayment(dummyPayment), throwsAssertionError); }); test('should add payment to the payment queue', () async { final SKPaymentQueueWrapper queue = SKPaymentQueueWrapper(); final TestPaymentTransactionObserver observer = TestPaymentTransactionObserver(); queue.setTransactionObserver(observer); await queue.addPayment(dummyPayment); expect(fakeStoreKitPlatform.payments.first, equals(dummyPayment)); }); test('should finish transaction', () async { final SKPaymentQueueWrapper queue = SKPaymentQueueWrapper(); final TestPaymentTransactionObserver observer = TestPaymentTransactionObserver(); queue.setTransactionObserver(observer); await queue.finishTransaction(dummyTransaction); expect(fakeStoreKitPlatform.transactionsFinished.first, equals(dummyTransaction.toFinishMap())); }); test('should restore transaction', () async { final SKPaymentQueueWrapper queue = SKPaymentQueueWrapper(); final TestPaymentTransactionObserver observer = TestPaymentTransactionObserver(); queue.setTransactionObserver(observer); await queue.restoreTransactions(applicationUserName: 'aUserID'); expect(fakeStoreKitPlatform.applicationNameHasTransactionRestored, 'aUserID'); }); test('startObservingTransactionQueue should call methodChannel', () async { expect(fakeStoreKitPlatform.queueIsActive, isNot(true)); await SKPaymentQueueWrapper().startObservingTransactionQueue(); expect(fakeStoreKitPlatform.queueIsActive, true); }); test('stopObservingTransactionQueue should call methodChannel', () async { expect(fakeStoreKitPlatform.queueIsActive, isNot(false)); await SKPaymentQueueWrapper().stopObservingTransactionQueue(); expect(fakeStoreKitPlatform.queueIsActive, false); }); test('setDelegate should call methodChannel', () async { expect(fakeStoreKitPlatform.isPaymentQueueDelegateRegistered, false); await SKPaymentQueueWrapper().setDelegate(TestPaymentQueueDelegate()); expect(fakeStoreKitPlatform.isPaymentQueueDelegateRegistered, true); await SKPaymentQueueWrapper().setDelegate(null); expect(fakeStoreKitPlatform.isPaymentQueueDelegateRegistered, false); }); test('showPriceConsentIfNeeded should call methodChannel', () async { expect(fakeStoreKitPlatform.showPriceConsent, false); await SKPaymentQueueWrapper().showPriceConsentIfNeeded(); expect(fakeStoreKitPlatform.showPriceConsent, true); }); }); group('Code Redemption Sheet', () { test('presentCodeRedemptionSheet should not throw', () async { expect(fakeStoreKitPlatform.presentCodeRedemption, false); await SKPaymentQueueWrapper().presentCodeRedemptionSheet(); expect(fakeStoreKitPlatform.presentCodeRedemption, true); fakeStoreKitPlatform.presentCodeRedemption = false; }); }); } class FakeStoreKitPlatform implements TestInAppPurchaseApi { // get product request List<dynamic> startProductRequestParam = <dynamic>[]; bool getProductRequestFailTest = false; bool testReturnNull = false; // get receipt request bool getReceiptFailTest = false; // refresh receipt request int refreshReceiptCount = 0; late Map<String, dynamic> refreshReceiptParam; // payment queue List<SKPaymentWrapper> payments = <SKPaymentWrapper>[]; List<Map<String, String>> transactionsFinished = <Map<String, String>>[]; String applicationNameHasTransactionRestored = ''; // present Code Redemption bool presentCodeRedemption = false; // show price consent sheet bool showPriceConsent = false; // indicate if the payment queue delegate is registered bool isPaymentQueueDelegateRegistered = false; // Listen to purchase updates bool? queueIsActive; @override void addPayment(Map<String?, Object?> paymentMap) { payments .add(SKPaymentWrapper.fromJson(Map<String, dynamic>.from(paymentMap))); } @override bool canMakePayments() { return true; } @override SKStorefrontMessage storefront() { return SKStorefrontMessage( countryCode: 'USA', identifier: 'unique_identifier'); } @override List<SKPaymentTransactionMessage?> transactions() => <SKPaymentTransactionMessage>[dummyTransactionMessage]; @override void finishTransaction(Map<String?, String?> finishMap) { transactionsFinished.add(Map<String, String>.from(finishMap)); } @override void presentCodeRedemptionSheet() { presentCodeRedemption = true; } @override void restoreTransactions(String? applicationUserName) { applicationNameHasTransactionRestored = applicationUserName!; } @override Future<SKProductsResponseMessage> startProductRequest( List<String?> productIdentifiers) { startProductRequestParam = productIdentifiers; if (getProductRequestFailTest) { return Future<SKProductsResponseMessage>.value( SKProductsResponseMessage()); } return Future<SKProductsResponseMessage>.value(dummyProductResponseMessage); } @override void registerPaymentQueueDelegate() { isPaymentQueueDelegateRegistered = true; } @override void removePaymentQueueDelegate() { isPaymentQueueDelegateRegistered = false; } @override void startObservingPaymentQueue() { queueIsActive = true; } @override void stopObservingPaymentQueue() { queueIsActive = false; } @override String retrieveReceiptData() { if (getReceiptFailTest) { throw Exception('some arbitrary error'); } return 'receipt data'; } @override Future<void> refreshReceipt({Map<String?, dynamic>? receiptProperties}) { refreshReceiptCount++; refreshReceiptParam = Map.castFrom<dynamic, dynamic, String, dynamic>(receiptProperties!); return Future<void>.sync(() {}); } @override void showPriceConsentIfNeeded() { showPriceConsent = true; } } class TestPaymentQueueDelegate extends SKPaymentQueueDelegateWrapper {} class TestPaymentTransactionObserver extends SKTransactionObserverWrapper { @override void updatedTransactions( {required List<SKPaymentTransactionWrapper> transactions}) {} @override void removedTransactions( {required List<SKPaymentTransactionWrapper> transactions}) {} @override void restoreCompletedTransactionsFailed({required SKError error}) {} @override void paymentQueueRestoreCompletedTransactionsFinished() {} @override bool shouldAddStorePayment( {required SKPaymentWrapper payment, required SKProductWrapper product}) { return true; } }
packages/packages/in_app_purchase/in_app_purchase_storekit/test/store_kit_wrappers/sk_methodchannel_apis_test.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_storekit/test/store_kit_wrappers/sk_methodchannel_apis_test.dart", "repo_id": "packages", "token_count": 3597 }
1,035
org.gradle.jvmargs=-Xmx4G android.useAndroidX=true android.enableJetifier=true
packages/packages/local_auth/local_auth/example/android/gradle.properties/0
{ "file_path": "packages/packages/local_auth/local_auth/example/android/gradle.properties", "repo_id": "packages", "token_count": 30 }
1,036
rootProject.name = 'local_auth'
packages/packages/local_auth/local_auth_android/android/settings.gradle/0
{ "file_path": "packages/packages/local_auth/local_auth_android/android/settings.gradle", "repo_id": "packages", "token_count": 11 }
1,037
// Copyright 2013 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:flutter/foundation.dart' show visibleForTesting; import 'package:flutter/services.dart'; import 'package:local_auth_platform_interface/local_auth_platform_interface.dart'; import 'src/auth_messages_android.dart'; import 'src/messages.g.dart'; export 'package:local_auth_android/src/auth_messages_android.dart'; export 'package:local_auth_platform_interface/types/auth_messages.dart'; export 'package:local_auth_platform_interface/types/auth_options.dart'; export 'package:local_auth_platform_interface/types/biometric_type.dart'; /// The implementation of [LocalAuthPlatform] for Android. class LocalAuthAndroid extends LocalAuthPlatform { /// Creates a new plugin implementation instance. LocalAuthAndroid({ @visibleForTesting LocalAuthApi? api, }) : _api = api ?? LocalAuthApi(); /// Registers this class as the default instance of [LocalAuthPlatform]. static void registerWith() { LocalAuthPlatform.instance = LocalAuthAndroid(); } final LocalAuthApi _api; @override Future<bool> authenticate({ required String localizedReason, required Iterable<AuthMessages> authMessages, AuthenticationOptions options = const AuthenticationOptions(), }) async { assert(localizedReason.isNotEmpty); final AuthResult result = await _api.authenticate( AuthOptions( biometricOnly: options.biometricOnly, sensitiveTransaction: options.sensitiveTransaction, sticky: options.stickyAuth, useErrorDialgs: options.useErrorDialogs), _pigeonStringsFromAuthMessages(localizedReason, authMessages)); // TODO(stuartmorgan): Replace this with structured errors, coordinated // across all platform implementations, per // https://github.com/flutter/flutter/wiki/Contributing-to-Plugins-and-Packages#platform-exception-handling // The PlatformExceptions thrown here are for compatibiilty with the // previous Java implementation. switch (result) { case AuthResult.success: return true; case AuthResult.failure: return false; case AuthResult.errorAlreadyInProgress: throw PlatformException( code: 'auth_in_progress', message: 'Authentication in progress'); case AuthResult.errorNoActivity: throw PlatformException( code: 'no_activity', message: 'local_auth plugin requires a foreground activity'); case AuthResult.errorNotFragmentActivity: throw PlatformException( code: 'no_fragment_activity', message: 'local_auth plugin requires activity to be a FragmentActivity.'); case AuthResult.errorNotAvailable: throw PlatformException( code: 'NotAvailable', message: 'Security credentials not available.'); case AuthResult.errorNotEnrolled: throw PlatformException( code: 'NotEnrolled', message: 'No Biometrics enrolled on this device.'); case AuthResult.errorLockedOutTemporarily: throw PlatformException( code: 'LockedOut', message: 'The operation was canceled because the API is locked out ' 'due to too many attempts. This occurs after 5 failed ' 'attempts, and lasts for 30 seconds.'); case AuthResult.errorLockedOutPermanently: throw PlatformException( code: 'PermanentlyLockedOut', message: 'The operation was canceled because ERROR_LOCKOUT ' 'occurred too many times. Biometric authentication is disabled ' 'until the user unlocks with strong authentication ' '(PIN/Pattern/Password)'); } } @override Future<bool> deviceSupportsBiometrics() async { return _api.deviceCanSupportBiometrics(); } @override Future<List<BiometricType>> getEnrolledBiometrics() async { final List<AuthClassificationWrapper?> result = await _api.getEnrolledBiometrics(); return result .cast<AuthClassificationWrapper>() .map((AuthClassificationWrapper entry) { switch (entry.value) { case AuthClassification.weak: return BiometricType.weak; case AuthClassification.strong: return BiometricType.strong; } }).toList(); } @override Future<bool> isDeviceSupported() async => _api.isDeviceSupported(); @override Future<bool> stopAuthentication() async => _api.stopAuthentication(); AuthStrings _pigeonStringsFromAuthMessages( String localizedReason, Iterable<AuthMessages> messagesList) { AndroidAuthMessages? messages; for (final AuthMessages entry in messagesList) { if (entry is AndroidAuthMessages) { messages = entry; } } return AuthStrings( reason: localizedReason, biometricHint: messages?.biometricHint ?? androidBiometricHint, biometricNotRecognized: messages?.biometricNotRecognized ?? androidBiometricNotRecognized, biometricRequiredTitle: messages?.biometricRequiredTitle ?? androidBiometricRequiredTitle, cancelButton: messages?.cancelButton ?? androidCancelButton, deviceCredentialsRequiredTitle: messages?.deviceCredentialsRequiredTitle ?? androidDeviceCredentialsRequiredTitle, deviceCredentialsSetupDescription: messages?.deviceCredentialsSetupDescription ?? androidDeviceCredentialsSetupDescription, goToSettingsButton: messages?.goToSettingsButton ?? goToSettings, goToSettingsDescription: messages?.goToSettingsDescription ?? androidGoToSettingsDescription, signInTitle: messages?.signInTitle ?? androidSignInTitle); } }
packages/packages/local_auth/local_auth_android/lib/local_auth_android.dart/0
{ "file_path": "packages/packages/local_auth/local_auth_android/lib/local_auth_android.dart", "repo_id": "packages", "token_count": 2114 }
1,038
// Copyright 2013 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. // Autogenerated from Pigeon (v13.1.2), do not edit directly. // See also: https://pub.dev/packages/pigeon #import <Foundation/Foundation.h> @protocol FlutterBinaryMessenger; @protocol FlutterMessageCodec; @class FlutterError; @class FlutterStandardTypedData; NS_ASSUME_NONNULL_BEGIN /// Possible outcomes of an authentication attempt. typedef NS_ENUM(NSUInteger, FLADAuthResult) { /// The user authenticated successfully. FLADAuthResultSuccess = 0, /// The user failed to successfully authenticate. FLADAuthResultFailure = 1, /// The authentication system was not available. FLADAuthResultErrorNotAvailable = 2, /// No biometrics are enrolled. FLADAuthResultErrorNotEnrolled = 3, /// No passcode is set. FLADAuthResultErrorPasscodeNotSet = 4, }; /// Wrapper for FLADAuthResult to allow for nullability. @interface FLADAuthResultBox : NSObject @property(nonatomic, assign) FLADAuthResult value; - (instancetype)initWithValue:(FLADAuthResult)value; @end /// Pigeon equivalent of the subset of BiometricType used by iOS. typedef NS_ENUM(NSUInteger, FLADAuthBiometric) { FLADAuthBiometricFace = 0, FLADAuthBiometricFingerprint = 1, }; /// Wrapper for FLADAuthBiometric to allow for nullability. @interface FLADAuthBiometricBox : NSObject @property(nonatomic, assign) FLADAuthBiometric value; - (instancetype)initWithValue:(FLADAuthBiometric)value; @end @class FLADAuthStrings; @class FLADAuthOptions; @class FLADAuthResultDetails; @class FLADAuthBiometricWrapper; /// Pigeon version of IOSAuthMessages, plus the authorization reason. /// /// See auth_messages_ios.dart for details. @interface FLADAuthStrings : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithReason:(NSString *)reason lockOut:(NSString *)lockOut goToSettingsButton:(NSString *)goToSettingsButton goToSettingsDescription:(NSString *)goToSettingsDescription cancelButton:(NSString *)cancelButton localizedFallbackTitle:(nullable NSString *)localizedFallbackTitle; @property(nonatomic, copy) NSString *reason; @property(nonatomic, copy) NSString *lockOut; @property(nonatomic, copy) NSString *goToSettingsButton; @property(nonatomic, copy) NSString *goToSettingsDescription; @property(nonatomic, copy) NSString *cancelButton; @property(nonatomic, copy, nullable) NSString *localizedFallbackTitle; @end @interface FLADAuthOptions : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithBiometricOnly:(BOOL)biometricOnly sticky:(BOOL)sticky useErrorDialogs:(BOOL)useErrorDialogs; @property(nonatomic, assign) BOOL biometricOnly; @property(nonatomic, assign) BOOL sticky; @property(nonatomic, assign) BOOL useErrorDialogs; @end @interface FLADAuthResultDetails : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithResult:(FLADAuthResult)result errorMessage:(nullable NSString *)errorMessage errorDetails:(nullable NSString *)errorDetails; /// The result of authenticating. @property(nonatomic, assign) FLADAuthResult result; /// A system-provided error message, if any. @property(nonatomic, copy, nullable) NSString *errorMessage; /// System-provided error details, if any. @property(nonatomic, copy, nullable) NSString *errorDetails; @end @interface FLADAuthBiometricWrapper : NSObject /// `init` unavailable to enforce nonnull fields, see the `make` class method. - (instancetype)init NS_UNAVAILABLE; + (instancetype)makeWithValue:(FLADAuthBiometric)value; @property(nonatomic, assign) FLADAuthBiometric value; @end /// The codec used by FLADLocalAuthApi. NSObject<FlutterMessageCodec> *FLADLocalAuthApiGetCodec(void); @protocol FLADLocalAuthApi /// Returns true if this device supports authentication. /// /// @return `nil` only when `error != nil`. - (nullable NSNumber *)isDeviceSupportedWithError:(FlutterError *_Nullable *_Nonnull)error; /// Returns true if this device can support biometric authentication, whether /// any biometrics are enrolled or not. /// /// @return `nil` only when `error != nil`. - (nullable NSNumber *)deviceCanSupportBiometricsWithError:(FlutterError *_Nullable *_Nonnull)error; /// Returns the biometric types that are enrolled, and can thus be used /// without additional setup. /// /// @return `nil` only when `error != nil`. - (nullable NSArray<FLADAuthBiometricWrapper *> *)getEnrolledBiometricsWithError: (FlutterError *_Nullable *_Nonnull)error; /// Attempts to authenticate the user with the provided [options], and using /// [strings] for any UI. - (void)authenticateWithOptions:(FLADAuthOptions *)options strings:(FLADAuthStrings *)strings completion:(void (^)(FLADAuthResultDetails *_Nullable, FlutterError *_Nullable))completion; @end extern void SetUpFLADLocalAuthApi(id<FlutterBinaryMessenger> binaryMessenger, NSObject<FLADLocalAuthApi> *_Nullable api); NS_ASSUME_NONNULL_END
packages/packages/local_auth/local_auth_darwin/darwin/Classes/messages.g.h/0
{ "file_path": "packages/packages/local_auth/local_auth_darwin/darwin/Classes/messages.g.h", "repo_id": "packages", "token_count": 1847 }
1,039
// Mocks generated by Mockito 5.4.4 from annotations // in local_auth_darwin/test/local_auth_darwin_test.dart. // Do not manually edit this file. // ignore_for_file: no_leading_underscores_for_library_prefixes import 'dart:async' as _i3; import 'package:local_auth_darwin/src/messages.g.dart' as _i2; import 'package:mockito/mockito.dart' as _i1; // ignore_for_file: type=lint // ignore_for_file: avoid_redundant_argument_values // ignore_for_file: avoid_setters_without_getters // ignore_for_file: comment_references // ignore_for_file: deprecated_member_use // ignore_for_file: deprecated_member_use_from_same_package // ignore_for_file: implementation_imports // ignore_for_file: invalid_use_of_visible_for_testing_member // ignore_for_file: prefer_const_constructors // ignore_for_file: unnecessary_parenthesis // ignore_for_file: camel_case_types // ignore_for_file: subtype_of_sealed_class class _FakeAuthResultDetails_0 extends _i1.SmartFake implements _i2.AuthResultDetails { _FakeAuthResultDetails_0( Object parent, Invocation parentInvocation, ) : super( parent, parentInvocation, ); } /// A class which mocks [LocalAuthApi]. /// /// See the documentation for Mockito's code generation for more information. class MockLocalAuthApi extends _i1.Mock implements _i2.LocalAuthApi { MockLocalAuthApi() { _i1.throwOnMissingStub(this); } @override _i3.Future<bool> isDeviceSupported() => (super.noSuchMethod( Invocation.method( #isDeviceSupported, [], ), returnValue: _i3.Future<bool>.value(false), ) as _i3.Future<bool>); @override _i3.Future<bool> deviceCanSupportBiometrics() => (super.noSuchMethod( Invocation.method( #deviceCanSupportBiometrics, [], ), returnValue: _i3.Future<bool>.value(false), ) as _i3.Future<bool>); @override _i3.Future<List<_i2.AuthBiometricWrapper?>> getEnrolledBiometrics() => (super.noSuchMethod( Invocation.method( #getEnrolledBiometrics, [], ), returnValue: _i3.Future<List<_i2.AuthBiometricWrapper?>>.value( <_i2.AuthBiometricWrapper?>[]), ) as _i3.Future<List<_i2.AuthBiometricWrapper?>>); @override _i3.Future<_i2.AuthResultDetails> authenticate( _i2.AuthOptions? arg_options, _i2.AuthStrings? arg_strings, ) => (super.noSuchMethod( Invocation.method( #authenticate, [ arg_options, arg_strings, ], ), returnValue: _i3.Future<_i2.AuthResultDetails>.value(_FakeAuthResultDetails_0( this, Invocation.method( #authenticate, [ arg_options, arg_strings, ], ), )), ) as _i3.Future<_i2.AuthResultDetails>); }
packages/packages/local_auth/local_auth_darwin/test/local_auth_darwin_test.mocks.dart/0
{ "file_path": "packages/packages/local_auth/local_auth_darwin/test/local_auth_darwin_test.mocks.dart", "repo_id": "packages", "token_count": 1280 }
1,040
// Copyright 2013 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. /// Strings used for MetricPoint tag keys const String kGithubRepoKey = 'gitRepo'; /// Strings used for MetricPoint tag keys const String kGitRevisionKey = 'gitRevision'; /// Strings used for MetricPoint tag keys const String kUnitKey = 'unit'; /// Strings used for MetricPoint tag keys const String kNameKey = 'name'; /// Strings used for MetricPoint tag keys const String kSubResultKey = 'subResult'; /// Flutter repo name. const String kFlutterFrameworkRepo = 'flutter/flutter'; /// Engine repo name. const String kFlutterEngineRepo = 'flutter/engine'; /// The key for the GCP project id in the credentials json. const String kProjectId = 'project_id'; /// Timeline key in JSON. const String kSourceTimeMicrosName = 'sourceTimeMicros'; /// The prod bucket name for Flutter's instance of Skia Perf. const String kBucketName = 'flutter-skia-perf-prod'; /// The test bucket name for Flutter's instance of Skia Perf. const String kTestBucketName = 'flutter-skia-perf-test'; /// JSON key for Skia Perf's git hash entry. const String kSkiaPerfGitHashKey = 'gitHash'; /// JSON key for Skia Perf's results entry. const String kSkiaPerfResultsKey = 'results'; /// JSON key for Skia Perf's value entry. const String kSkiaPerfValueKey = 'value'; /// JSON key for Skia Perf's options entry. const String kSkiaPerfOptionsKey = 'options'; /// JSON key for Skia Perf's default config entry. const String kSkiaPerfDefaultConfig = 'default';
packages/packages/metrics_center/lib/src/constants.dart/0
{ "file_path": "packages/packages/metrics_center/lib/src/constants.dart", "repo_id": "packages", "token_count": 487 }
1,041
## NEXT * Updates minimum supported SDK version to Flutter 3.13/Dart 3.1. ## 0.3.2+6 * Improves links in README.md. ## 0.3.2+5 * Updates `PendingRequest` to be a `base class` for Dart 3.0 compatibility. * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. ## 0.3.2+4 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 0.3.2+3 * Removes use of `runtimeType.toString()`. * Updates minimum SDK version to Flutter 3.0. ## 0.3.2+2 * Fixes lints warnings. ## 0.3.2+1 * Migrates from `ui.hash*` to `Object.hash*`. ## 0.3.2 * Updates package description. * Make [MDnsClient.start] idempotent. ## 0.3.1 * Close IPv6 sockets on [MDnsClient.stop]. ## 0.3.0+1 * Removed redundant link in README.md file. ## 0.3.0 * Migrate package to null safety. ## 0.2.2 * Fixes parsing of TXT records. Continues parsing on non-utf8 strings. ## 0.2.1 * Fixes the handling of packets containing non-utf8 strings. ## 0.2.0 * Allow configuration of the port and address the mdns query is performed on. ## 0.1.1 * Fixes [flutter/issue/31854](https://github.com/flutter/flutter/issues/31854) where `decodeMDnsResponse` advanced to incorrect code points and ignored some records. ## 0.1.0 * Initial Open Source release. * Migrates the dartino-sdk's mDNS client to Dart 2.0 and Flutter's analysis rules * Breaks from original Dartino code, as it does not use native libraries for macOS and overhauls the `ResourceRecord` class.
packages/packages/multicast_dns/CHANGELOG.md/0
{ "file_path": "packages/packages/multicast_dns/CHANGELOG.md", "repo_id": "packages", "token_count": 521 }
1,042
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io'; import 'package:multicast_dns/src/lookup_resolver.dart'; import 'package:multicast_dns/src/resource_record.dart'; import 'package:test/test.dart'; void main() { testTimeout(); testResult(); testResult2(); testResult3(); } ResourceRecord ip4Result(String name, InternetAddress address) { final int validUntil = DateTime.now().millisecondsSinceEpoch + 2000; return IPAddressResourceRecord(name, validUntil, address: address); } void testTimeout() { test('Resolver does not return with short timeout', () async { const Duration shortTimeout = Duration(milliseconds: 1); final LookupResolver resolver = LookupResolver(); final Stream<ResourceRecord> result = resolver.addPendingRequest( ResourceRecordType.addressIPv4, 'xxx', shortTimeout); expect(await result.isEmpty, isTrue); }); } // One pending request and one response. void testResult() { test('One pending request and one response', () async { const Duration noTimeout = Duration(days: 1); final LookupResolver resolver = LookupResolver(); final Stream<ResourceRecord> futureResult = resolver.addPendingRequest( ResourceRecordType.addressIPv4, 'xxx.local', noTimeout); final ResourceRecord response = ip4Result('xxx.local', InternetAddress('1.2.3.4')); resolver.handleResponse(<ResourceRecord>[response]); final IPAddressResourceRecord result = await futureResult.first as IPAddressResourceRecord; expect('1.2.3.4', result.address.address); resolver.clearPendingRequests(); }); } void testResult2() { test('Two requests', () async { const Duration noTimeout = Duration(days: 1); final LookupResolver resolver = LookupResolver(); final Stream<ResourceRecord> futureResult1 = resolver.addPendingRequest( ResourceRecordType.addressIPv4, 'xxx.local', noTimeout); final Stream<ResourceRecord> futureResult2 = resolver.addPendingRequest( ResourceRecordType.addressIPv4, 'yyy.local', noTimeout); final ResourceRecord response1 = ip4Result('xxx.local', InternetAddress('1.2.3.4')); final ResourceRecord response2 = ip4Result('yyy.local', InternetAddress('2.3.4.5')); resolver.handleResponse(<ResourceRecord>[response2, response1]); final IPAddressResourceRecord result1 = await futureResult1.first as IPAddressResourceRecord; final IPAddressResourceRecord result2 = await futureResult2.first as IPAddressResourceRecord; expect('1.2.3.4', result1.address.address); expect('2.3.4.5', result2.address.address); resolver.clearPendingRequests(); }); } void testResult3() { test('Multiple requests', () async { const Duration noTimeout = Duration(days: 1); final LookupResolver resolver = LookupResolver(); final ResourceRecord response0 = ip4Result('zzz.local', InternetAddress('2.3.4.5')); resolver.handleResponse(<ResourceRecord>[response0]); final Stream<ResourceRecord> futureResult1 = resolver.addPendingRequest( ResourceRecordType.addressIPv4, 'xxx.local', noTimeout); resolver.handleResponse(<ResourceRecord>[response0]); final Stream<ResourceRecord> futureResult2 = resolver.addPendingRequest( ResourceRecordType.addressIPv4, 'yyy.local', noTimeout); resolver.handleResponse(<ResourceRecord>[response0]); final ResourceRecord response1 = ip4Result('xxx.local', InternetAddress('1.2.3.4')); resolver.handleResponse(<ResourceRecord>[response0]); final ResourceRecord response2 = ip4Result('yyy.local', InternetAddress('2.3.4.5')); resolver.handleResponse(<ResourceRecord>[response0]); resolver.handleResponse(<ResourceRecord>[response2, response1]); resolver.handleResponse(<ResourceRecord>[response0]); final IPAddressResourceRecord result1 = await futureResult1.first as IPAddressResourceRecord; final IPAddressResourceRecord result2 = await futureResult2.first as IPAddressResourceRecord; expect('1.2.3.4', result1.address.address); expect('2.3.4.5', result2.address.address); resolver.clearPendingRequests(); }); }
packages/packages/multicast_dns/test/lookup_resolver_test.dart/0
{ "file_path": "packages/packages/multicast_dns/test/lookup_resolver_test.dart", "repo_id": "packages", "token_count": 1427 }
1,043
#include "Generated.xcconfig"
packages/packages/palette_generator/example/ios/Flutter/Debug.xcconfig/0
{ "file_path": "packages/packages/palette_generator/example/ios/Flutter/Debug.xcconfig", "repo_id": "packages", "token_count": 12 }
1,044
// Copyright 2013 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. // TODO(goderbauer): Fix this warning for the classes in this file. // ignore_for_file: avoid_equals_and_hash_code_on_mutable_classes import 'dart:async'; import 'dart:collection'; import 'dart:math' as math; import 'dart:ui' as ui; import 'dart:ui' show Color, ImageByteFormat; import 'package:collection/collection.dart' show HeapPriorityQueue, PriorityQueue; import 'package:flutter/foundation.dart'; import 'package:flutter/painting.dart'; /// A description of an encoded image. /// /// Used in [PaletteGenerator.fromByteData]. class EncodedImage { /// Creates a description of an encoded image. const EncodedImage( this.byteData, { required this.width, required this.height, }); /// Encoded image byte data. final ByteData byteData; /// Image width. final int width; /// Image height. final int height; } /// A class to extract prominent colors from an image for use as user interface /// colors. /// /// To create a new [PaletteGenerator], use the asynchronous /// [PaletteGenerator.fromImage] static function. /// /// A number of color paletteColors with different profiles are chosen from the /// image: /// /// * [vibrantColor] /// * [darkVibrantColor] /// * [lightVibrantColor] /// * [mutedColor] /// * [darkMutedColor] /// * [lightMutedColor] /// /// You may add your own target palette color types by supplying them to the /// `targets` parameter for [PaletteGenerator.fromImage]. /// /// In addition, the population-sorted list of discovered [colors] is available, /// and a [paletteColors] list providing contrasting title text and body text /// colors for each palette color. /// /// The palette is created using a color quantizer based on the Median-cut /// algorithm, but optimized for picking out distinct colors rather than /// representative colors. /// /// The color space is represented as a 3-dimensional cube with each dimension /// being one component of an RGB image. The cube is then repeatedly divided /// until the color space is reduced to the requested number of colors. An /// average color is then generated from each cube. /// /// What makes this different from a median-cut algorithm is that median-cut /// divides cubes so that all of the cubes have roughly the same population, /// where the quantizer that is used to create the palette divides cubes based /// on their color volume. This means that the color space is divided into /// distinct colors, rather than representative colors. /// /// See also: /// /// * [PaletteColor], to contain various pieces of metadata about a chosen /// palette color. /// * [PaletteTarget], to be able to create your own target color types. /// * [PaletteFilter], a function signature for filtering the allowed colors /// in the palette. class PaletteGenerator with Diagnosticable { /// Create a [PaletteGenerator] from a set of paletteColors and targets. /// /// The usual way to create a [PaletteGenerator] is to use the asynchronous /// [PaletteGenerator.fromImage] static function. This constructor is mainly /// used for cases when you have your own source of color information and /// would like to use the target selection and scoring methods here. PaletteGenerator.fromColors( this.paletteColors, { this.targets = const <PaletteTarget>[], }) : selectedSwatches = <PaletteTarget, PaletteColor>{} { _sortSwatches(); _selectSwatches(); } // TODO(gspencergoog): remove `dart:ui` paragraph from [fromByteData] method when https://github.com/flutter/flutter/issues/10647 is resolved /// Create a [PaletteGenerator] asynchronously from encoded image [ByteData], /// width, and height. These parameters are packed in [EncodedImage]. /// /// The image encoding must be RGBA with 8 bits per channel, this corresponds to /// [ImageByteFormat.rawRgba] or [ImageByteFormat.rawStraightRgba]. /// /// In contast with [fromImage] and [fromImageProvider] this method can be used /// in non-root isolates, because it doesn't involve interaction with the /// `dart:ui` library, which is currently not supported, see https://github.com/flutter/flutter/issues/10647. /// /// The [region] specifies the part of the image to inspect for color /// candidates. By default it uses the entire image. Must not be equal to /// [Rect.zero], and must not be larger than the image dimensions. /// /// The [maximumColorCount] sets the maximum number of colors that will be /// returned in the [PaletteGenerator]. The default is 16 colors. /// /// The [filters] specify a lost of [PaletteFilter] instances that can be used /// to include certain colors in the list of colors. The default filter is /// an instance of [AvoidRedBlackWhitePaletteFilter], which stays away from /// whites, blacks, and low-saturation reds. /// /// The [targets] are a list of target color types, specified by creating /// custom [PaletteTarget]s. By default, this is the list of targets in /// [PaletteTarget.baseTargets]. static Future<PaletteGenerator> fromByteData( EncodedImage encodedImage, { Rect? region, int maximumColorCount = _defaultCalculateNumberColors, List<PaletteFilter> filters = const <PaletteFilter>[ avoidRedBlackWhitePaletteFilter ], List<PaletteTarget> targets = const <PaletteTarget>[], }) async { assert(region == null || region != Rect.zero); assert( region == null || (region.topLeft.dx >= 0.0 && region.topLeft.dy >= 0.0), 'Region $region is outside the image ${encodedImage.width}x${encodedImage.height}'); assert( region == null || (region.bottomRight.dx <= encodedImage.width && region.bottomRight.dy <= encodedImage.height), 'Region $region is outside the image ${encodedImage.width}x${encodedImage.height}'); assert( encodedImage.byteData.lengthInBytes ~/ 4 == encodedImage.width * encodedImage.height, "Image byte data doesn't match the image size, or has invalid encoding. " 'The encoding must be RGBA with 8 bits per channel.', ); final _ColorCutQuantizer quantizer = _ColorCutQuantizer( encodedImage, maxColors: maximumColorCount, filters: filters, region: region, ); final List<PaletteColor> colors = await quantizer.quantizedColors; return PaletteGenerator.fromColors( colors, targets: targets, ); } /// Create a [PaletteGenerator] from an [dart:ui.Image] asynchronously. /// /// The [region] specifies the part of the image to inspect for color /// candidates. By default it uses the entire image. Must not be equal to /// [Rect.zero], and must not be larger than the image dimensions. /// /// The [maximumColorCount] sets the maximum number of colors that will be /// returned in the [PaletteGenerator]. The default is 16 colors. /// /// The [filters] specify a lost of [PaletteFilter] instances that can be used /// to include certain colors in the list of colors. The default filter is /// an instance of [AvoidRedBlackWhitePaletteFilter], which stays away from /// whites, blacks, and low-saturation reds. /// /// The [targets] are a list of target color types, specified by creating /// custom [PaletteTarget]s. By default, this is the list of targets in /// [PaletteTarget.baseTargets]. static Future<PaletteGenerator> fromImage( ui.Image image, { Rect? region, int maximumColorCount = _defaultCalculateNumberColors, List<PaletteFilter> filters = const <PaletteFilter>[ avoidRedBlackWhitePaletteFilter ], List<PaletteTarget> targets = const <PaletteTarget>[], }) async { final ByteData? imageData = await image.toByteData(); if (imageData == null) { throw StateError('Failed to encode the image.'); } return PaletteGenerator.fromByteData( EncodedImage( imageData, width: image.width, height: image.height, ), region: region, maximumColorCount: maximumColorCount, filters: filters, targets: targets, ); } /// Create a [PaletteGenerator] from an [ImageProvider], like [FileImage], or /// [AssetImage], asynchronously. /// /// The [size] is the desired size of the image. The image will be resized to /// this size before creating the [PaletteGenerator] from it. /// /// The [region] specifies the part of the (resized) image to inspect for /// color candidates. By default it uses the entire image. Must not be equal /// to [Rect.zero], and must not be larger than the image dimensions. /// /// The [maximumColorCount] sets the maximum number of colors that will be /// returned in the [PaletteGenerator]. The default is 16 colors. /// /// The [filters] specify a lost of [PaletteFilter] instances that can be used /// to include certain colors in the list of colors. The default filter is /// an instance of [AvoidRedBlackWhitePaletteFilter], which stays away from /// whites, blacks, and low-saturation reds. /// /// The [targets] are a list of target color types, specified by creating /// custom [PaletteTarget]s. By default, this is the list of targets in /// [PaletteTarget.baseTargets]. /// /// The [timeout] describes how long to wait for the image to load before /// giving up on it. A value of Duration.zero implies waiting forever. The /// default timeout is 15 seconds. static Future<PaletteGenerator> fromImageProvider( ImageProvider imageProvider, { Size? size, Rect? region, int maximumColorCount = _defaultCalculateNumberColors, List<PaletteFilter> filters = const <PaletteFilter>[ avoidRedBlackWhitePaletteFilter ], List<PaletteTarget> targets = const <PaletteTarget>[], Duration timeout = const Duration(seconds: 15), }) async { assert(region == null || size != null); assert(region == null || region != Rect.zero); assert( region == null || (region.topLeft.dx >= 0.0 && region.topLeft.dy >= 0.0), 'Region $region is outside the image ${size!.width}x${size.height}'); assert(region == null || size!.contains(region.topLeft), 'Region $region is outside the image $size'); assert( region == null || (region.bottomRight.dx <= size!.width && region.bottomRight.dy <= size.height), 'Region $region is outside the image $size'); final ImageStream stream = imageProvider.resolve( ImageConfiguration(size: size, devicePixelRatio: 1.0), ); final Completer<ui.Image> imageCompleter = Completer<ui.Image>(); Timer? loadFailureTimeout; late ImageStreamListener listener; listener = ImageStreamListener((ImageInfo info, bool synchronousCall) { loadFailureTimeout?.cancel(); stream.removeListener(listener); imageCompleter.complete(info.image); }); if (timeout != Duration.zero) { loadFailureTimeout = Timer(timeout, () { stream.removeListener(listener); imageCompleter.completeError( TimeoutException( 'Timeout occurred trying to load from $imageProvider'), ); }); } stream.addListener(listener); final ui.Image image = await imageCompleter.future; ui.Rect? newRegion = region; if (size != null && region != null) { final double scale = image.width / size.width; newRegion = Rect.fromLTRB( region.left * scale, region.top * scale, region.right * scale, region.bottom * scale, ); } return PaletteGenerator.fromImage( image, region: newRegion, maximumColorCount: maximumColorCount, filters: filters, targets: targets, ); } static const int _defaultCalculateNumberColors = 16; /// Provides a map of the selected paletteColors for each target in [targets]. final Map<PaletteTarget, PaletteColor> selectedSwatches; /// The list of [PaletteColor]s that make up the palette, sorted from most /// dominant color to least dominant color. final List<PaletteColor> paletteColors; /// The list of targets that the palette uses for custom color selection. /// /// By default, this contains the entire list of predefined targets in /// [PaletteTarget.baseTargets]. final List<PaletteTarget> targets; /// Returns a list of colors in the [paletteColors], sorted from most /// dominant to least dominant color. Iterable<Color> get colors sync* { for (final PaletteColor paletteColor in paletteColors) { yield paletteColor.color; } } /// Returns a vibrant color from the palette. Might be null if an appropriate /// target color could not be found. PaletteColor? get vibrantColor => selectedSwatches[PaletteTarget.vibrant]; /// Returns a light and vibrant color from the palette. Might be null if an /// appropriate target color could not be found. PaletteColor? get lightVibrantColor => selectedSwatches[PaletteTarget.lightVibrant]; /// Returns a dark and vibrant color from the palette. Might be null if an /// appropriate target color could not be found. PaletteColor? get darkVibrantColor => selectedSwatches[PaletteTarget.darkVibrant]; /// Returns a muted color from the palette. Might be null if an appropriate /// target color could not be found. PaletteColor? get mutedColor => selectedSwatches[PaletteTarget.muted]; /// Returns a muted and light color from the palette. Might be null if an /// appropriate target color could not be found. PaletteColor? get lightMutedColor => selectedSwatches[PaletteTarget.lightMuted]; /// Returns a muted and dark color from the palette. Might be null if an /// appropriate target color could not be found. PaletteColor? get darkMutedColor => selectedSwatches[PaletteTarget.darkMuted]; /// The dominant color (the color with the largest population). PaletteColor? get dominantColor => _dominantColor; PaletteColor? _dominantColor; void _sortSwatches() { if (paletteColors.isEmpty) { _dominantColor = null; return; } // Sort from most common to least common. paletteColors.sort((PaletteColor a, PaletteColor b) { return b.population.compareTo(a.population); }); _dominantColor = paletteColors[0]; } void _selectSwatches() { final Set<PaletteTarget> allTargets = Set<PaletteTarget>.from(targets + PaletteTarget.baseTargets); final Set<Color> usedColors = <Color>{}; for (final PaletteTarget target in allTargets) { target._normalizeWeights(); final PaletteColor? targetScore = _generateScoredTarget(target, usedColors); if (targetScore != null) { selectedSwatches[target] = targetScore; } } } PaletteColor? _generateScoredTarget( PaletteTarget target, Set<Color> usedColors) { final PaletteColor? maxScoreSwatch = _getMaxScoredSwatchForTarget(target, usedColors); if (maxScoreSwatch != null && target.isExclusive) { // If we have a color, and the target is exclusive, add the color to the // used list. usedColors.add(maxScoreSwatch.color); } return maxScoreSwatch; } PaletteColor? _getMaxScoredSwatchForTarget( PaletteTarget target, Set<Color> usedColors) { double maxScore = 0.0; PaletteColor? maxScoreSwatch; for (final PaletteColor paletteColor in paletteColors) { if (_shouldBeScoredForTarget(paletteColor, target, usedColors)) { final double score = _generateScore(paletteColor, target); if (maxScoreSwatch == null || score > maxScore) { maxScoreSwatch = paletteColor; maxScore = score; } } } return maxScoreSwatch; } bool _shouldBeScoredForTarget( PaletteColor paletteColor, PaletteTarget target, Set<Color> usedColors) { // Check whether the HSL lightness is within the correct range, and that // this color hasn't been used yet. final HSLColor hslColor = HSLColor.fromColor(paletteColor.color); return hslColor.saturation >= target.minimumSaturation && hslColor.saturation <= target.maximumSaturation && hslColor.lightness >= target.minimumLightness && hslColor.lightness <= target.maximumLightness && !usedColors.contains(paletteColor.color); } double _generateScore(PaletteColor paletteColor, PaletteTarget target) { final HSLColor hslColor = HSLColor.fromColor(paletteColor.color); double saturationScore = 0.0; double valueScore = 0.0; double populationScore = 0.0; if (target.saturationWeight > 0.0) { saturationScore = target.saturationWeight * (1.0 - (hslColor.saturation - target.targetSaturation).abs()); } if (target.lightnessWeight > 0.0) { valueScore = target.lightnessWeight * (1.0 - (hslColor.lightness - target.targetLightness).abs()); } if (_dominantColor != null && target.populationWeight > 0.0) { populationScore = target.populationWeight * (paletteColor.population / _dominantColor!.population); } return saturationScore + valueScore + populationScore; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(IterableProperty<PaletteColor>( 'paletteColors', paletteColors, defaultValue: <PaletteColor>[])); properties.add(IterableProperty<PaletteTarget>('targets', targets, defaultValue: PaletteTarget.baseTargets)); } } /// A class which allows custom selection of colors when a [PaletteGenerator] is /// generated. /// /// To add a target, supply it to the `targets` list in /// [PaletteGenerator.fromImage] or [PaletteGenerator..fromColors]. /// /// See also: /// /// * [PaletteGenerator], a class for selecting color palettes from images. class PaletteTarget with Diagnosticable { /// Creates a [PaletteTarget] for custom palette selection. PaletteTarget({ this.minimumSaturation = 0.0, this.targetSaturation = 0.5, this.maximumSaturation = 1.0, this.minimumLightness = 0.0, this.targetLightness = 0.5, this.maximumLightness = 1.0, this.isExclusive = true, }); /// The minimum saturation value for this target. final double minimumSaturation; /// The target saturation value for this target. final double targetSaturation; /// The maximum saturation value for this target. final double maximumSaturation; /// The minimum lightness value for this target. final double minimumLightness; /// The target lightness value for this target. final double targetLightness; /// The maximum lightness value for this target. final double maximumLightness; /// Returns whether any color selected for this target is exclusive for this /// target only. /// /// If false, then the color can also be selected for other targets. Defaults /// to true. final bool isExclusive; /// The weight of importance that a color's saturation value has on selection. double saturationWeight = _weightSaturation; /// The weight of importance that a color's lightness value has on selection. double lightnessWeight = _weightLightness; /// The weight of importance that a color's population value has on selection. double populationWeight = _weightPopulation; static const double _targetDarkLightness = 0.26; static const double _maxDarkLightness = 0.45; static const double _minLightLightness = 0.55; static const double _targetLightLightness = 0.74; static const double _minNormalLightness = 0.3; static const double _maxNormalLightness = 0.7; static const double _targetMutedSaturation = 0.3; static const double _maxMutedSaturation = 0.4; static const double _targetVibrantSaturation = 1.0; static const double _minVibrantSaturation = 0.35; static const double _weightSaturation = 0.24; static const double _weightLightness = 0.52; static const double _weightPopulation = 0.24; /// A target which has the characteristics of a vibrant color which is light /// in luminance. /// /// One of the base set of `targets` for [PaletteGenerator.fromImage], in [baseTargets]. static final PaletteTarget lightVibrant = PaletteTarget( targetLightness: _targetLightLightness, minimumLightness: _minLightLightness, minimumSaturation: _minVibrantSaturation, targetSaturation: _targetVibrantSaturation, ); /// A target which has the characteristics of a vibrant color which is neither /// light or dark. /// /// One of the base set of `targets` for [PaletteGenerator.fromImage], in [baseTargets]. static final PaletteTarget vibrant = PaletteTarget( minimumLightness: _minNormalLightness, maximumLightness: _maxNormalLightness, minimumSaturation: _minVibrantSaturation, targetSaturation: _targetVibrantSaturation, ); /// A target which has the characteristics of a vibrant color which is dark in /// luminance. /// /// One of the base set of `targets` for [PaletteGenerator.fromImage], in [baseTargets]. static final PaletteTarget darkVibrant = PaletteTarget( targetLightness: _targetDarkLightness, maximumLightness: _maxDarkLightness, minimumSaturation: _minVibrantSaturation, targetSaturation: _targetVibrantSaturation, ); /// A target which has the characteristics of a muted color which is light in /// luminance. /// /// One of the base set of `targets` for [PaletteGenerator.fromImage], in [baseTargets]. static final PaletteTarget lightMuted = PaletteTarget( targetLightness: _targetLightLightness, minimumLightness: _minLightLightness, targetSaturation: _targetMutedSaturation, maximumSaturation: _maxMutedSaturation, ); /// A target which has the characteristics of a muted color which is neither /// light or dark. /// /// One of the base set of `targets` for [PaletteGenerator.fromImage], in [baseTargets]. static final PaletteTarget muted = PaletteTarget( minimumLightness: _minNormalLightness, maximumLightness: _maxNormalLightness, targetSaturation: _targetMutedSaturation, maximumSaturation: _maxMutedSaturation, ); /// A target which has the characteristics of a muted color which is dark in /// luminance. /// /// One of the base set of `targets` for [PaletteGenerator.fromImage], in [baseTargets]. static final PaletteTarget darkMuted = PaletteTarget( targetLightness: _targetDarkLightness, maximumLightness: _maxDarkLightness, targetSaturation: _targetMutedSaturation, maximumSaturation: _maxMutedSaturation, ); /// A list of all the available predefined targets. /// /// The base set of `targets` for [PaletteGenerator.fromImage]. static final List<PaletteTarget> baseTargets = <PaletteTarget>[ lightVibrant, vibrant, darkVibrant, lightMuted, muted, darkMuted, ]; void _normalizeWeights() { final double sum = saturationWeight + lightnessWeight + populationWeight; if (sum != 0.0) { saturationWeight /= sum; lightnessWeight /= sum; populationWeight /= sum; } } @override bool operator ==(Object other) { return other is PaletteTarget && minimumSaturation == other.minimumSaturation && targetSaturation == other.targetSaturation && maximumSaturation == other.maximumSaturation && minimumLightness == other.minimumLightness && targetLightness == other.targetLightness && maximumLightness == other.maximumLightness && saturationWeight == other.saturationWeight && lightnessWeight == other.lightnessWeight && populationWeight == other.populationWeight; } @override int get hashCode { return Object.hash( minimumSaturation, targetSaturation, maximumSaturation, minimumLightness, targetLightness, maximumLightness, saturationWeight, lightnessWeight, populationWeight, ); } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); final PaletteTarget defaultTarget = PaletteTarget(); properties.add(DoubleProperty('minimumSaturation', minimumSaturation, defaultValue: defaultTarget.minimumSaturation)); properties.add(DoubleProperty('targetSaturation', targetSaturation, defaultValue: defaultTarget.targetSaturation)); properties.add(DoubleProperty('maximumSaturation', maximumSaturation, defaultValue: defaultTarget.maximumSaturation)); properties.add(DoubleProperty('minimumLightness', minimumLightness, defaultValue: defaultTarget.minimumLightness)); properties.add(DoubleProperty('targetLightness', targetLightness, defaultValue: defaultTarget.targetLightness)); properties.add(DoubleProperty('maximumLightness', maximumLightness, defaultValue: defaultTarget.maximumLightness)); properties.add(DoubleProperty('saturationWeight', saturationWeight, defaultValue: defaultTarget.saturationWeight)); properties.add(DoubleProperty('lightnessWeight', lightnessWeight, defaultValue: defaultTarget.lightnessWeight)); properties.add(DoubleProperty('populationWeight', populationWeight, defaultValue: defaultTarget.populationWeight)); } } typedef _ContrastCalculator = double Function(Color a, Color b, int alpha); /// A color palette color generated by the [PaletteGenerator]. /// /// This palette color represents a dominant [color] in an image, and has a /// [population] of how many pixels in the source image it represents. It picks /// a [titleTextColor] and a [bodyTextColor] that contrast sufficiently with the /// source [color] for comfortable reading. /// /// See also: /// /// * [PaletteGenerator], a class for selecting color palettes from images. class PaletteColor with Diagnosticable { /// Generate a [PaletteColor]. PaletteColor(this.color, this.population); static const double _minContrastTitleText = 3.0; static const double _minContrastBodyText = 4.5; /// The color that this palette color represents. final Color color; /// The number of pixels in the source image that this palette color /// represents. final int population; /// The color of title text for use with this palette color. Color get titleTextColor { if (_titleTextColor == null) { _ensureTextColorsGenerated(); } return _titleTextColor!; } Color? _titleTextColor; /// The color of body text for use with this palette color. Color get bodyTextColor { if (_bodyTextColor == null) { _ensureTextColorsGenerated(); } return _bodyTextColor!; } Color? _bodyTextColor; void _ensureTextColorsGenerated() { if (_titleTextColor == null || _bodyTextColor == null) { const Color white = Color(0xffffffff); const Color black = Color(0xff000000); // First check white, as most colors will be dark final int? lightBodyAlpha = _calculateMinimumAlpha(white, color, _minContrastBodyText); final int? lightTitleAlpha = _calculateMinimumAlpha(white, color, _minContrastTitleText); if (lightBodyAlpha != null && lightTitleAlpha != null) { // If we found valid light values, use them and return _bodyTextColor = white.withAlpha(lightBodyAlpha); _titleTextColor = white.withAlpha(lightTitleAlpha); return; } final int? darkBodyAlpha = _calculateMinimumAlpha(black, color, _minContrastBodyText); final int? darkTitleAlpha = _calculateMinimumAlpha(black, color, _minContrastTitleText); if (darkBodyAlpha != null && darkTitleAlpha != null) { // If we found valid dark values, use them and return _bodyTextColor = black.withAlpha(darkBodyAlpha); _titleTextColor = black.withAlpha(darkTitleAlpha); return; } // If we reach here then we can not find title and body values which use // the same lightness, we need to use mismatched values _bodyTextColor = lightBodyAlpha != null ? white.withAlpha(lightBodyAlpha) : black.withAlpha(darkBodyAlpha ?? 255); _titleTextColor = lightTitleAlpha != null ? white.withAlpha(lightTitleAlpha) : black.withAlpha(darkTitleAlpha ?? 255); } } /// Returns the contrast ratio between [foreground] and [background]. /// [background] must be opaque. /// /// Formula defined [here](http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef). static double _calculateContrast(Color foreground, Color background) { assert(background.alpha == 0xff, 'background can not be translucent: $background.'); if (foreground.alpha < 0xff) { // If the foreground is translucent, composite the foreground over the // background foreground = Color.alphaBlend(foreground, background); } final double lightness1 = foreground.computeLuminance() + 0.05; final double lightness2 = background.computeLuminance() + 0.05; return math.max(lightness1, lightness2) / math.min(lightness1, lightness2); } // Calculates the minimum alpha value which can be applied to foreground that // would have a contrast value of at least [minContrastRatio] when compared to // background. // // The background must be opaque (alpha of 255). // // Returns the alpha value in the range 0-255, or null if no value could be // calculated. static int? _calculateMinimumAlpha( Color foreground, Color background, double minContrastRatio) { assert(background.alpha == 0xff, 'The background cannot be translucent: $background.'); double contrastCalculator(Color fg, Color bg, int alpha) { final Color testForeground = fg.withAlpha(alpha); return _calculateContrast(testForeground, bg); } // First lets check that a fully opaque foreground has sufficient contrast final double testRatio = contrastCalculator(foreground, background, 0xff); if (testRatio < minContrastRatio) { // Fully opaque foreground does not have sufficient contrast, return error return null; } foreground = foreground.withAlpha(0xff); return _binaryAlphaSearch( foreground, background, minContrastRatio, contrastCalculator); } // Calculates the alpha value using binary search based on a given contrast // evaluation function and target contrast that needs to be satisfied. // // The background must be opaque (alpha of 255). // // Returns the alpha value in the range [0, 255]. static int _binaryAlphaSearch( Color foreground, Color background, double minContrastRatio, _ContrastCalculator calculator, ) { assert(background.alpha == 0xff, 'The background cannot be translucent: $background.'); const int minAlphaSearchMaxIterations = 10; const int minAlphaSearchPrecision = 1; // Binary search to find a value with the minimum value which provides // sufficient contrast int numIterations = 0; int minAlpha = 0; int maxAlpha = 0xff; while (numIterations <= minAlphaSearchMaxIterations && (maxAlpha - minAlpha) > minAlphaSearchPrecision) { final int testAlpha = (minAlpha + maxAlpha) ~/ 2; final double testRatio = calculator(foreground, background, testAlpha); if (testRatio < minContrastRatio) { minAlpha = testAlpha; } else { maxAlpha = testAlpha; } numIterations++; } // Conservatively return the max of the range of possible alphas, which is // known to pass. return maxAlpha; } @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); properties.add(DiagnosticsProperty<Color>('color', color)); properties .add(DiagnosticsProperty<Color>('titleTextColor', titleTextColor)); properties.add(DiagnosticsProperty<Color>('bodyTextColor', bodyTextColor)); properties.add(IntProperty('population', population, defaultValue: 0)); } @override int get hashCode => Object.hash(color, population); @override bool operator ==(Object other) { return other is PaletteColor && color == other.color && population == other.population; } } /// Hook to allow clients to be able filter colors from selected in a /// [PaletteGenerator]. Returns true if the [color] is allowed. /// /// See also: /// /// * [PaletteGenerator.fromImage], which takes a list of these for its /// `filters` parameter. /// * [avoidRedBlackWhitePaletteFilter], the default filter for /// [PaletteGenerator]. typedef PaletteFilter = bool Function(HSLColor color); /// A basic [PaletteFilter], which rejects colors near black, white and low /// saturation red. /// /// Use this as an element in the `filters` list given to [PaletteGenerator.fromImage]. /// /// See also: /// * [PaletteGenerator], a class for selecting color palettes from images. bool avoidRedBlackWhitePaletteFilter(HSLColor color) { bool isBlack(HSLColor hslColor) { const double blackMaxLightness = 0.05; return hslColor.lightness <= blackMaxLightness; } bool isWhite(HSLColor hslColor) { const double whiteMinLightness = 0.95; return hslColor.lightness >= whiteMinLightness; } // Returns true if the color is close to the red side of the I line. bool isNearRedILine(HSLColor hslColor) { const double redLineMinHue = 10.0; const double redLineMaxHue = 37.0; const double redLineMaxSaturation = 0.82; return hslColor.hue >= redLineMinHue && hslColor.hue <= redLineMaxHue && hslColor.saturation <= redLineMaxSaturation; } return !isWhite(color) && !isBlack(color) && !isNearRedILine(color); } enum _ColorComponent { red, green, blue, } /// A box that represents a volume in the RGB color space. class _ColorVolumeBox { _ColorVolumeBox( this._lowerIndex, this._upperIndex, this.histogram, this.colors) { _fitMinimumBox(); } final _ColorHistogram histogram; final List<Color> colors; // The lower and upper index are inclusive. final int _lowerIndex; int _upperIndex; // The population of colors within this box. late int _population; // Bounds in each of the dimensions. late int _minRed; late int _maxRed; late int _minGreen; late int _maxGreen; late int _minBlue; late int _maxBlue; int getVolume() { return (_maxRed - _minRed + 1) * (_maxGreen - _minGreen + 1) * (_maxBlue - _minBlue + 1); } bool canSplit() { return getColorCount() > 1; } int getColorCount() { return 1 + _upperIndex - _lowerIndex; } /// Recomputes the boundaries of this box to tightly fit the colors within the /// box. void _fitMinimumBox() { // Reset the min and max to opposite values int minRed = 256; int minGreen = 256; int minBlue = 256; int maxRed = -1; int maxGreen = -1; int maxBlue = -1; int count = 0; for (int i = _lowerIndex; i <= _upperIndex; i++) { final Color color = colors[i]; count += histogram[color]!.value; if (color.red > maxRed) { maxRed = color.red; } if (color.red < minRed) { minRed = color.red; } if (color.green > maxGreen) { maxGreen = color.green; } if (color.green < minGreen) { minGreen = color.green; } if (color.blue > maxBlue) { maxBlue = color.blue; } if (color.blue < minBlue) { minBlue = color.blue; } } _minRed = minRed; _maxRed = maxRed; _minGreen = minGreen; _maxGreen = maxGreen; _minBlue = minBlue; _maxBlue = maxBlue; _population = count; } /// Split this color box at the mid-point along it's longest dimension. /// /// Returns the new ColorBox. _ColorVolumeBox splitBox() { assert(canSplit(), "Can't split a box with only 1 color"); // find median along the longest dimension final int splitPoint = _findSplitPoint(); final _ColorVolumeBox newBox = _ColorVolumeBox(splitPoint + 1, _upperIndex, histogram, colors); // Now change this box's upperIndex and recompute the color boundaries _upperIndex = splitPoint; _fitMinimumBox(); return newBox; } /// Returns the largest dimension of this color box. _ColorComponent _getLongestColorDimension() { final int redLength = _maxRed - _minRed; final int greenLength = _maxGreen - _minGreen; final int blueLength = _maxBlue - _minBlue; if (redLength >= greenLength && redLength >= blueLength) { return _ColorComponent.red; } else if (greenLength >= redLength && greenLength >= blueLength) { return _ColorComponent.green; } else { return _ColorComponent.blue; } } // Finds where to split this box between _lowerIndex and _upperIndex. // // The split point is calculated by finding the longest color dimension, and // then sorting the sub-array based on that dimension value in each color. // The colors are then iterated over until a color is found with the // midpoint closest to the whole box's dimension midpoint. // // Returns the index of the split point in the colors array. int _findSplitPoint() { final _ColorComponent longestDimension = _getLongestColorDimension(); int compareColors(Color a, Color b) { int makeValue(int first, int second, int third) { return first << 16 | second << 8 | third; } switch (longestDimension) { case _ColorComponent.red: final int aValue = makeValue(a.red, a.green, a.blue); final int bValue = makeValue(b.red, b.green, b.blue); return aValue.compareTo(bValue); case _ColorComponent.green: final int aValue = makeValue(a.green, a.red, a.blue); final int bValue = makeValue(b.green, b.red, b.blue); return aValue.compareTo(bValue); case _ColorComponent.blue: final int aValue = makeValue(a.blue, a.green, a.red); final int bValue = makeValue(b.blue, b.green, b.red); return aValue.compareTo(bValue); } } // We need to sort the colors in this box based on the longest color // dimension. final List<Color> colorSubset = colors.sublist(_lowerIndex, _upperIndex + 1); colorSubset.sort(compareColors); colors.replaceRange(_lowerIndex, _upperIndex + 1, colorSubset); final int median = (_population / 2).round(); for (int i = 0, count = 0; i <= colorSubset.length; i++) { count += histogram[colorSubset[i]]!.value; if (count >= median) { // We never want to split on the upperIndex, as this will result in the // same box. return math.min(_upperIndex - 1, i + _lowerIndex); } } return _lowerIndex; } PaletteColor getAverageColor() { int redSum = 0; int greenSum = 0; int blueSum = 0; int totalPopulation = 0; for (int i = _lowerIndex; i <= _upperIndex; i++) { final Color color = colors[i]; final int colorPopulation = histogram[color]!.value; totalPopulation += colorPopulation; redSum += colorPopulation * color.red; greenSum += colorPopulation * color.green; blueSum += colorPopulation * color.blue; } final int redMean = (redSum / totalPopulation).round(); final int greenMean = (greenSum / totalPopulation).round(); final int blueMean = (blueSum / totalPopulation).round(); return PaletteColor( Color.fromARGB(0xff, redMean, greenMean, blueMean), totalPopulation, ); } } /// Holds mutable count for a color. // Using a mutable count rather than replacing value in the histogram // in the _ColorCutQuantizer speeds up building the histogram significantly. class _ColorCount { int value = 0; } class _ColorHistogram { final Map<int, Map<int, Map<int, _ColorCount>>> _hist = <int, Map<int, Map<int, _ColorCount>>>{}; final DoubleLinkedQueue<Color> _keys = DoubleLinkedQueue<Color>(); _ColorCount? operator [](Color color) { final Map<int, Map<int, _ColorCount>>? redMap = _hist[color.red]; if (redMap == null) { return null; } final Map<int, _ColorCount>? blueMap = redMap[color.blue]; if (blueMap == null) { return null; } return blueMap[color.green]; } void operator []=(Color key, _ColorCount value) { final int red = key.red; final int blue = key.blue; final int green = key.green; bool newColor = false; Map<int, Map<int, _ColorCount>>? redMap = _hist[red]; if (redMap == null) { _hist[red] = redMap = <int, Map<int, _ColorCount>>{}; newColor = true; } Map<int, _ColorCount>? blueMap = redMap[blue]; if (blueMap == null) { redMap[blue] = blueMap = <int, _ColorCount>{}; newColor = true; } if (blueMap[green] == null) { newColor = true; } blueMap[green] = value; if (newColor) { _keys.add(key); } } void removeWhere(bool Function(Color key) predicate) { for (final Color key in _keys) { if (predicate(key)) { _hist[key.red]?[key.blue]?.remove(key.green); } } _keys.removeWhere((Color color) => predicate(color)); } Iterable<Color> get keys { return _keys; } int get length { return _keys.length; } } class _ColorCutQuantizer { _ColorCutQuantizer( this.encodedImage, { this.maxColors = PaletteGenerator._defaultCalculateNumberColors, this.region, this.filters = const <PaletteFilter>[avoidRedBlackWhitePaletteFilter], }) : assert(region == null || region != Rect.zero); final EncodedImage encodedImage; final int maxColors; final Rect? region; final List<PaletteFilter> filters; Completer<List<PaletteColor>>? _paletteColorsCompleter; FutureOr<List<PaletteColor>> get quantizedColors async { if (_paletteColorsCompleter == null) { _paletteColorsCompleter = Completer<List<PaletteColor>>(); _paletteColorsCompleter!.complete(_quantizeColors()); } return _paletteColorsCompleter!.future; } Iterable<Color> _getImagePixels(ByteData pixels, int width, int height, {Rect? region}) sync* { final int rowStride = width * 4; int rowStart; int rowEnd; int colStart; int colEnd; if (region != null) { rowStart = region.top.floor(); rowEnd = region.bottom.floor(); colStart = region.left.floor(); colEnd = region.right.floor(); assert(rowStart >= 0); assert(rowEnd <= height); assert(colStart >= 0); assert(colEnd <= width); } else { rowStart = 0; rowEnd = height; colStart = 0; colEnd = width; } int byteCount = 0; for (int row = rowStart; row < rowEnd; ++row) { for (int col = colStart; col < colEnd; ++col) { final int position = row * rowStride + col * 4; // Convert from RGBA to ARGB. final int pixel = pixels.getUint32(position); final Color result = Color((pixel << 24) | (pixel >> 8)); byteCount += 4; yield result; } } assert(byteCount == ((rowEnd - rowStart) * (colEnd - colStart) * 4)); } bool _shouldIgnoreColor(Color color) { final HSLColor hslColor = HSLColor.fromColor(color); if (filters.isNotEmpty) { for (final PaletteFilter filter in filters) { if (!filter(hslColor)) { return true; } } } return false; } List<PaletteColor> _quantizeColors() { const int quantizeWordWidth = 5; const int quantizeChannelWidth = 8; const int quantizeShift = quantizeChannelWidth - quantizeWordWidth; const int quantizeWordMask = ((1 << quantizeWordWidth) - 1) << quantizeShift; Color quantizeColor(Color color) { return Color.fromARGB( color.alpha, color.red & quantizeWordMask, color.green & quantizeWordMask, color.blue & quantizeWordMask, ); } final List<PaletteColor> paletteColors = <PaletteColor>[]; final Iterable<Color> pixels = _getImagePixels( encodedImage.byteData, encodedImage.width, encodedImage.height, region: region, ); final _ColorHistogram hist = _ColorHistogram(); Color? currentColor; _ColorCount? currentColorCount; for (final Color pixel in pixels) { // Update the histogram, but only for non-zero alpha values, and for the // ones we do add, make their alphas opaque so that we can use a Color as // the histogram key. final Color quantizedColor = quantizeColor(pixel); final Color colorKey = quantizedColor.withAlpha(0xff); // Skip pixels that are entirely transparent. if (quantizedColor.alpha == 0x0) { continue; } if (currentColor != colorKey) { currentColor = colorKey; currentColorCount = hist[colorKey]; if (currentColorCount == null) { hist[colorKey] = currentColorCount = _ColorCount(); } } currentColorCount!.value = currentColorCount.value + 1; } // Now let's remove any colors that the filters want to ignore. hist.removeWhere((Color color) { return _shouldIgnoreColor(color); }); if (hist.length <= maxColors) { // The image has fewer colors than the maximum requested, so just return // the colors. paletteColors.clear(); for (final Color color in hist.keys) { paletteColors.add(PaletteColor(color, hist[color]!.value)); } } else { // We need use quantization to reduce the number of colors paletteColors.clear(); paletteColors.addAll(_quantizePixels(maxColors, hist)); } return paletteColors; } List<PaletteColor> _quantizePixels( int maxColors, _ColorHistogram histogram, ) { int volumeComparator(_ColorVolumeBox a, _ColorVolumeBox b) { return b.getVolume().compareTo(a.getVolume()); } // Create the priority queue which is sorted by volume descending. This // means we always split the largest box in the queue final PriorityQueue<_ColorVolumeBox> priorityQueue = HeapPriorityQueue<_ColorVolumeBox>(volumeComparator); // To start, offer a box which contains all of the colors priorityQueue.add(_ColorVolumeBox( 0, histogram.length - 1, histogram, histogram.keys.toList())); // Now go through the boxes, splitting them until we have reached maxColors // or there are no more boxes to split _splitBoxes(priorityQueue, maxColors); // Finally, return the average colors of the color boxes. return _generateAverageColors(priorityQueue); } // Iterate through the [PriorityQueue], popping [_ColorVolumeBox] objects // from the queue and splitting them. Once split, the new box and the // remaining box are offered back to the queue. // // The `maxSize` is the maximum number of boxes to split. void _splitBoxes(PriorityQueue<_ColorVolumeBox> queue, final int maxSize) { while (queue.length < maxSize) { final _ColorVolumeBox colorVolumeBox = queue.removeFirst(); if (colorVolumeBox.canSplit()) { // First split the box, and offer the result queue.add(colorVolumeBox.splitBox()); // Then offer the box back queue.add(colorVolumeBox); } else { // If we get here then there are no more boxes to split, so return return; } } } // Generates the average colors from each of the boxes in the queue. List<PaletteColor> _generateAverageColors( PriorityQueue<_ColorVolumeBox> colorVolumeBoxes) { final List<PaletteColor> colors = <PaletteColor>[]; for (final _ColorVolumeBox colorVolumeBox in colorVolumeBoxes.toList()) { final PaletteColor paletteColor = colorVolumeBox.getAverageColor(); if (!_shouldIgnoreColor(paletteColor.color)) { colors.add(paletteColor); } } return colors; } }
packages/packages/palette_generator/lib/palette_generator.dart/0
{ "file_path": "packages/packages/palette_generator/lib/palette_generator.dart", "repo_id": "packages", "token_count": 16153 }
1,045
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io'; import 'package:flutter_test/flutter_test.dart'; import 'package:path_provider_example/readme_excerpts.dart'; import 'package:path_provider_platform_interface/path_provider_platform_interface.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); setUpAll(() async { PathProviderPlatform.instance = FakePathProvider(); }); test('sanity check readmeSnippets', () async { // Ensure that the snippet code runs successfully. final List<Directory?> results = await readmeSnippets(); // It should demonstrate a couple of calls. expect(results.length, greaterThan(2)); // And the calls should all be different. expect(results.toSet().length, results.length); }); } class FakePathProvider extends PathProviderPlatform { @override Future<String?> getApplicationDocumentsPath() async { return 'docs'; } @override Future<String?> getDownloadsPath() async { return 'downloads'; } @override Future<String?> getTemporaryPath() async { return 'temp'; } }
packages/packages/path_provider/path_provider/example/test/readme_excerpts_test.dart/0
{ "file_path": "packages/packages/path_provider/path_provider/example/test/readme_excerpts_test.dart", "repo_id": "packages", "token_count": 380 }
1,046
// Copyright 2013 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. package io.flutter.plugins.pathprovider; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.os.Environment; /** Helps to map the Dart `StorageDirectory` enum to a Android system constant. */ class StorageDirectoryMapper { /** * Return a Android Environment constant for a Dart Index. * * @return The correct Android Environment constant or null, if the index is null. * @throws IllegalArgumentException If `dartIndex` is not null but also not matches any known * index. */ static String androidType(Integer dartIndex) throws IllegalArgumentException { if (dartIndex == null) { return null; } switch (dartIndex) { case 0: return Environment.DIRECTORY_MUSIC; case 1: return Environment.DIRECTORY_PODCASTS; case 2: return Environment.DIRECTORY_RINGTONES; case 3: return Environment.DIRECTORY_ALARMS; case 4: return Environment.DIRECTORY_NOTIFICATIONS; case 5: return Environment.DIRECTORY_PICTURES; case 6: return Environment.DIRECTORY_MOVIES; case 7: return Environment.DIRECTORY_DOWNLOADS; case 8: return Environment.DIRECTORY_DCIM; case 9: if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) { return Environment.DIRECTORY_DOCUMENTS; } else { throw new IllegalArgumentException("Documents directory is unsupported."); } default: throw new IllegalArgumentException("Unknown index: " + dartIndex); } } }
packages/packages/path_provider/path_provider_android/android/src/main/java/io/flutter/plugins/pathprovider/StorageDirectoryMapper.java/0
{ "file_path": "packages/packages/path_provider/path_provider_android/android/src/main/java/io/flutter/plugins/pathprovider/StorageDirectoryMapper.java", "repo_id": "packages", "token_count": 649 }
1,047
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>com.apple.security.application-groups</key> <array> <string>group.flutter.appGroupTest</string> </array> </dict> </plist>
packages/packages/path_provider/path_provider_foundation/example/ios/Runner/Runner.entitlements/0
{ "file_path": "packages/packages/path_provider/path_provider_foundation/example/ios/Runner/Runner.entitlements", "repo_id": "packages", "token_count": 130 }
1,048
// Copyright 2013 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:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:path_provider_linux/path_provider_linux.dart'; void main() { runApp(const MyApp()); } /// Sample app class MyApp extends StatefulWidget { /// Default Constructor const MyApp({super.key}); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { String? _tempDirectory = 'Unknown'; String? _downloadsDirectory = 'Unknown'; String? _appSupportDirectory = 'Unknown'; String? _appCacheDirectory = 'Unknown'; String? _documentsDirectory = 'Unknown'; final PathProviderLinux _provider = PathProviderLinux(); @override void initState() { super.initState(); initDirectories(); } // Platform messages are asynchronous, so we initialize in an async method. Future<void> initDirectories() async { String? tempDirectory; String? downloadsDirectory; String? appSupportDirectory; String? appCacheDirectory; String? documentsDirectory; // Platform messages may fail, so we use a try/catch PlatformException. try { tempDirectory = await _provider.getTemporaryPath(); } on PlatformException { tempDirectory = 'Failed to get temp directory.'; } try { downloadsDirectory = await _provider.getDownloadsPath(); } on PlatformException { downloadsDirectory = 'Failed to get downloads directory.'; } try { documentsDirectory = await _provider.getApplicationDocumentsPath(); } on PlatformException { documentsDirectory = 'Failed to get documents directory.'; } try { appSupportDirectory = await _provider.getApplicationSupportPath(); } on PlatformException { appSupportDirectory = 'Failed to get documents directory.'; } try { appCacheDirectory = await _provider.getApplicationCachePath(); } on PlatformException { appCacheDirectory = 'Failed to get cache directory.'; } // If the widget was removed from the tree while the asynchronous platform // message was in flight, we want to discard the reply rather than calling // setState to update our non-existent appearance. if (!mounted) { return; } setState(() { _tempDirectory = tempDirectory; _downloadsDirectory = downloadsDirectory; _appSupportDirectory = appSupportDirectory; _appCacheDirectory = appCacheDirectory; _documentsDirectory = documentsDirectory; }); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('Path Provider Linux example app'), ), body: Center( child: Column( children: <Widget>[ Text('Temp Directory: $_tempDirectory\n'), Text('Documents Directory: $_documentsDirectory\n'), Text('Downloads Directory: $_downloadsDirectory\n'), Text('Application Support Directory: $_appSupportDirectory\n'), Text('Application Cache Directory: $_appCacheDirectory\n'), ], ), ), ), ); } }
packages/packages/path_provider/path_provider_linux/example/lib/main.dart/0
{ "file_path": "packages/packages/path_provider/path_provider_linux/example/lib/main.dart", "repo_id": "packages", "token_count": 1129 }
1,049
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:ffi'; import 'package:ffi/ffi.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:path_provider_linux/src/get_application_id_real.dart'; class _FakeGioUtils implements GioUtils { int? application; Pointer<Utf8>? applicationId; @override bool libraryIsPresent = false; @override int gApplicationGetDefault() => application!; @override Pointer<Utf8> gApplicationGetApplicationId(int app) => applicationId!; } void main() { late _FakeGioUtils fakeGio; setUp(() { fakeGio = _FakeGioUtils(); gioUtilsOverride = fakeGio; }); tearDown(() { gioUtilsOverride = null; }); test('returns null if libgio is not available', () { expect(getApplicationId(), null); }); test('returns null if g_paplication_get_default returns 0', () { fakeGio.libraryIsPresent = true; fakeGio.application = 0; expect(getApplicationId(), null); }); test('returns null if g_application_get_application_id returns nullptr', () { fakeGio.libraryIsPresent = true; fakeGio.application = 1; fakeGio.applicationId = nullptr; expect(getApplicationId(), null); }); test('returns value if g_application_get_application_id returns a value', () { fakeGio.libraryIsPresent = true; fakeGio.application = 1; const String id = 'foo'; final Pointer<Utf8> idPtr = id.toNativeUtf8(); fakeGio.applicationId = idPtr; expect(getApplicationId(), id); calloc.free(idPtr); }); }
packages/packages/path_provider/path_provider_linux/test/get_application_id_test.dart/0
{ "file_path": "packages/packages/path_provider/path_provider_linux/test/get_application_id_test.dart", "repo_id": "packages", "token_count": 581 }
1,050
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:ffi'; import 'dart:io'; import 'package:flutter_test/flutter_test.dart'; import 'package:path_provider_platform_interface/path_provider_platform_interface.dart'; import 'package:path_provider_windows/path_provider_windows.dart'; import 'package:path_provider_windows/src/path_provider_windows_real.dart' show encodingCP1252, encodingUnicode, languageEn; // A fake VersionInfoQuerier that just returns preset responses. class FakeVersionInfoQuerier implements VersionInfoQuerier { FakeVersionInfoQuerier( this.responses, { this.language = languageEn, this.encoding = encodingUnicode, }); final String language; final String encoding; final Map<String, String> responses; // ignore: unreachable_from_main String? getStringValue( Pointer<Uint8>? versionInfo, String key, { required String language, required String encoding, }) { if (language == this.language && encoding == this.encoding) { return responses[key]; } else { return null; } } } void main() { test('registered instance', () { PathProviderWindows.registerWith(); expect(PathProviderPlatform.instance, isA<PathProviderWindows>()); }); test('getTemporaryPath', () async { final PathProviderWindows pathProvider = PathProviderWindows(); expect(await pathProvider.getTemporaryPath(), contains(r'C:\')); }, skip: !Platform.isWindows); test('getApplicationSupportPath with no version info', () async { final PathProviderWindows pathProvider = PathProviderWindows(); pathProvider.versionInfoQuerier = FakeVersionInfoQuerier(<String, String>{}); final String? path = await pathProvider.getApplicationSupportPath(); expect(path, contains(r'C:\')); expect(path, contains(r'AppData')); // The last path component should be the executable name. expect(path, endsWith(r'flutter_tester')); }, skip: !Platform.isWindows); test('getApplicationSupportPath with full version info in CP1252', () async { final PathProviderWindows pathProvider = PathProviderWindows(); pathProvider.versionInfoQuerier = FakeVersionInfoQuerier(<String, String>{ 'CompanyName': 'A Company', 'ProductName': 'Amazing App', }, encoding: encodingCP1252); final String? path = await pathProvider.getApplicationSupportPath(); expect(path, isNotNull); if (path != null) { expect(path, endsWith(r'AppData\Roaming\A Company\Amazing App')); expect(Directory(path).existsSync(), isTrue); } }, skip: !Platform.isWindows); test('getApplicationSupportPath with full version info in Unicode', () async { final PathProviderWindows pathProvider = PathProviderWindows(); pathProvider.versionInfoQuerier = FakeVersionInfoQuerier(<String, String>{ 'CompanyName': 'A Company', 'ProductName': 'Amazing App', }); final String? path = await pathProvider.getApplicationSupportPath(); expect(path, isNotNull); if (path != null) { expect(path, endsWith(r'AppData\Roaming\A Company\Amazing App')); expect(Directory(path).existsSync(), isTrue); } }, skip: !Platform.isWindows); test( 'getApplicationSupportPath with full version info in Unsupported Encoding', () async { final PathProviderWindows pathProvider = PathProviderWindows(); pathProvider.versionInfoQuerier = FakeVersionInfoQuerier(<String, String>{ 'CompanyName': 'A Company', 'ProductName': 'Amazing App', }, language: '0000', encoding: '0000'); final String? path = await pathProvider.getApplicationSupportPath(); expect(path, contains(r'C:\')); expect(path, contains(r'AppData')); // The last path component should be the executable name. expect(path, endsWith(r'flutter_tester')); }, skip: !Platform.isWindows); test('getApplicationSupportPath with missing company', () async { final PathProviderWindows pathProvider = PathProviderWindows(); pathProvider.versionInfoQuerier = FakeVersionInfoQuerier(<String, String>{ 'ProductName': 'Amazing App', }); final String? path = await pathProvider.getApplicationSupportPath(); expect(path, isNotNull); if (path != null) { expect(path, endsWith(r'AppData\Roaming\Amazing App')); expect(Directory(path).existsSync(), isTrue); } }, skip: !Platform.isWindows); test('getApplicationSupportPath with problematic values', () async { final PathProviderWindows pathProvider = PathProviderWindows(); pathProvider.versionInfoQuerier = FakeVersionInfoQuerier(<String, String>{ 'CompanyName': r'A <Bad> Company: Name.', 'ProductName': r'A"/Terrible\|App?*Name', }); final String? path = await pathProvider.getApplicationSupportPath(); expect(path, isNotNull); if (path != null) { expect( path, endsWith( r'AppData\Roaming\A _Bad_ Company_ Name\A__Terrible__App__Name')); expect(Directory(path).existsSync(), isTrue); } }, skip: !Platform.isWindows); test('getApplicationSupportPath with a completely invalid company', () async { final PathProviderWindows pathProvider = PathProviderWindows(); pathProvider.versionInfoQuerier = FakeVersionInfoQuerier(<String, String>{ 'CompanyName': r'..', 'ProductName': r'Amazing App', }); final String? path = await pathProvider.getApplicationSupportPath(); expect(path, isNotNull); if (path != null) { expect(path, endsWith(r'AppData\Roaming\Amazing App')); expect(Directory(path).existsSync(), isTrue); } }, skip: !Platform.isWindows); test('getApplicationSupportPath with very long app name', () async { final PathProviderWindows pathProvider = PathProviderWindows(); final String truncatedName = 'A' * 255; pathProvider.versionInfoQuerier = FakeVersionInfoQuerier(<String, String>{ 'CompanyName': 'A Company', 'ProductName': truncatedName * 2, }); final String? path = await pathProvider.getApplicationSupportPath(); expect(path, endsWith('\\$truncatedName')); // The directory won't exist, since it's longer than MAXPATH, so don't check // that here. }, skip: !Platform.isWindows); test('getApplicationDocumentsPath', () async { final PathProviderWindows pathProvider = PathProviderWindows(); final String? path = await pathProvider.getApplicationDocumentsPath(); expect(path, contains(r'C:\')); expect(path, contains(r'Documents')); }, skip: !Platform.isWindows); test('getApplicationCachePath', () async { final PathProviderWindows pathProvider = PathProviderWindows(); pathProvider.versionInfoQuerier = FakeVersionInfoQuerier(<String, String>{ 'CompanyName': 'A Company', 'ProductName': 'Amazing App', }, encoding: encodingCP1252); final String? path = await pathProvider.getApplicationCachePath(); expect(path, isNotNull); if (path != null) { expect(path, endsWith(r'AppData\Local\A Company\Amazing App')); expect(Directory(path).existsSync(), isTrue); } }, skip: !Platform.isWindows); test('getDownloadsPath', () async { final PathProviderWindows pathProvider = PathProviderWindows(); final String? path = await pathProvider.getDownloadsPath(); expect(path, contains(r'C:\')); expect(path, contains(r'Downloads')); }, skip: !Platform.isWindows); }
packages/packages/path_provider/path_provider_windows/test/path_provider_windows_test.dart/0
{ "file_path": "packages/packages/path_provider/path_provider_windows/test/path_provider_windows_test.dart", "repo_id": "packages", "token_count": 2450 }
1,051
# This file tracks properties of this Flutter project. # Used by Flutter tool to assess capabilities and perform upgrades etc. # # This file should be version controlled. version: revision: 4d9e56e694b656610ab87fcf2efbcd226e0ed8cf channel: stable project_type: app # Tracks metadata for the flutter migrate command migration: platforms: - platform: root create_revision: 4d9e56e694b656610ab87fcf2efbcd226e0ed8cf base_revision: 4d9e56e694b656610ab87fcf2efbcd226e0ed8cf - platform: android create_revision: 4d9e56e694b656610ab87fcf2efbcd226e0ed8cf base_revision: 4d9e56e694b656610ab87fcf2efbcd226e0ed8cf - platform: ios create_revision: 4d9e56e694b656610ab87fcf2efbcd226e0ed8cf base_revision: 4d9e56e694b656610ab87fcf2efbcd226e0ed8cf - platform: linux create_revision: 4d9e56e694b656610ab87fcf2efbcd226e0ed8cf base_revision: 4d9e56e694b656610ab87fcf2efbcd226e0ed8cf - platform: macos create_revision: 4d9e56e694b656610ab87fcf2efbcd226e0ed8cf base_revision: 4d9e56e694b656610ab87fcf2efbcd226e0ed8cf - platform: web create_revision: 4d9e56e694b656610ab87fcf2efbcd226e0ed8cf base_revision: 4d9e56e694b656610ab87fcf2efbcd226e0ed8cf - platform: windows create_revision: 4d9e56e694b656610ab87fcf2efbcd226e0ed8cf base_revision: 4d9e56e694b656610ab87fcf2efbcd226e0ed8cf # User provided section # List of Local paths (relative to this file) that should be # ignored by the migrate tool. # # Files that are not part of the templates will be ignored by default. unmanaged_files: - 'lib/main.dart' - 'ios/Runner.xcodeproj/project.pbxproj'
packages/packages/pigeon/example/app/.metadata/0
{ "file_path": "packages/packages/pigeon/example/app/.metadata", "repo_id": "packages", "token_count": 758 }
1,052
// Copyright 2013 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 'ast.dart'; import 'functional.dart'; import 'generator.dart'; import 'generator_tools.dart'; import 'pigeon_lib.dart' show TaskQueueType; /// Documentation open symbol. const String _docCommentPrefix = '/**'; /// Documentation continuation symbol. const String _docCommentContinuation = ' *'; /// Documentation close symbol. const String _docCommentSuffix = ' */'; /// Documentation comment spec. const DocumentCommentSpecification _docCommentSpec = DocumentCommentSpecification( _docCommentPrefix, closeCommentToken: _docCommentSuffix, blockContinuationToken: _docCommentContinuation, ); /// The standard codec for Flutter, used for any non custom codecs and extended for custom codecs. const String _standardMessageCodec = 'StandardMessageCodec'; /// Options that control how Java code will be generated. class JavaOptions { /// Creates a [JavaOptions] object const JavaOptions({ this.className, this.package, this.copyrightHeader, this.useGeneratedAnnotation, }); /// The name of the class that will house all the generated classes. final String? className; /// The package where the generated class will live. final String? package; /// A copyright header that will get prepended to generated code. final Iterable<String>? copyrightHeader; /// Determines if the `javax.annotation.Generated` is used in the output. This /// is false by default since that dependency isn't available in plugins by /// default . final bool? useGeneratedAnnotation; /// Creates a [JavaOptions] from a Map representation where: /// `x = JavaOptions.fromMap(x.toMap())`. static JavaOptions fromMap(Map<String, Object> map) { final Iterable<dynamic>? copyrightHeader = map['copyrightHeader'] as Iterable<dynamic>?; return JavaOptions( className: map['className'] as String?, package: map['package'] as String?, copyrightHeader: copyrightHeader?.cast<String>(), useGeneratedAnnotation: map['useGeneratedAnnotation'] as bool?, ); } /// Converts a [JavaOptions] to a Map representation where: /// `x = JavaOptions.fromMap(x.toMap())`. Map<String, Object> toMap() { final Map<String, Object> result = <String, Object>{ if (className != null) 'className': className!, if (package != null) 'package': package!, if (copyrightHeader != null) 'copyrightHeader': copyrightHeader!, if (useGeneratedAnnotation != null) 'useGeneratedAnnotation': useGeneratedAnnotation!, }; return result; } /// Overrides any non-null parameters from [options] into this to make a new /// [JavaOptions]. JavaOptions merge(JavaOptions options) { return JavaOptions.fromMap(mergeMaps(toMap(), options.toMap())); } } /// Class that manages all Java code generation. class JavaGenerator extends StructuredGenerator<JavaOptions> { /// Instantiates a Java Generator. const JavaGenerator(); @override void writeFilePrologue( JavaOptions generatorOptions, Root root, Indent indent, { required String dartPackageName, }) { if (generatorOptions.copyrightHeader != null) { addLines(indent, generatorOptions.copyrightHeader!, linePrefix: '// '); } indent.writeln('// ${getGeneratedCodeWarning()}'); indent.writeln('// $seeAlsoWarning'); indent.newln(); } @override void writeFileImports( JavaOptions generatorOptions, Root root, Indent indent, { required String dartPackageName, }) { if (generatorOptions.package != null) { indent.writeln('package ${generatorOptions.package};'); indent.newln(); } if (root.classes.isNotEmpty) { indent.writeln('import static java.lang.annotation.ElementType.METHOD;'); indent .writeln('import static java.lang.annotation.RetentionPolicy.CLASS;'); indent.newln(); } indent.writeln('import android.util.Log;'); indent.writeln('import androidx.annotation.NonNull;'); indent.writeln('import androidx.annotation.Nullable;'); indent.writeln('import io.flutter.plugin.common.BasicMessageChannel;'); indent.writeln('import io.flutter.plugin.common.BinaryMessenger;'); indent.writeln('import io.flutter.plugin.common.MessageCodec;'); indent.writeln('import io.flutter.plugin.common.StandardMessageCodec;'); indent.writeln('import java.io.ByteArrayOutputStream;'); if (root.classes.isNotEmpty) { indent.writeln('import java.lang.annotation.Retention;'); indent.writeln('import java.lang.annotation.Target;'); } indent.writeln('import java.nio.ByteBuffer;'); indent.writeln('import java.util.ArrayList;'); indent.writeln('import java.util.Arrays;'); indent.writeln('import java.util.Collections;'); indent.writeln('import java.util.HashMap;'); indent.writeln('import java.util.List;'); indent.writeln('import java.util.Map;'); indent.newln(); } @override void writeOpenNamespace( JavaOptions generatorOptions, Root root, Indent indent, { required String dartPackageName, }) { indent.writeln( '$_docCommentPrefix Generated class from Pigeon.$_docCommentSuffix'); indent.writeln( '@SuppressWarnings({"unused", "unchecked", "CodeBlock2Expr", "RedundantSuppression", "serial"})'); if (generatorOptions.useGeneratedAnnotation ?? false) { indent.writeln('@javax.annotation.Generated("dev.flutter.pigeon")'); } indent.writeln('public class ${generatorOptions.className!} {'); indent.inc(); } @override void writeEnum( JavaOptions generatorOptions, Root root, Indent indent, Enum anEnum, { required String dartPackageName, }) { String camelToSnake(String camelCase) { final RegExp regex = RegExp('([a-z])([A-Z]+)'); return camelCase .replaceAllMapped(regex, (Match m) => '${m[1]}_${m[2]}') .toUpperCase(); } indent.newln(); addDocumentationComments( indent, anEnum.documentationComments, _docCommentSpec); indent.write('public enum ${anEnum.name} '); indent.addScoped('{', '}', () { enumerate(anEnum.members, (int index, final EnumMember member) { addDocumentationComments( indent, member.documentationComments, _docCommentSpec); indent.writeln( '${camelToSnake(member.name)}($index)${index == anEnum.members.length - 1 ? ';' : ','}'); }); indent.newln(); // This uses default access (package-private), because private causes // SyntheticAccessor warnings in the serialization code. indent.writeln('final int index;'); indent.newln(); indent.write('private ${anEnum.name}(final int index) '); indent.addScoped('{', '}', () { indent.writeln('this.index = index;'); }); }); } @override void writeDataClass( JavaOptions generatorOptions, Root root, Indent indent, Class classDefinition, { required String dartPackageName, }) { const List<String> generatedMessages = <String>[ ' Generated class from Pigeon that represents data sent in messages.' ]; indent.newln(); addDocumentationComments( indent, classDefinition.documentationComments, _docCommentSpec, generatorComments: generatedMessages); indent.write('public static final class ${classDefinition.name} '); indent.addScoped('{', '}', () { for (final NamedType field in getFieldsInSerializationOrder(classDefinition)) { _writeClassField(generatorOptions, root, indent, field); indent.newln(); } if (getFieldsInSerializationOrder(classDefinition) .map((NamedType e) => !e.type.isNullable) .any((bool e) => e)) { indent.writeln( '$_docCommentPrefix Constructor is non-public to enforce null safety; use Builder.$_docCommentSuffix'); indent.writeln('${classDefinition.name}() {}'); indent.newln(); } _writeClassBuilder(generatorOptions, root, indent, classDefinition); writeClassEncode( generatorOptions, root, indent, classDefinition, dartPackageName: dartPackageName, ); writeClassDecode( generatorOptions, root, indent, classDefinition, dartPackageName: dartPackageName, ); }); } void _writeClassField( JavaOptions generatorOptions, Root root, Indent indent, NamedType field) { final HostDatatype hostDatatype = getFieldHostDatatype( field, (TypeDeclaration x) => _javaTypeForBuiltinDartType(x)); final String nullability = field.type.isNullable ? '@Nullable' : '@NonNull'; addDocumentationComments( indent, field.documentationComments, _docCommentSpec); indent.writeln( 'private $nullability ${hostDatatype.datatype} ${field.name};'); indent.newln(); indent.write( 'public $nullability ${hostDatatype.datatype} ${_makeGetter(field)}() '); indent.addScoped('{', '}', () { indent.writeln('return ${field.name};'); }); indent.newln(); indent.writeScoped( 'public void ${_makeSetter(field)}($nullability ${hostDatatype.datatype} setterArg) {', '}', () { if (!field.type.isNullable) { indent.writeScoped('if (setterArg == null) {', '}', () { indent.writeln( 'throw new IllegalStateException("Nonnull field \\"${field.name}\\" is null.");'); }); } indent.writeln('this.${field.name} = setterArg;'); }); } void _writeClassBuilder( JavaOptions generatorOptions, Root root, Indent indent, Class classDefinition, ) { indent.write('public static final class Builder '); indent.addScoped('{', '}', () { for (final NamedType field in getFieldsInSerializationOrder(classDefinition)) { final HostDatatype hostDatatype = getFieldHostDatatype( field, (TypeDeclaration x) => _javaTypeForBuiltinDartType(x)); final String nullability = field.type.isNullable ? '@Nullable' : '@NonNull'; indent.newln(); indent.writeln( 'private @Nullable ${hostDatatype.datatype} ${field.name};'); indent.newln(); indent.writeln('@CanIgnoreReturnValue'); indent.writeScoped( 'public @NonNull Builder ${_makeSetter(field)}($nullability ${hostDatatype.datatype} setterArg) {', '}', () { indent.writeln('this.${field.name} = setterArg;'); indent.writeln('return this;'); }); } indent.newln(); indent.write('public @NonNull ${classDefinition.name} build() '); indent.addScoped('{', '}', () { const String returnVal = 'pigeonReturn'; indent.writeln( '${classDefinition.name} $returnVal = new ${classDefinition.name}();'); for (final NamedType field in getFieldsInSerializationOrder(classDefinition)) { indent.writeln('$returnVal.${_makeSetter(field)}(${field.name});'); } indent.writeln('return $returnVal;'); }); }); } @override void writeClassEncode( JavaOptions generatorOptions, Root root, Indent indent, Class classDefinition, { required String dartPackageName, }) { indent.newln(); indent.writeln('@NonNull'); indent.write('ArrayList<Object> toList() '); indent.addScoped('{', '}', () { indent.writeln( 'ArrayList<Object> toListResult = new ArrayList<Object>(${classDefinition.fields.length});'); for (final NamedType field in getFieldsInSerializationOrder(classDefinition)) { String toWriteValue = ''; final String fieldName = field.name; if (field.type.isClass) { toWriteValue = '($fieldName == null) ? null : $fieldName.toList()'; } else if (field.type.isEnum) { toWriteValue = '$fieldName == null ? null : $fieldName.index'; } else { toWriteValue = field.name; } indent.writeln('toListResult.add($toWriteValue);'); } indent.writeln('return toListResult;'); }); } @override void writeClassDecode( JavaOptions generatorOptions, Root root, Indent indent, Class classDefinition, { required String dartPackageName, }) { indent.newln(); indent.write( 'static @NonNull ${classDefinition.name} fromList(@NonNull ArrayList<Object> list) '); indent.addScoped('{', '}', () { const String result = 'pigeonResult'; indent.writeln( '${classDefinition.name} $result = new ${classDefinition.name}();'); enumerate(getFieldsInSerializationOrder(classDefinition), (int index, final NamedType field) { final String fieldVariable = field.name; final String setter = _makeSetter(field); indent.writeln('Object $fieldVariable = list.get($index);'); if (field.type.isEnum) { indent.writeln( '$result.$setter(${_intToEnum(fieldVariable, field.type.baseName, field.type.isNullable)});'); } else { indent.writeln( '$result.$setter(${_castObject(field, fieldVariable)});'); } }); indent.writeln('return $result;'); }); } /// Writes the code for a flutter [Api], [api]. /// Example: /// public static final class Foo { /// public Foo(BinaryMessenger argBinaryMessenger) {...} /// public interface Result<T> { /// void reply(T reply); /// } /// public int add(int x, int y, Result<int> result) {...} /// } @override void writeFlutterApi( JavaOptions generatorOptions, Root root, Indent indent, AstFlutterApi api, { required String dartPackageName, }) { /// Returns an argument name that can be used in a context where it is possible to collide /// and append `.index` to enums. String getEnumSafeArgumentExpression(int count, NamedType argument) { if (argument.type.isEnum) { return argument.type.isNullable ? '${_getArgumentName(count, argument)}Arg == null ? null : ${_getArgumentName(count, argument)}Arg.index' : '${_getArgumentName(count, argument)}Arg.index'; } return '${_getArgumentName(count, argument)}Arg'; } if (getCodecClasses(api, root).isNotEmpty) { _writeCodec(indent, api, root); } const List<String> generatedMessages = <String>[ ' Generated class from Pigeon that represents Flutter messages that can be called from Java.' ]; addDocumentationComments(indent, api.documentationComments, _docCommentSpec, generatorComments: generatedMessages); indent.write('public static class ${api.name} '); indent.addScoped('{', '}', () { indent.writeln('private final @NonNull BinaryMessenger binaryMessenger;'); indent.newln(); indent.write( 'public ${api.name}(@NonNull BinaryMessenger argBinaryMessenger) '); indent.addScoped('{', '}', () { indent.writeln('this.binaryMessenger = argBinaryMessenger;'); }); indent.newln(); indent.writeln('/** Public interface for sending reply. */ '); final String codecName = _getCodecName(api); indent.writeln('/** The codec used by ${api.name}. */'); indent.write('static @NonNull MessageCodec<Object> getCodec() '); indent.addScoped('{', '}', () { indent.write('return '); if (getCodecClasses(api, root).isNotEmpty) { indent.addln('$codecName.INSTANCE;'); } else { indent.addln('new $_standardMessageCodec();'); } }); for (final Method func in api.methods) { final String resultType = _getResultType(func.returnType); final String returnType = func.returnType.isVoid ? 'Void' : _javaTypeForDartType(func.returnType); String sendArgument; addDocumentationComments( indent, func.documentationComments, _docCommentSpec); if (func.parameters.isEmpty) { indent .write('public void ${func.name}(@NonNull $resultType result) '); sendArgument = 'null'; } else { final Iterable<String> argTypes = func.parameters .map((NamedType e) => _nullsafeJavaTypeForDartType(e.type)); final Iterable<String> argNames = indexMap(func.parameters, _getSafeArgumentName); final Iterable<String> enumSafeArgNames = indexMap(func.parameters, getEnumSafeArgumentExpression); if (func.parameters.length == 1) { sendArgument = 'new ArrayList<Object>(Collections.singletonList(${enumSafeArgNames.first}))'; } else { sendArgument = 'new ArrayList<Object>(Arrays.asList(${enumSafeArgNames.join(', ')}))'; } final String argsSignature = map2(argTypes, argNames, (String x, String y) => '$x $y') .join(', '); indent.write( 'public void ${func.name}($argsSignature, @NonNull $resultType result) '); } indent.addScoped('{', '}', () { const String channel = 'channel'; indent.writeln( 'final String channelName = "${makeChannelName(api, func, dartPackageName)}";'); indent.writeln('BasicMessageChannel<Object> $channel ='); indent.nest(2, () { indent.writeln('new BasicMessageChannel<>('); indent.nest(2, () { indent.writeln('binaryMessenger, channelName, getCodec());'); }); }); indent.writeln('$channel.send('); indent.nest(2, () { indent.writeln('$sendArgument,'); indent.write('channelReply -> '); indent.addScoped('{', '});', () { indent.writeScoped('if (channelReply instanceof List) {', '} ', () { indent.writeln( 'List<Object> listReply = (List<Object>) channelReply;'); indent.writeScoped('if (listReply.size() > 1) {', '} ', () { indent.writeln( 'result.error(new FlutterError((String) listReply.get(0), (String) listReply.get(1), (String) listReply.get(2)));'); }, addTrailingNewline: false); if (!func.returnType.isNullable && !func.returnType.isVoid) { indent.addScoped('else if (listReply.get(0) == null) {', '} ', () { indent.writeln( 'result.error(new FlutterError("null-error", "Flutter api returned null value for non-null return value.", ""));'); }, addTrailingNewline: false); } indent.addScoped('else {', '}', () { if (func.returnType.isVoid) { indent.writeln('result.success();'); } else { const String output = 'output'; final String outputExpression; indent.writeln('@SuppressWarnings("ConstantConditions")'); if (func.returnType.baseName == 'int') { outputExpression = 'listReply.get(0) == null ? null : ((Number) listReply.get(0)).longValue();'; } else if (func.returnType.isEnum) { if (func.returnType.isNullable) { outputExpression = 'listReply.get(0) == null ? null : $returnType.values()[(int) listReply.get(0)];'; } else { outputExpression = '$returnType.values()[(int) listReply.get(0)];'; } } else { outputExpression = '${_cast('listReply.get(0)', javaType: returnType)};'; } indent.writeln('$returnType $output = $outputExpression'); indent.writeln('result.success($output);'); } }); }, addTrailingNewline: false); indent.addScoped(' else {', '} ', () { indent.writeln( 'result.error(createConnectionError(channelName));'); }); }); }); }); } }); } @override void writeApis( JavaOptions generatorOptions, Root root, Indent indent, { required String dartPackageName, }) { if (root.apis.any((Api api) => api is AstHostApi && api.methods.any((Method it) => it.isAsynchronous) || api is AstFlutterApi)) { indent.newln(); _writeResultInterfaces(indent); } super.writeApis(generatorOptions, root, indent, dartPackageName: dartPackageName); } /// Write the java code that represents a host [Api], [api]. /// Example: /// public interface Foo { /// int add(int x, int y); /// static void setUp(BinaryMessenger binaryMessenger, Foo api) {...} /// } @override void writeHostApi( JavaOptions generatorOptions, Root root, Indent indent, AstHostApi api, { required String dartPackageName, }) { if (getCodecClasses(api, root).isNotEmpty) { _writeCodec(indent, api, root); } const List<String> generatedMessages = <String>[ ' Generated interface from Pigeon that represents a handler of messages from Flutter.' ]; addDocumentationComments(indent, api.documentationComments, _docCommentSpec, generatorComments: generatedMessages); indent.write('public interface ${api.name} '); indent.addScoped('{', '}', () { for (final Method method in api.methods) { _writeInterfaceMethod(generatorOptions, root, indent, api, method); } indent.newln(); final String codecName = _getCodecName(api); indent.writeln('/** The codec used by ${api.name}. */'); indent.write('static @NonNull MessageCodec<Object> getCodec() '); indent.addScoped('{', '}', () { indent.write('return '); if (getCodecClasses(api, root).isNotEmpty) { indent.addln('$codecName.INSTANCE;'); } else { indent.addln('new $_standardMessageCodec();'); } }); indent.writeln( '${_docCommentPrefix}Sets up an instance of `${api.name}` to handle messages through the `binaryMessenger`.$_docCommentSuffix'); indent.write( 'static void setUp(@NonNull BinaryMessenger binaryMessenger, @Nullable ${api.name} api) '); indent.addScoped('{', '}', () { for (final Method method in api.methods) { _writeMethodSetUp( generatorOptions, root, indent, api, method, dartPackageName: dartPackageName, ); } }); }); } /// Write a method in the interface. /// Example: /// int add(int x, int y); void _writeInterfaceMethod(JavaOptions generatorOptions, Root root, Indent indent, Api api, final Method method) { final String resultType = _getResultType(method.returnType); final String nullableType = method.isAsynchronous ? '' : _nullabilityAnnotationFromType(method.returnType); final String returnType = method.isAsynchronous ? 'void' : _javaTypeForDartType(method.returnType); final List<String> argSignature = <String>[]; if (method.parameters.isNotEmpty) { final Iterable<String> argTypes = method.parameters .map((NamedType e) => _nullsafeJavaTypeForDartType(e.type)); final Iterable<String> argNames = method.parameters.map((NamedType e) => e.name); argSignature .addAll(map2(argTypes, argNames, (String argType, String argName) { return '$argType $argName'; })); } if (method.isAsynchronous) { argSignature.add('@NonNull $resultType result'); } if (method.documentationComments.isNotEmpty) { addDocumentationComments( indent, method.documentationComments, _docCommentSpec); } else { indent.newln(); } if (nullableType != '') { indent.writeln(nullableType); } indent.writeln('$returnType ${method.name}(${argSignature.join(', ')});'); } /// Write a static setUp function in the interface. /// Example: /// static void setUp(BinaryMessenger binaryMessenger, Foo api) {...} void _writeMethodSetUp( JavaOptions generatorOptions, Root root, Indent indent, Api api, final Method method, { required String dartPackageName, }) { final String channelName = makeChannelName(api, method, dartPackageName); indent.write(''); indent.addScoped('{', '}', () { String? taskQueue; if (method.taskQueueType != TaskQueueType.serial) { taskQueue = 'taskQueue'; indent.writeln( 'BinaryMessenger.TaskQueue taskQueue = binaryMessenger.makeBackgroundTaskQueue();'); } indent.writeln('BasicMessageChannel<Object> channel ='); indent.nest(2, () { indent.writeln('new BasicMessageChannel<>('); indent.nest(2, () { indent.write('binaryMessenger, "$channelName", getCodec()'); if (taskQueue != null) { indent.addln(', $taskQueue);'); } else { indent.addln(');'); } }); }); indent.write('if (api != null) '); indent.addScoped('{', '} else {', () { indent.writeln('channel.setMessageHandler('); indent.nest(2, () { indent.write('(message, reply) -> '); indent.addScoped('{', '});', () { String enumTag = ''; final String returnType = method.returnType.isVoid ? 'Void' : _javaTypeForDartType(method.returnType); indent.writeln( 'ArrayList<Object> wrapped = new ArrayList<Object>();'); final List<String> methodArgument = <String>[]; if (method.parameters.isNotEmpty) { indent.writeln( 'ArrayList<Object> args = (ArrayList<Object>) message;'); enumerate(method.parameters, (int index, NamedType arg) { // The StandardMessageCodec can give us [Integer, Long] for // a Dart 'int'. To keep things simple we just use 64bit // longs in Pigeon with Java. final bool isInt = arg.type.baseName == 'int'; final String argType = isInt ? 'Number' : _javaTypeForDartType(arg.type); final String argName = _getSafeArgumentName(index, arg); final String argExpression = isInt ? '($argName == null) ? null : $argName.longValue()' : argName; String accessor = 'args.get($index)'; if (arg.type.isEnum) { accessor = _intToEnum( accessor, arg.type.baseName, arg.type.isNullable); } else if (argType != 'Object') { accessor = _cast(accessor, javaType: argType); } indent.writeln('$argType $argName = $accessor;'); methodArgument.add(argExpression); }); } if (method.isAsynchronous) { final String resultValue = method.returnType.isVoid ? 'null' : 'result'; if (method.returnType.isEnum) { enumTag = method.returnType.isNullable ? ' == null ? null : $resultValue.index' : '.index'; } final String resultType = _getResultType(method.returnType); final String resultParam = method.returnType.isVoid ? '' : '$returnType result'; final String addResultArg = method.returnType.isVoid ? 'null' : '$resultValue$enumTag'; const String resultName = 'resultCallback'; indent.format(''' $resultType $resultName = \t\tnew $resultType() { \t\t\tpublic void success($resultParam) { \t\t\t\twrapped.add(0, $addResultArg); \t\t\t\treply.reply(wrapped); \t\t\t} \t\t\tpublic void error(Throwable error) { \t\t\t\tArrayList<Object> wrappedError = wrapError(error); \t\t\t\treply.reply(wrappedError); \t\t\t} \t\t}; '''); methodArgument.add(resultName); } final String call = 'api.${method.name}(${methodArgument.join(', ')})'; if (method.isAsynchronous) { indent.writeln('$call;'); } else { indent.write('try '); indent.addScoped('{', '}', () { if (method.returnType.isVoid) { indent.writeln('$call;'); indent.writeln('wrapped.add(0, null);'); } else { if (method.returnType.isEnum) { enumTag = method.returnType.isNullable ? ' == null ? null : output.index' : '.index'; } indent.writeln('$returnType output = $call;'); indent.writeln('wrapped.add(0, output$enumTag);'); } }); indent.add(' catch (Throwable exception) '); indent.addScoped('{', '}', () { indent.writeln( 'ArrayList<Object> wrappedError = wrapError(exception);'); if (method.isAsynchronous) { indent.writeln('reply.reply(wrappedError);'); } else { indent.writeln('wrapped = wrappedError;'); } }); indent.writeln('reply.reply(wrapped);'); } }); }); }); indent.addScoped(null, '}', () { indent.writeln('channel.setMessageHandler(null);'); }); }); } /// Writes the codec class that will be used by [api]. /// Example: /// private static class FooCodec extends StandardMessageCodec {...} void _writeCodec(Indent indent, Api api, Root root) { assert(getCodecClasses(api, root).isNotEmpty); final Iterable<EnumeratedClass> codecClasses = getCodecClasses(api, root); final String codecName = _getCodecName(api); indent.newln(); indent.write( 'private static class $codecName extends $_standardMessageCodec '); indent.addScoped('{', '}', () { indent.writeln( 'public static final $codecName INSTANCE = new $codecName();'); indent.newln(); indent.writeln('private $codecName() {}'); indent.newln(); indent.writeln('@Override'); indent.write( 'protected Object readValueOfType(byte type, @NonNull ByteBuffer buffer) '); indent.addScoped('{', '}', () { indent.write('switch (type) '); indent.addScoped('{', '}', () { for (final EnumeratedClass customClass in codecClasses) { indent.writeln('case (byte) ${customClass.enumeration}:'); indent.nest(1, () { indent.writeln( 'return ${customClass.name}.fromList((ArrayList<Object>) readValue(buffer));'); }); } indent.writeln('default:'); indent.nest(1, () { indent.writeln('return super.readValueOfType(type, buffer);'); }); }); }); indent.newln(); indent.writeln('@Override'); indent.write( 'protected void writeValue(@NonNull ByteArrayOutputStream stream, Object value) '); indent.addScoped('{', '}', () { bool firstClass = true; for (final EnumeratedClass customClass in codecClasses) { if (firstClass) { indent.write(''); firstClass = false; } indent.add('if (value instanceof ${customClass.name}) '); indent.addScoped('{', '} else ', () { indent.writeln('stream.write(${customClass.enumeration});'); indent.writeln( 'writeValue(stream, ((${customClass.name}) value).toList());'); }, addTrailingNewline: false); } indent.addScoped('{', '}', () { indent.writeln('super.writeValue(stream, value);'); }); }); }); indent.newln(); } void _writeResultInterfaces(Indent indent) { indent.writeln( '/** Asynchronous error handling return type for non-nullable API method returns. */'); indent.write('public interface Result<T> '); indent.addScoped('{', '}', () { indent .writeln('/** Success case callback method for handling returns. */'); indent.writeln('void success(@NonNull T result);'); indent.newln(); indent .writeln('/** Failure case callback method for handling errors. */'); indent.writeln('void error(@NonNull Throwable error);'); }); indent.writeln( '/** Asynchronous error handling return type for nullable API method returns. */'); indent.write('public interface NullableResult<T> '); indent.addScoped('{', '}', () { indent .writeln('/** Success case callback method for handling returns. */'); indent.writeln('void success(@Nullable T result);'); indent.newln(); indent .writeln('/** Failure case callback method for handling errors. */'); indent.writeln('void error(@NonNull Throwable error);'); }); indent.writeln( '/** Asynchronous error handling return type for void API method returns. */'); indent.write('public interface VoidResult '); indent.addScoped('{', '}', () { indent .writeln('/** Success case callback method for handling returns. */'); indent.writeln('void success();'); indent.newln(); indent .writeln('/** Failure case callback method for handling errors. */'); indent.writeln('void error(@NonNull Throwable error);'); }); } void _writeErrorClass(Indent indent) { indent.writeln( '/** Error class for passing custom error details to Flutter via a thrown PlatformException. */'); indent.write('public static class FlutterError extends RuntimeException '); indent.addScoped('{', '}', () { indent.newln(); indent.writeln('/** The error code. */'); indent.writeln('public final String code;'); indent.newln(); indent.writeln( '/** The error details. Must be a datatype supported by the api codec. */'); indent.writeln('public final Object details;'); indent.newln(); indent.writeln( 'public FlutterError(@NonNull String code, @Nullable String message, @Nullable Object details) '); indent.writeScoped('{', '}', () { indent.writeln('super(message);'); indent.writeln('this.code = code;'); indent.writeln('this.details = details;'); }); }); } void _writeWrapError(Indent indent) { indent.format(''' @NonNull protected static ArrayList<Object> wrapError(@NonNull Throwable exception) { \tArrayList<Object> errorList = new ArrayList<Object>(3); \tif (exception instanceof FlutterError) { \t\tFlutterError error = (FlutterError) exception; \t\terrorList.add(error.code); \t\terrorList.add(error.getMessage()); \t\terrorList.add(error.details); \t} else { \t\terrorList.add(exception.toString()); \t\terrorList.add(exception.getClass().getSimpleName()); \t\terrorList.add( \t\t\t"Cause: " + exception.getCause() + ", Stacktrace: " + Log.getStackTraceString(exception)); \t} \treturn errorList; }'''); } void _writeCreateConnectionError(Indent indent) { indent.writeln('@NonNull'); indent.writeScoped( 'protected static FlutterError createConnectionError(@NonNull String channelName) {', '}', () { indent.writeln( 'return new FlutterError("channel-error", "Unable to establish connection on channel: " + channelName + ".", "");'); }); } // We are emitting our own definition of [@CanIgnoreReturnValue] to support // clients who use CheckReturnValue, without having to force Pigeon clients // to take a new dependency on error_prone_annotations. void _writeCanIgnoreReturnValueAnnotation( JavaOptions opt, Root root, Indent indent) { indent.newln(); indent.writeln('@Target(METHOD)'); indent.writeln('@Retention(CLASS)'); indent.writeln('@interface CanIgnoreReturnValue {}'); } @override void writeGeneralUtilities( JavaOptions generatorOptions, Root root, Indent indent, { required String dartPackageName, }) { final bool hasHostApi = root.apis .whereType<AstHostApi>() .any((Api api) => api.methods.isNotEmpty); final bool hasFlutterApi = root.apis .whereType<AstFlutterApi>() .any((Api api) => api.methods.isNotEmpty); indent.newln(); _writeErrorClass(indent); if (hasHostApi) { indent.newln(); _writeWrapError(indent); } if (hasFlutterApi) { indent.newln(); _writeCreateConnectionError(indent); } if (root.classes.isNotEmpty) { _writeCanIgnoreReturnValueAnnotation(generatorOptions, root, indent); } } @override void writeCloseNamespace( JavaOptions generatorOptions, Root root, Indent indent, { required String dartPackageName, }) { indent.dec(); indent.addln('}'); } } /// Calculates the name of the codec that will be generated for [api]. String _getCodecName(Api api) => '${api.name}Codec'; /// Converts an expression that evaluates to an nullable int to an expression /// that evaluates to a nullable enum. String _intToEnum(String expression, String enumName, bool nullable) => nullable ? '$expression == null ? null : $enumName.values()[(int) $expression]' : '$enumName.values()[(int) $expression]'; String _getArgumentName(int count, NamedType argument) => argument.name.isEmpty ? 'arg$count' : argument.name; /// Returns an argument name that can be used in a context where it is possible to collide. String _getSafeArgumentName(int count, NamedType argument) => '${_getArgumentName(count, argument)}Arg'; String _makeGetter(NamedType field) { final String uppercased = field.name.substring(0, 1).toUpperCase() + field.name.substring(1); return 'get$uppercased'; } String _makeSetter(NamedType field) { final String uppercased = field.name.substring(0, 1).toUpperCase() + field.name.substring(1); return 'set$uppercased'; } /// Converts a [List] of [TypeDeclaration]s to a comma separated [String] to be /// used in Java code. String _flattenTypeArguments(List<TypeDeclaration> args) { return args.map<String>(_javaTypeForDartType).join(', '); } String _javaTypeForBuiltinGenericDartType( TypeDeclaration type, int numberTypeArguments, ) { if (type.typeArguments.isEmpty) { return '${type.baseName}<${repeat('Object', numberTypeArguments).join(', ')}>'; } else { return '${type.baseName}<${_flattenTypeArguments(type.typeArguments)}>'; } } String? _javaTypeForBuiltinDartType(TypeDeclaration type) { const Map<String, String> javaTypeForDartTypeMap = <String, String>{ 'bool': 'Boolean', 'int': 'Long', 'String': 'String', 'double': 'Double', 'Uint8List': 'byte[]', 'Int32List': 'int[]', 'Int64List': 'long[]', 'Float64List': 'double[]', 'Object': 'Object', }; if (javaTypeForDartTypeMap.containsKey(type.baseName)) { return javaTypeForDartTypeMap[type.baseName]; } else if (type.baseName == 'List') { return _javaTypeForBuiltinGenericDartType(type, 1); } else if (type.baseName == 'Map') { return _javaTypeForBuiltinGenericDartType(type, 2); } else { return null; } } String _javaTypeForDartType(TypeDeclaration type) { return _javaTypeForBuiltinDartType(type) ?? type.baseName; } String _nullabilityAnnotationFromType(TypeDeclaration type) { return type.isVoid ? '' : (type.isNullable ? '@Nullable ' : '@NonNull '); } String _nullsafeJavaTypeForDartType(TypeDeclaration type) { final String nullSafe = _nullabilityAnnotationFromType(type); return '$nullSafe${_javaTypeForDartType(type)}'; } /// Returns an expression to cast [variable] to [javaType]. String _cast(String variable, {required String javaType}) { // Special-case Object, since casting to Object doesn't do anything, and // causes a warning. return javaType == 'Object' ? variable : '($javaType) $variable'; } /// Casts variable named [varName] to the correct host datatype for [field]. /// This is for use in codecs where we may have a map representation of an /// object. String _castObject(NamedType field, String varName) { final HostDatatype hostDatatype = getFieldHostDatatype( field, (TypeDeclaration x) => _javaTypeForBuiltinDartType(x)); if (field.type.baseName == 'int') { return '($varName == null) ? null : (($varName instanceof Integer) ? (Integer) $varName : (${hostDatatype.datatype}) $varName)'; } else if (field.type.isClass) { return '($varName == null) ? null : ${hostDatatype.datatype}.fromList((ArrayList<Object>) $varName)'; } else { return _cast(varName, javaType: hostDatatype.datatype); } } /// Returns string of Result class type for method based on [TypeDeclaration]. String _getResultType(TypeDeclaration type) { if (type.isVoid) { return 'VoidResult'; } if (type.isNullable) { return 'NullableResult<${_javaTypeForDartType(type)}>'; } return 'Result<${_javaTypeForDartType(type)}>'; }
packages/packages/pigeon/lib/java_generator.dart/0
{ "file_path": "packages/packages/pigeon/lib/java_generator.dart", "repo_id": "packages", "token_count": 17316 }
1,053
// Copyright 2013 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. // This file is an example pigeon file that is used in compilation, unit, mock // handler, and e2e tests. import 'package:pigeon/pigeon.dart'; class NullFieldsSearchRequest { NullFieldsSearchRequest(this.query, this.identifier); String? query; // The following non-null field was added to reproduce // https://github.com/flutter/flutter/issues/104871 int identifier; } enum NullFieldsSearchReplyType { success, failure, } class NullFieldsSearchReply { NullFieldsSearchReply( this.result, this.error, this.indices, this.request, this.type, ); String? result; String? error; List<int?>? indices; NullFieldsSearchRequest? request; NullFieldsSearchReplyType? type; } @HostApi() abstract class NullFieldsHostApi { NullFieldsSearchReply search(NullFieldsSearchRequest nested); } @FlutterApi() abstract class NullFieldsFlutterApi { NullFieldsSearchReply search(NullFieldsSearchRequest request); }
packages/packages/pigeon/pigeons/null_fields.dart/0
{ "file_path": "packages/packages/pigeon/pigeons/null_fields.dart", "repo_id": "packages", "token_count": 359 }
1,054
// Copyright 2013 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. package com.example.alternate_language_test_plugin; import static org.junit.Assert.*; import static org.mockito.Mockito.*; import androidx.annotation.NonNull; import com.example.alternate_language_test_plugin.CoreTests.*; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.MessageCodec; import java.nio.ByteBuffer; import java.util.ArrayList; import org.junit.Test; import org.mockito.ArgumentCaptor; public class AsyncTest { class Success implements HostSmallApi { @Override public void echo(@NonNull String value, Result<String> result) { result.success(value); } @Override public void voidVoid(VoidResult result) { result.success(); } } class Error implements HostSmallApi { @Override public void echo(@NonNull String value, Result<String> result) { result.error(new Exception("error")); } @Override public void voidVoid(VoidResult result) { result.error(new Exception("error")); } } @Test public void asyncSuccess() { Success api = new Success(); BinaryMessenger binaryMessenger = mock(BinaryMessenger.class); HostSmallApi.setUp(binaryMessenger, api); ArgumentCaptor<BinaryMessenger.BinaryMessageHandler> handler = ArgumentCaptor.forClass(BinaryMessenger.BinaryMessageHandler.class); verify(binaryMessenger) .setMessageHandler( eq("dev.flutter.pigeon.pigeon_integration_tests.HostSmallApi.echo"), any()); verify(binaryMessenger) .setMessageHandler( eq("dev.flutter.pigeon.pigeon_integration_tests.HostSmallApi.voidVoid"), handler.capture()); MessageCodec<Object> codec = HostSmallApi.getCodec(); ByteBuffer message = codec.encodeMessage(null); Boolean[] didCall = {false}; handler .getValue() .onMessage( message, (bytes) -> { bytes.rewind(); @SuppressWarnings("unchecked") ArrayList<Object> wrapped = (ArrayList<Object>) codec.decodeMessage(bytes); assertTrue(wrapped.size() == 1); didCall[0] = true; }); assertTrue(didCall[0]); } @Test public void asyncError() { Error api = new Error(); BinaryMessenger binaryMessenger = mock(BinaryMessenger.class); HostSmallApi.setUp(binaryMessenger, api); ArgumentCaptor<BinaryMessenger.BinaryMessageHandler> handler = ArgumentCaptor.forClass(BinaryMessenger.BinaryMessageHandler.class); verify(binaryMessenger) .setMessageHandler( eq("dev.flutter.pigeon.pigeon_integration_tests.HostSmallApi.echo"), any()); verify(binaryMessenger) .setMessageHandler( eq("dev.flutter.pigeon.pigeon_integration_tests.HostSmallApi.voidVoid"), handler.capture()); MessageCodec<Object> codec = HostSmallApi.getCodec(); ByteBuffer message = codec.encodeMessage(null); Boolean[] didCall = {false}; handler .getValue() .onMessage( message, (bytes) -> { bytes.rewind(); @SuppressWarnings("unchecked") ArrayList<Object> wrapped = (ArrayList<Object>) codec.decodeMessage(bytes); assertTrue(wrapped.size() > 1); assertEquals("java.lang.Exception: error", (String) wrapped.get(0)); didCall[0] = true; }); assertTrue(didCall[0]); } }
packages/packages/pigeon/platform_tests/alternate_language_test_plugin/android/src/test/java/com/example/alternate_language_test_plugin/AsyncTest.java/0
{ "file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/android/src/test/java/com/example/alternate_language_test_plugin/AsyncTest.java", "repo_id": "packages", "token_count": 1459 }
1,055
// Copyright 2013 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 Flutter; @import XCTest; @import alternate_language_test_plugin; #import "HandlerBinaryMessenger.h" /////////////////////////////////////////////////////////////////////////////////////////// @interface MultipleAritytest : XCTestCase @end /////////////////////////////////////////////////////////////////////////////////////////// @implementation MultipleAritytest - (void)testSimple { HandlerBinaryMessenger *binaryMessenger = [[HandlerBinaryMessenger alloc] initWithCodec:MultipleArityHostApiGetCodec() handler:^id _Nullable(NSArray *_Nonnull args) { return @[ @([args[0] intValue] - [args[1] intValue]) ]; }]; MultipleArityFlutterApi *api = [[MultipleArityFlutterApi alloc] initWithBinaryMessenger:binaryMessenger]; XCTestExpectation *expectation = [self expectationWithDescription:@"subtraction"]; [api subtractX:30 y:10 completion:^(NSNumber *_Nonnull result, FlutterError *_Nullable error) { XCTAssertNil(error); XCTAssertEqual(20, result.intValue); [expectation fulfill]; }]; [self waitForExpectations:@[ expectation ] timeout:30.0]; } @end
packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/MultipleArityTest.m/0
{ "file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/MultipleArityTest.m", "repo_id": "packages", "token_count": 452 }
1,056
// Copyright 2013 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 "AlternateLanguageTestPlugin.h" #import "CoreTests.gen.h" @interface AlternateLanguageTestPlugin () @property(nonatomic) FlutterIntegrationCoreApi *flutterAPI; @end /// This plugin handles the native side of the integration tests in example/integration_test/. @implementation AlternateLanguageTestPlugin + (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar { AlternateLanguageTestPlugin *plugin = [[AlternateLanguageTestPlugin alloc] init]; SetUpHostIntegrationCoreApi(registrar.messenger, plugin); plugin.flutterAPI = [[FlutterIntegrationCoreApi alloc] initWithBinaryMessenger:registrar.messenger]; } #pragma mark HostIntegrationCoreApi implementation - (void)noopWithError:(FlutterError *_Nullable *_Nonnull)error { } - (nullable AllTypes *)echoAllTypes:(AllTypes *)everything error:(FlutterError *_Nullable *_Nonnull)error { return everything; } - (nullable AllNullableTypes *)echoAllNullableTypes:(nullable AllNullableTypes *)everything error:(FlutterError *_Nullable *_Nonnull)error { return everything; } - (nullable id)throwErrorWithError:(FlutterError *_Nullable *_Nonnull)error { *error = [FlutterError errorWithCode:@"An error" message:nil details:nil]; return nil; } - (void)throwErrorFromVoidWithError:(FlutterError *_Nullable *_Nonnull)error { *error = [FlutterError errorWithCode:@"An error" message:nil details:nil]; } - (nullable id)throwFlutterErrorWithError:(FlutterError *_Nullable *_Nonnull)error { *error = [FlutterError errorWithCode:@"code" message:@"message" details:@"details"]; return nil; } - (nullable NSNumber *)echoInt:(NSInteger)anInt error:(FlutterError *_Nullable *_Nonnull)error { return @(anInt); } - (nullable NSNumber *)echoDouble:(double)aDouble error:(FlutterError *_Nullable *_Nonnull)error { return @(aDouble); } - (nullable NSNumber *)echoBool:(BOOL)aBool error:(FlutterError *_Nullable *_Nonnull)error { return @(aBool); } - (nullable NSString *)echoString:(NSString *)aString error:(FlutterError *_Nullable *_Nonnull)error { return aString; } - (nullable FlutterStandardTypedData *)echoUint8List:(FlutterStandardTypedData *)aUint8List error:(FlutterError *_Nullable *_Nonnull)error { return aUint8List; } - (nullable id)echoObject:(id)anObject error:(FlutterError *_Nullable *_Nonnull)error { return anObject; } - (nullable NSArray<id> *)echoList:(NSArray<id> *)aList error:(FlutterError *_Nullable *_Nonnull)error { return aList; } - (nullable NSDictionary<NSString *, id> *)echoMap:(NSDictionary<NSString *, id> *)aMap error:(FlutterError *_Nullable *_Nonnull)error { return aMap; } - (nullable AllClassesWrapper *)echoClassWrapper:(AllClassesWrapper *)wrapper error:(FlutterError *_Nullable *_Nonnull)error { return wrapper; } - (AnEnumBox *_Nullable)echoEnum:(AnEnum)anEnum error:(FlutterError *_Nullable *_Nonnull)error { return [[AnEnumBox alloc] initWithValue:anEnum]; } - (nullable NSString *)echoNamedDefaultString:(NSString *)aString error:(FlutterError *_Nullable *_Nonnull)error { return aString; } - (nullable NSNumber *)echoOptionalDefaultDouble:(double)aDouble error:(FlutterError *_Nullable *_Nonnull)error { return @(aDouble); } - (nullable NSNumber *)echoRequiredInt:(NSInteger)anInt error:(FlutterError *_Nullable *_Nonnull)error { return @(anInt); } - (nullable NSString *)extractNestedNullableStringFrom:(AllClassesWrapper *)wrapper error:(FlutterError *_Nullable *_Nonnull)error { return wrapper.allNullableTypes.aNullableString; } - (nullable AllClassesWrapper *) createNestedObjectWithNullableString:(nullable NSString *)nullableString error:(FlutterError *_Nullable *_Nonnull)error { AllNullableTypes *innerObject = [[AllNullableTypes alloc] init]; innerObject.aNullableString = nullableString; return [AllClassesWrapper makeWithAllNullableTypes:innerObject allTypes:nil]; } - (nullable AllNullableTypes *)sendMultipleNullableTypesABool:(nullable NSNumber *)aNullableBool anInt:(nullable NSNumber *)aNullableInt aString:(nullable NSString *)aNullableString error:(FlutterError *_Nullable *_Nonnull) error { AllNullableTypes *someTypes = [[AllNullableTypes alloc] init]; someTypes.aNullableBool = aNullableBool; someTypes.aNullableInt = aNullableInt; someTypes.aNullableString = aNullableString; return someTypes; } - (nullable NSNumber *)echoNullableInt:(nullable NSNumber *)aNullableInt error:(FlutterError *_Nullable *_Nonnull)error { return aNullableInt; } - (nullable NSNumber *)echoNullableDouble:(nullable NSNumber *)aNullableDouble error:(FlutterError *_Nullable *_Nonnull)error { return aNullableDouble; } - (nullable NSNumber *)echoNullableBool:(nullable NSNumber *)aNullableBool error:(FlutterError *_Nullable *_Nonnull)error { return aNullableBool; } - (nullable NSString *)echoNullableString:(nullable NSString *)aNullableString error:(FlutterError *_Nullable *_Nonnull)error { return aNullableString; } - (nullable FlutterStandardTypedData *) echoNullableUint8List:(nullable FlutterStandardTypedData *)aNullableUint8List error:(FlutterError *_Nullable *_Nonnull)error { return aNullableUint8List; } - (nullable id)echoNullableObject:(nullable id)aNullableObject error:(FlutterError *_Nullable *_Nonnull)error { return aNullableObject; } - (nullable NSArray<id> *)echoNullableList:(nullable NSArray<id> *)aNullableList error:(FlutterError *_Nullable *_Nonnull)error { return aNullableList; } - (nullable NSDictionary<NSString *, id> *) echoNullableMap:(nullable NSDictionary<NSString *, id> *)aNullableMap error:(FlutterError *_Nullable *_Nonnull)error { return aNullableMap; } - (AnEnumBox *_Nullable)echoNullableEnum:(nullable AnEnumBox *)AnEnumBoxed error:(FlutterError *_Nullable *_Nonnull)error { return AnEnumBoxed; } - (nullable NSNumber *)echoOptionalNullableInt:(nullable NSNumber *)aNullableInt error:(FlutterError *_Nullable *_Nonnull)error { return aNullableInt; } - (nullable NSString *)echoNamedNullableString:(nullable NSString *)aNullableString error:(FlutterError *_Nullable *_Nonnull)error { return aNullableString; } - (void)noopAsyncWithCompletion:(void (^)(FlutterError *_Nullable))completion { completion(nil); } - (void)throwAsyncErrorWithCompletion:(void (^)(id _Nullable, FlutterError *_Nullable))completion { completion(nil, [FlutterError errorWithCode:@"An error" message:nil details:nil]); } - (void)throwAsyncErrorFromVoidWithCompletion:(void (^)(FlutterError *_Nullable))completion { completion([FlutterError errorWithCode:@"An error" message:nil details:nil]); } - (void)throwAsyncFlutterErrorWithCompletion:(void (^)(id _Nullable, FlutterError *_Nullable))completion { completion(nil, [FlutterError errorWithCode:@"code" message:@"message" details:@"details"]); } - (void)echoAsyncAllTypes:(AllTypes *)everything completion:(void (^)(AllTypes *_Nullable, FlutterError *_Nullable))completion { completion(everything, nil); } - (void)echoAsyncNullableAllNullableTypes:(nullable AllNullableTypes *)everything completion:(void (^)(AllNullableTypes *_Nullable, FlutterError *_Nullable))completion { completion(everything, nil); } - (void)echoAsyncInt:(NSInteger)anInt completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion { completion(@(anInt), nil); } - (void)echoAsyncDouble:(double)aDouble completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion { completion(@(aDouble), nil); } - (void)echoAsyncBool:(BOOL)aBool completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion { completion(@(aBool), nil); } - (void)echoAsyncString:(NSString *)aString completion:(void (^)(NSString *_Nullable, FlutterError *_Nullable))completion { completion(aString, nil); } - (void)echoAsyncUint8List:(FlutterStandardTypedData *)aUint8List completion:(void (^)(FlutterStandardTypedData *_Nullable, FlutterError *_Nullable))completion { completion(aUint8List, nil); } - (void)echoAsyncObject:(id)anObject completion:(void (^)(id _Nullable, FlutterError *_Nullable))completion { completion(anObject, nil); } - (void)echoAsyncList:(NSArray<id> *)aList completion:(void (^)(NSArray<id> *_Nullable, FlutterError *_Nullable))completion { completion(aList, nil); } - (void)echoAsyncMap:(NSDictionary<NSString *, id> *)aMap completion:(void (^)(NSDictionary<NSString *, id> *_Nullable, FlutterError *_Nullable))completion { completion(aMap, nil); } - (void)echoAsyncEnum:(AnEnum)anEnum completion:(void (^)(AnEnumBox *_Nullable, FlutterError *_Nullable))completion { completion([[AnEnumBox alloc] initWithValue:anEnum], nil); } - (void)echoAsyncNullableInt:(nullable NSNumber *)anInt completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion { completion(anInt, nil); } - (void)echoAsyncNullableDouble:(nullable NSNumber *)aDouble completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion { completion(aDouble, nil); } - (void)echoAsyncNullableBool:(nullable NSNumber *)aBool completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion { completion(aBool, nil); } - (void)echoAsyncNullableString:(nullable NSString *)aString completion:(void (^)(NSString *_Nullable, FlutterError *_Nullable))completion { completion(aString, nil); } - (void)echoAsyncNullableUint8List:(nullable FlutterStandardTypedData *)aUint8List completion:(void (^)(FlutterStandardTypedData *_Nullable, FlutterError *_Nullable))completion { completion(aUint8List, nil); } - (void)echoAsyncNullableObject:(nullable id)anObject completion:(void (^)(id _Nullable, FlutterError *_Nullable))completion { completion(anObject, nil); } - (void)echoAsyncNullableList:(nullable NSArray<id> *)aList completion: (void (^)(NSArray<id> *_Nullable, FlutterError *_Nullable))completion { completion(aList, nil); } - (void)echoAsyncNullableMap:(nullable NSDictionary<NSString *, id> *)aMap completion:(void (^)(NSDictionary<NSString *, id> *_Nullable, FlutterError *_Nullable))completion { completion(aMap, nil); } - (void)echoAsyncNullableEnum:(nullable AnEnumBox *)AnEnumBoxed completion:(void (^)(AnEnumBox *_Nullable, FlutterError *_Nullable))completion { completion(AnEnumBoxed, nil); } - (void)callFlutterNoopWithCompletion:(void (^)(FlutterError *_Nullable))completion { [self.flutterAPI noopWithCompletion:^(FlutterError *error) { completion(error); }]; } - (void)callFlutterThrowErrorWithCompletion:(void (^)(id _Nullable, FlutterError *_Nullable))completion { [self.flutterAPI throwErrorWithCompletion:^(id value, FlutterError *error) { completion(value, error); }]; } - (void)callFlutterThrowErrorFromVoidWithCompletion:(void (^)(FlutterError *_Nullable))completion { [self.flutterAPI throwErrorFromVoidWithCompletion:^(FlutterError *error) { completion(error); }]; } - (void)callFlutterEchoAllTypes:(AllTypes *)everything completion:(void (^)(AllTypes *_Nullable, FlutterError *_Nullable))completion { [self.flutterAPI echoAllTypes:everything completion:^(AllTypes *value, FlutterError *error) { completion(value, error); }]; } - (void)callFlutterSendMultipleNullableTypesABool:(nullable NSNumber *)aNullableBool anInt:(nullable NSNumber *)aNullableInt aString:(nullable NSString *)aNullableString completion:(void (^)(AllNullableTypes *_Nullable, FlutterError *_Nullable))completion { [self.flutterAPI sendMultipleNullableTypesABool:aNullableBool anInt:aNullableInt aString:aNullableString completion:^(AllNullableTypes *value, FlutterError *error) { completion(value, error); }]; } - (void)callFlutterEchoBool:(BOOL)aBool completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion { [self.flutterAPI echoBool:aBool completion:^(NSNumber *value, FlutterError *error) { completion(value, error); }]; } - (void)callFlutterEchoInt:(NSInteger)anInt completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion { [self.flutterAPI echoInt:anInt completion:^(NSNumber *value, FlutterError *error) { completion(value, error); }]; } - (void)callFlutterEchoDouble:(double)aDouble completion:(void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion { [self.flutterAPI echoDouble:aDouble completion:^(NSNumber *value, FlutterError *error) { completion(value, error); }]; } - (void)callFlutterEchoString:(NSString *)aString completion:(void (^)(NSString *_Nullable, FlutterError *_Nullable))completion { [self.flutterAPI echoString:aString completion:^(NSString *value, FlutterError *error) { completion(value, error); }]; } - (void)callFlutterEchoUint8List:(FlutterStandardTypedData *)aList completion:(void (^)(FlutterStandardTypedData *_Nullable, FlutterError *_Nullable))completion { [self.flutterAPI echoUint8List:aList completion:^(FlutterStandardTypedData *value, FlutterError *error) { completion(value, error); }]; } - (void)callFlutterEchoList:(NSArray<id> *)aList completion:(void (^)(NSArray<id> *_Nullable, FlutterError *_Nullable))completion { [self.flutterAPI echoList:aList completion:^(NSArray<id> *value, FlutterError *error) { completion(value, error); }]; } - (void)callFlutterEchoMap:(NSDictionary<NSString *, id> *)aMap completion:(void (^)(NSDictionary<NSString *, id> *_Nullable, FlutterError *_Nullable))completion { [self.flutterAPI echoMap:aMap completion:^(NSDictionary<NSString *, id> *value, FlutterError *error) { completion(value, error); }]; } - (void)callFlutterEchoEnum:(AnEnum)anEnum completion:(void (^)(AnEnumBox *_Nullable, FlutterError *_Nullable))completion { [self.flutterAPI echoEnum:anEnum completion:^(AnEnumBox *value, FlutterError *error) { completion(value, error); }]; } - (void)callFlutterEchoAllNullableTypes:(nullable AllNullableTypes *)everything completion:(void (^)(AllNullableTypes *_Nullable, FlutterError *_Nullable))completion { [self.flutterAPI echoAllNullableTypes:everything completion:^(AllNullableTypes *value, FlutterError *error) { completion(value, error); }]; } - (void)callFlutterEchoNullableBool:(nullable NSNumber *)aBool completion: (void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion { [self.flutterAPI echoNullableBool:aBool completion:^(NSNumber *value, FlutterError *error) { completion(value, error); }]; } - (void)callFlutterEchoNullableInt:(nullable NSNumber *)anInt completion: (void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion { [self.flutterAPI echoNullableInt:anInt completion:^(NSNumber *value, FlutterError *error) { completion(value, error); }]; } - (void)callFlutterEchoNullableDouble:(nullable NSNumber *)aDouble completion: (void (^)(NSNumber *_Nullable, FlutterError *_Nullable))completion { [self.flutterAPI echoNullableDouble:aDouble completion:^(NSNumber *value, FlutterError *error) { completion(value, error); }]; } - (void)callFlutterEchoNullableString:(nullable NSString *)aString completion: (void (^)(NSString *_Nullable, FlutterError *_Nullable))completion { [self.flutterAPI echoNullableString:aString completion:^(NSString *value, FlutterError *error) { completion(value, error); }]; } - (void)callFlutterEchoNullableUint8List:(nullable FlutterStandardTypedData *)aList completion:(void (^)(FlutterStandardTypedData *_Nullable, FlutterError *_Nullable))completion { [self.flutterAPI echoNullableUint8List:aList completion:^(FlutterStandardTypedData *value, FlutterError *error) { completion(value, error); }]; } - (void)callFlutterEchoNullableList:(nullable NSArray<id> *)aList completion: (void (^)(NSArray<id> *_Nullable, FlutterError *_Nullable))completion { [self.flutterAPI echoNullableList:aList completion:^(NSArray<id> *value, FlutterError *error) { completion(value, error); }]; } - (void)callFlutterEchoNullableMap:(nullable NSDictionary<NSString *, id> *)aMap completion:(void (^)(NSDictionary<NSString *, id> *_Nullable, FlutterError *_Nullable))completion { [self.flutterAPI echoNullableMap:aMap completion:^(NSDictionary<NSString *, id> *value, FlutterError *error) { completion(value, error); }]; } - (void)callFlutterEchoNullableEnum:(nullable AnEnumBox *)AnEnumBoxed completion: (void (^)(AnEnumBox *_Nullable, FlutterError *_Nullable))completion { [self.flutterAPI echoNullableEnum:AnEnumBoxed completion:^(AnEnumBox *value, FlutterError *error) { completion(value, error); }]; } @end
packages/packages/pigeon/platform_tests/alternate_language_test_plugin/macos/Classes/AlternateLanguageTestPlugin.m/0
{ "file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/macos/Classes/AlternateLanguageTestPlugin.m", "repo_id": "packages", "token_count": 9607 }
1,057
// Copyright 2013 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. // // Autogenerated from Pigeon, do not edit directly. // See also: https://pub.dev/packages/pigeon // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import, no_leading_underscores_for_local_identifiers import 'dart:async'; import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; import 'package:flutter/services.dart'; PlatformException _createConnectionError(String channelName) { return PlatformException( code: 'channel-error', message: 'Unable to establish connection on channel: "$channelName".', ); } List<Object?> wrapResponse( {Object? result, PlatformException? error, bool empty = false}) { if (empty) { return <Object?>[]; } if (error == null) { return <Object?>[result]; } return <Object?>[error.code, error.message, error.details]; } class MultipleArityHostApi { /// Constructor for [MultipleArityHostApi]. The [binaryMessenger] named argument is /// available for dependency injection. If it is left null, the default /// BinaryMessenger will be used which routes to the host platform. MultipleArityHostApi({BinaryMessenger? binaryMessenger}) : __pigeon_binaryMessenger = binaryMessenger; final BinaryMessenger? __pigeon_binaryMessenger; static const MessageCodec<Object?> pigeonChannelCodec = StandardMessageCodec(); Future<int> subtract(int x, int y) async { const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.MultipleArityHostApi.subtract'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[x, y]) as List<Object?>?; if (__pigeon_replyList == null) { throw _createConnectionError(__pigeon_channelName); } else if (__pigeon_replyList.length > 1) { throw PlatformException( code: __pigeon_replyList[0]! as String, message: __pigeon_replyList[1] as String?, details: __pigeon_replyList[2], ); } else if (__pigeon_replyList[0] == null) { throw PlatformException( code: 'null-error', message: 'Host platform returned null value for non-null return value.', ); } else { return (__pigeon_replyList[0] as int?)!; } } } abstract class MultipleArityFlutterApi { static const MessageCodec<Object?> pigeonChannelCodec = StandardMessageCodec(); int subtract(int x, int y); static void setup(MultipleArityFlutterApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.MultipleArityFlutterApi.subtract', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (api == null) { __pigeon_channel.setMessageHandler(null); } else { __pigeon_channel.setMessageHandler((Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MultipleArityFlutterApi.subtract was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_x = (args[0] as int?); assert(arg_x != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MultipleArityFlutterApi.subtract was null, expected non-null int.'); final int? arg_y = (args[1] as int?); assert(arg_y != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.MultipleArityFlutterApi.subtract was null, expected non-null int.'); try { final int output = api.subtract(arg_x!, arg_y!); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } } }
packages/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/multiple_arity.gen.dart/0
{ "file_path": "packages/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/multiple_arity.gen.dart", "repo_id": "packages", "token_count": 1766 }
1,058
// Copyright 2013 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:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:shared_test_plugin_code/src/generated/primitive.gen.dart'; import 'primitive_test.mocks.dart'; import 'test_util.dart'; @GenerateMocks(<Type>[BinaryMessenger, PrimitiveFlutterApi]) void main() { test('test anInt', () async { final BinaryMessenger mockMessenger = MockBinaryMessenger(); echoOneArgument( mockMessenger, 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.anInt', PrimitiveHostApi.pigeonChannelCodec, ); final PrimitiveHostApi api = PrimitiveHostApi(binaryMessenger: mockMessenger); final int result = await api.anInt(1); expect(result, 1); }); test('test List<bool>', () async { final BinaryMessenger mockMessenger = MockBinaryMessenger(); echoOneArgument( mockMessenger, 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aBoolList', PrimitiveHostApi.pigeonChannelCodec, ); final PrimitiveHostApi api = PrimitiveHostApi(binaryMessenger: mockMessenger); final List<bool?> result = await api.aBoolList(<bool?>[true]); expect(result[0], true); }); test('test List<bool> flutterapi', () async { final BinaryMessenger mockMessenger = MockBinaryMessenger(); final PrimitiveFlutterApi api = MockPrimitiveFlutterApi(); when(api.aBoolList(<bool?>[true, false])).thenReturn(<bool?>[]); when(mockMessenger.setMessageHandler( 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aBoolList', any)) .thenAnswer((Invocation realInvocation) { final MessageHandler? handler = realInvocation.positionalArguments[1] as MessageHandler?; handler!(PrimitiveFlutterApi.pigeonChannelCodec.encodeMessage(<Object?>[ <Object?>[true, false] ])); }); PrimitiveFlutterApi.setup(api, binaryMessenger: mockMessenger); verify(api.aBoolList(<bool?>[true, false])); }); test('test Map<String?, int?>', () async { final BinaryMessenger mockMessenger = MockBinaryMessenger(); echoOneArgument( mockMessenger, 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aStringIntMap', PrimitiveHostApi.pigeonChannelCodec, ); final PrimitiveHostApi api = PrimitiveHostApi(binaryMessenger: mockMessenger); final Map<String?, int?> result = await api.aStringIntMap(<String?, int?>{'hello': 1}); expect(result['hello'], 1); }); }
packages/packages/pigeon/platform_tests/shared_test_plugin_code/test/primitive_test.dart/0
{ "file_path": "packages/packages/pigeon/platform_tests/shared_test_plugin_code/test/primitive_test.dart", "repo_id": "packages", "token_count": 1066 }
1,059
// Copyright 2013 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. package com.example.test_plugin import io.flutter.plugin.common.BinaryMessenger import io.flutter.plugin.common.MessageCodec import java.nio.ByteBuffer import java.util.ArrayList internal class EchoBinaryMessenger(private val codec: MessageCodec<Any?>) : BinaryMessenger { override fun send(channel: String, message: ByteBuffer?) { // Method not implemented because this messenger is just for echoing. } override fun send(channel: String, message: ByteBuffer?, callback: BinaryMessenger.BinaryReply?) { message?.rewind() val args = codec.decodeMessage(message) as ArrayList<*> val replyData = codec.encodeMessage(args) replyData?.position(0) callback?.reply(replyData) } override fun setMessageHandler(channel: String, handler: BinaryMessenger.BinaryMessageHandler?) { // Method not implemented because this messenger is just for echoing. } }
packages/packages/pigeon/platform_tests/test_plugin/android/src/test/kotlin/com/example/test_plugin/EchoBinaryMessenger.kt/0
{ "file_path": "packages/packages/pigeon/platform_tests/test_plugin/android/src/test/kotlin/com/example/test_plugin/EchoBinaryMessenger.kt", "repo_id": "packages", "token_count": 304 }
1,060
// Copyright 2013 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 Foundation func equals(_ x: Any?, _ y: Any?) -> Bool { if x == nil, y == nil { return true } guard let x = x as? AnyHashable, let y = y as? AnyHashable else { return false } return x == y } func equalsList(_ x: [Any?]?, _ y: [Any?]?) -> Bool { if x == nil, y == nil { return true } guard x?.count == y?.count else { return false } guard let x = x, let y = y else { return false } return (0..<x.count).allSatisfy { equals(x[$0], y[$0]) } } func equalsDictionary(_ x: [AnyHashable: Any?]?, _ y: [AnyHashable: Any?]?) -> Bool { if x == nil, y == nil { return true } guard x?.count == y?.count else { return false } guard let x = x, let y = y else { return false } return x.allSatisfy { equals($0.value, y[$0.key] as Any?) } }
packages/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/Utils.swift/0
{ "file_path": "packages/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/Utils.swift", "repo_id": "packages", "token_count": 347 }
1,061
// Copyright 2013 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. // // Autogenerated from Pigeon, do not edit directly. // See also: https://pub.dev/packages/pigeon #undef _HAS_EXCEPTIONS #include "core_tests.gen.h" #include <flutter/basic_message_channel.h> #include <flutter/binary_messenger.h> #include <flutter/encodable_value.h> #include <flutter/standard_message_codec.h> #include <map> #include <optional> #include <string> namespace core_tests_pigeontest { using flutter::BasicMessageChannel; using flutter::CustomEncodableValue; using flutter::EncodableList; using flutter::EncodableMap; using flutter::EncodableValue; FlutterError CreateConnectionError(const std::string channel_name) { return FlutterError( "channel-error", "Unable to establish connection on channel: '" + channel_name + "'.", EncodableValue("")); } // AllTypes AllTypes::AllTypes(bool a_bool, int64_t an_int, int64_t an_int64, double a_double, const std::vector<uint8_t>& a_byte_array, const std::vector<int32_t>& a4_byte_array, const std::vector<int64_t>& a8_byte_array, const std::vector<double>& a_float_array, const EncodableList& a_list, const EncodableMap& a_map, const AnEnum& an_enum, const std::string& a_string, const EncodableValue& an_object) : a_bool_(a_bool), an_int_(an_int), an_int64_(an_int64), a_double_(a_double), a_byte_array_(a_byte_array), a4_byte_array_(a4_byte_array), a8_byte_array_(a8_byte_array), a_float_array_(a_float_array), a_list_(a_list), a_map_(a_map), an_enum_(an_enum), a_string_(a_string), an_object_(an_object) {} bool AllTypes::a_bool() const { return a_bool_; } void AllTypes::set_a_bool(bool value_arg) { a_bool_ = value_arg; } int64_t AllTypes::an_int() const { return an_int_; } void AllTypes::set_an_int(int64_t value_arg) { an_int_ = value_arg; } int64_t AllTypes::an_int64() const { return an_int64_; } void AllTypes::set_an_int64(int64_t value_arg) { an_int64_ = value_arg; } double AllTypes::a_double() const { return a_double_; } void AllTypes::set_a_double(double value_arg) { a_double_ = value_arg; } const std::vector<uint8_t>& AllTypes::a_byte_array() const { return a_byte_array_; } void AllTypes::set_a_byte_array(const std::vector<uint8_t>& value_arg) { a_byte_array_ = value_arg; } const std::vector<int32_t>& AllTypes::a4_byte_array() const { return a4_byte_array_; } void AllTypes::set_a4_byte_array(const std::vector<int32_t>& value_arg) { a4_byte_array_ = value_arg; } const std::vector<int64_t>& AllTypes::a8_byte_array() const { return a8_byte_array_; } void AllTypes::set_a8_byte_array(const std::vector<int64_t>& value_arg) { a8_byte_array_ = value_arg; } const std::vector<double>& AllTypes::a_float_array() const { return a_float_array_; } void AllTypes::set_a_float_array(const std::vector<double>& value_arg) { a_float_array_ = value_arg; } const EncodableList& AllTypes::a_list() const { return a_list_; } void AllTypes::set_a_list(const EncodableList& value_arg) { a_list_ = value_arg; } const EncodableMap& AllTypes::a_map() const { return a_map_; } void AllTypes::set_a_map(const EncodableMap& value_arg) { a_map_ = value_arg; } const AnEnum& AllTypes::an_enum() const { return an_enum_; } void AllTypes::set_an_enum(const AnEnum& value_arg) { an_enum_ = value_arg; } const std::string& AllTypes::a_string() const { return a_string_; } void AllTypes::set_a_string(std::string_view value_arg) { a_string_ = value_arg; } const EncodableValue& AllTypes::an_object() const { return an_object_; } void AllTypes::set_an_object(const EncodableValue& value_arg) { an_object_ = value_arg; } EncodableList AllTypes::ToEncodableList() const { EncodableList list; list.reserve(13); list.push_back(EncodableValue(a_bool_)); list.push_back(EncodableValue(an_int_)); list.push_back(EncodableValue(an_int64_)); list.push_back(EncodableValue(a_double_)); list.push_back(EncodableValue(a_byte_array_)); list.push_back(EncodableValue(a4_byte_array_)); list.push_back(EncodableValue(a8_byte_array_)); list.push_back(EncodableValue(a_float_array_)); list.push_back(EncodableValue(a_list_)); list.push_back(EncodableValue(a_map_)); list.push_back(EncodableValue((int)an_enum_)); list.push_back(EncodableValue(a_string_)); list.push_back(an_object_); return list; } AllTypes AllTypes::FromEncodableList(const EncodableList& list) { AllTypes decoded( std::get<bool>(list[0]), list[1].LongValue(), list[2].LongValue(), std::get<double>(list[3]), std::get<std::vector<uint8_t>>(list[4]), std::get<std::vector<int32_t>>(list[5]), std::get<std::vector<int64_t>>(list[6]), std::get<std::vector<double>>(list[7]), std::get<EncodableList>(list[8]), std::get<EncodableMap>(list[9]), (AnEnum)(std::get<int32_t>(list[10])), std::get<std::string>(list[11]), list[12]); return decoded; } // AllNullableTypes AllNullableTypes::AllNullableTypes() {} AllNullableTypes::AllNullableTypes( const bool* a_nullable_bool, const int64_t* a_nullable_int, const int64_t* a_nullable_int64, const double* a_nullable_double, const std::vector<uint8_t>* a_nullable_byte_array, const std::vector<int32_t>* a_nullable4_byte_array, const std::vector<int64_t>* a_nullable8_byte_array, const std::vector<double>* a_nullable_float_array, const EncodableList* a_nullable_list, const EncodableMap* a_nullable_map, const EncodableList* nullable_nested_list, const EncodableMap* nullable_map_with_annotations, const EncodableMap* nullable_map_with_object, const AnEnum* a_nullable_enum, const std::string* a_nullable_string, const EncodableValue* a_nullable_object) : a_nullable_bool_(a_nullable_bool ? std::optional<bool>(*a_nullable_bool) : std::nullopt), a_nullable_int_(a_nullable_int ? std::optional<int64_t>(*a_nullable_int) : std::nullopt), a_nullable_int64_(a_nullable_int64 ? std::optional<int64_t>(*a_nullable_int64) : std::nullopt), a_nullable_double_(a_nullable_double ? std::optional<double>(*a_nullable_double) : std::nullopt), a_nullable_byte_array_( a_nullable_byte_array ? std::optional<std::vector<uint8_t>>(*a_nullable_byte_array) : std::nullopt), a_nullable4_byte_array_( a_nullable4_byte_array ? std::optional<std::vector<int32_t>>(*a_nullable4_byte_array) : std::nullopt), a_nullable8_byte_array_( a_nullable8_byte_array ? std::optional<std::vector<int64_t>>(*a_nullable8_byte_array) : std::nullopt), a_nullable_float_array_( a_nullable_float_array ? std::optional<std::vector<double>>(*a_nullable_float_array) : std::nullopt), a_nullable_list_(a_nullable_list ? std::optional<EncodableList>(*a_nullable_list) : std::nullopt), a_nullable_map_(a_nullable_map ? std::optional<EncodableMap>(*a_nullable_map) : std::nullopt), nullable_nested_list_(nullable_nested_list ? std::optional<EncodableList>( *nullable_nested_list) : std::nullopt), nullable_map_with_annotations_( nullable_map_with_annotations ? std::optional<EncodableMap>(*nullable_map_with_annotations) : std::nullopt), nullable_map_with_object_( nullable_map_with_object ? std::optional<EncodableMap>(*nullable_map_with_object) : std::nullopt), a_nullable_enum_(a_nullable_enum ? std::optional<AnEnum>(*a_nullable_enum) : std::nullopt), a_nullable_string_(a_nullable_string ? std::optional<std::string>(*a_nullable_string) : std::nullopt), a_nullable_object_(a_nullable_object ? std::optional<EncodableValue>(*a_nullable_object) : std::nullopt) {} const bool* AllNullableTypes::a_nullable_bool() const { return a_nullable_bool_ ? &(*a_nullable_bool_) : nullptr; } void AllNullableTypes::set_a_nullable_bool(const bool* value_arg) { a_nullable_bool_ = value_arg ? std::optional<bool>(*value_arg) : std::nullopt; } void AllNullableTypes::set_a_nullable_bool(bool value_arg) { a_nullable_bool_ = value_arg; } const int64_t* AllNullableTypes::a_nullable_int() const { return a_nullable_int_ ? &(*a_nullable_int_) : nullptr; } void AllNullableTypes::set_a_nullable_int(const int64_t* value_arg) { a_nullable_int_ = value_arg ? std::optional<int64_t>(*value_arg) : std::nullopt; } void AllNullableTypes::set_a_nullable_int(int64_t value_arg) { a_nullable_int_ = value_arg; } const int64_t* AllNullableTypes::a_nullable_int64() const { return a_nullable_int64_ ? &(*a_nullable_int64_) : nullptr; } void AllNullableTypes::set_a_nullable_int64(const int64_t* value_arg) { a_nullable_int64_ = value_arg ? std::optional<int64_t>(*value_arg) : std::nullopt; } void AllNullableTypes::set_a_nullable_int64(int64_t value_arg) { a_nullable_int64_ = value_arg; } const double* AllNullableTypes::a_nullable_double() const { return a_nullable_double_ ? &(*a_nullable_double_) : nullptr; } void AllNullableTypes::set_a_nullable_double(const double* value_arg) { a_nullable_double_ = value_arg ? std::optional<double>(*value_arg) : std::nullopt; } void AllNullableTypes::set_a_nullable_double(double value_arg) { a_nullable_double_ = value_arg; } const std::vector<uint8_t>* AllNullableTypes::a_nullable_byte_array() const { return a_nullable_byte_array_ ? &(*a_nullable_byte_array_) : nullptr; } void AllNullableTypes::set_a_nullable_byte_array( const std::vector<uint8_t>* value_arg) { a_nullable_byte_array_ = value_arg ? std::optional<std::vector<uint8_t>>(*value_arg) : std::nullopt; } void AllNullableTypes::set_a_nullable_byte_array( const std::vector<uint8_t>& value_arg) { a_nullable_byte_array_ = value_arg; } const std::vector<int32_t>* AllNullableTypes::a_nullable4_byte_array() const { return a_nullable4_byte_array_ ? &(*a_nullable4_byte_array_) : nullptr; } void AllNullableTypes::set_a_nullable4_byte_array( const std::vector<int32_t>* value_arg) { a_nullable4_byte_array_ = value_arg ? std::optional<std::vector<int32_t>>(*value_arg) : std::nullopt; } void AllNullableTypes::set_a_nullable4_byte_array( const std::vector<int32_t>& value_arg) { a_nullable4_byte_array_ = value_arg; } const std::vector<int64_t>* AllNullableTypes::a_nullable8_byte_array() const { return a_nullable8_byte_array_ ? &(*a_nullable8_byte_array_) : nullptr; } void AllNullableTypes::set_a_nullable8_byte_array( const std::vector<int64_t>* value_arg) { a_nullable8_byte_array_ = value_arg ? std::optional<std::vector<int64_t>>(*value_arg) : std::nullopt; } void AllNullableTypes::set_a_nullable8_byte_array( const std::vector<int64_t>& value_arg) { a_nullable8_byte_array_ = value_arg; } const std::vector<double>* AllNullableTypes::a_nullable_float_array() const { return a_nullable_float_array_ ? &(*a_nullable_float_array_) : nullptr; } void AllNullableTypes::set_a_nullable_float_array( const std::vector<double>* value_arg) { a_nullable_float_array_ = value_arg ? std::optional<std::vector<double>>(*value_arg) : std::nullopt; } void AllNullableTypes::set_a_nullable_float_array( const std::vector<double>& value_arg) { a_nullable_float_array_ = value_arg; } const EncodableList* AllNullableTypes::a_nullable_list() const { return a_nullable_list_ ? &(*a_nullable_list_) : nullptr; } void AllNullableTypes::set_a_nullable_list(const EncodableList* value_arg) { a_nullable_list_ = value_arg ? std::optional<EncodableList>(*value_arg) : std::nullopt; } void AllNullableTypes::set_a_nullable_list(const EncodableList& value_arg) { a_nullable_list_ = value_arg; } const EncodableMap* AllNullableTypes::a_nullable_map() const { return a_nullable_map_ ? &(*a_nullable_map_) : nullptr; } void AllNullableTypes::set_a_nullable_map(const EncodableMap* value_arg) { a_nullable_map_ = value_arg ? std::optional<EncodableMap>(*value_arg) : std::nullopt; } void AllNullableTypes::set_a_nullable_map(const EncodableMap& value_arg) { a_nullable_map_ = value_arg; } const EncodableList* AllNullableTypes::nullable_nested_list() const { return nullable_nested_list_ ? &(*nullable_nested_list_) : nullptr; } void AllNullableTypes::set_nullable_nested_list( const EncodableList* value_arg) { nullable_nested_list_ = value_arg ? std::optional<EncodableList>(*value_arg) : std::nullopt; } void AllNullableTypes::set_nullable_nested_list( const EncodableList& value_arg) { nullable_nested_list_ = value_arg; } const EncodableMap* AllNullableTypes::nullable_map_with_annotations() const { return nullable_map_with_annotations_ ? &(*nullable_map_with_annotations_) : nullptr; } void AllNullableTypes::set_nullable_map_with_annotations( const EncodableMap* value_arg) { nullable_map_with_annotations_ = value_arg ? std::optional<EncodableMap>(*value_arg) : std::nullopt; } void AllNullableTypes::set_nullable_map_with_annotations( const EncodableMap& value_arg) { nullable_map_with_annotations_ = value_arg; } const EncodableMap* AllNullableTypes::nullable_map_with_object() const { return nullable_map_with_object_ ? &(*nullable_map_with_object_) : nullptr; } void AllNullableTypes::set_nullable_map_with_object( const EncodableMap* value_arg) { nullable_map_with_object_ = value_arg ? std::optional<EncodableMap>(*value_arg) : std::nullopt; } void AllNullableTypes::set_nullable_map_with_object( const EncodableMap& value_arg) { nullable_map_with_object_ = value_arg; } const AnEnum* AllNullableTypes::a_nullable_enum() const { return a_nullable_enum_ ? &(*a_nullable_enum_) : nullptr; } void AllNullableTypes::set_a_nullable_enum(const AnEnum* value_arg) { a_nullable_enum_ = value_arg ? std::optional<AnEnum>(*value_arg) : std::nullopt; } void AllNullableTypes::set_a_nullable_enum(const AnEnum& value_arg) { a_nullable_enum_ = value_arg; } const std::string* AllNullableTypes::a_nullable_string() const { return a_nullable_string_ ? &(*a_nullable_string_) : nullptr; } void AllNullableTypes::set_a_nullable_string( const std::string_view* value_arg) { a_nullable_string_ = value_arg ? std::optional<std::string>(*value_arg) : std::nullopt; } void AllNullableTypes::set_a_nullable_string(std::string_view value_arg) { a_nullable_string_ = value_arg; } const EncodableValue* AllNullableTypes::a_nullable_object() const { return a_nullable_object_ ? &(*a_nullable_object_) : nullptr; } void AllNullableTypes::set_a_nullable_object(const EncodableValue* value_arg) { a_nullable_object_ = value_arg ? std::optional<EncodableValue>(*value_arg) : std::nullopt; } void AllNullableTypes::set_a_nullable_object(const EncodableValue& value_arg) { a_nullable_object_ = value_arg; } EncodableList AllNullableTypes::ToEncodableList() const { EncodableList list; list.reserve(16); list.push_back(a_nullable_bool_ ? EncodableValue(*a_nullable_bool_) : EncodableValue()); list.push_back(a_nullable_int_ ? EncodableValue(*a_nullable_int_) : EncodableValue()); list.push_back(a_nullable_int64_ ? EncodableValue(*a_nullable_int64_) : EncodableValue()); list.push_back(a_nullable_double_ ? EncodableValue(*a_nullable_double_) : EncodableValue()); list.push_back(a_nullable_byte_array_ ? EncodableValue(*a_nullable_byte_array_) : EncodableValue()); list.push_back(a_nullable4_byte_array_ ? EncodableValue(*a_nullable4_byte_array_) : EncodableValue()); list.push_back(a_nullable8_byte_array_ ? EncodableValue(*a_nullable8_byte_array_) : EncodableValue()); list.push_back(a_nullable_float_array_ ? EncodableValue(*a_nullable_float_array_) : EncodableValue()); list.push_back(a_nullable_list_ ? EncodableValue(*a_nullable_list_) : EncodableValue()); list.push_back(a_nullable_map_ ? EncodableValue(*a_nullable_map_) : EncodableValue()); list.push_back(nullable_nested_list_ ? EncodableValue(*nullable_nested_list_) : EncodableValue()); list.push_back(nullable_map_with_annotations_ ? EncodableValue(*nullable_map_with_annotations_) : EncodableValue()); list.push_back(nullable_map_with_object_ ? EncodableValue(*nullable_map_with_object_) : EncodableValue()); list.push_back(a_nullable_enum_ ? EncodableValue((int)(*a_nullable_enum_)) : EncodableValue()); list.push_back(a_nullable_string_ ? EncodableValue(*a_nullable_string_) : EncodableValue()); list.push_back(a_nullable_object_ ? *a_nullable_object_ : EncodableValue()); return list; } AllNullableTypes AllNullableTypes::FromEncodableList( const EncodableList& list) { AllNullableTypes decoded; auto& encodable_a_nullable_bool = list[0]; if (!encodable_a_nullable_bool.IsNull()) { decoded.set_a_nullable_bool(std::get<bool>(encodable_a_nullable_bool)); } auto& encodable_a_nullable_int = list[1]; if (!encodable_a_nullable_int.IsNull()) { decoded.set_a_nullable_int(encodable_a_nullable_int.LongValue()); } auto& encodable_a_nullable_int64 = list[2]; if (!encodable_a_nullable_int64.IsNull()) { decoded.set_a_nullable_int64(encodable_a_nullable_int64.LongValue()); } auto& encodable_a_nullable_double = list[3]; if (!encodable_a_nullable_double.IsNull()) { decoded.set_a_nullable_double( std::get<double>(encodable_a_nullable_double)); } auto& encodable_a_nullable_byte_array = list[4]; if (!encodable_a_nullable_byte_array.IsNull()) { decoded.set_a_nullable_byte_array( std::get<std::vector<uint8_t>>(encodable_a_nullable_byte_array)); } auto& encodable_a_nullable4_byte_array = list[5]; if (!encodable_a_nullable4_byte_array.IsNull()) { decoded.set_a_nullable4_byte_array( std::get<std::vector<int32_t>>(encodable_a_nullable4_byte_array)); } auto& encodable_a_nullable8_byte_array = list[6]; if (!encodable_a_nullable8_byte_array.IsNull()) { decoded.set_a_nullable8_byte_array( std::get<std::vector<int64_t>>(encodable_a_nullable8_byte_array)); } auto& encodable_a_nullable_float_array = list[7]; if (!encodable_a_nullable_float_array.IsNull()) { decoded.set_a_nullable_float_array( std::get<std::vector<double>>(encodable_a_nullable_float_array)); } auto& encodable_a_nullable_list = list[8]; if (!encodable_a_nullable_list.IsNull()) { decoded.set_a_nullable_list( std::get<EncodableList>(encodable_a_nullable_list)); } auto& encodable_a_nullable_map = list[9]; if (!encodable_a_nullable_map.IsNull()) { decoded.set_a_nullable_map( std::get<EncodableMap>(encodable_a_nullable_map)); } auto& encodable_nullable_nested_list = list[10]; if (!encodable_nullable_nested_list.IsNull()) { decoded.set_nullable_nested_list( std::get<EncodableList>(encodable_nullable_nested_list)); } auto& encodable_nullable_map_with_annotations = list[11]; if (!encodable_nullable_map_with_annotations.IsNull()) { decoded.set_nullable_map_with_annotations( std::get<EncodableMap>(encodable_nullable_map_with_annotations)); } auto& encodable_nullable_map_with_object = list[12]; if (!encodable_nullable_map_with_object.IsNull()) { decoded.set_nullable_map_with_object( std::get<EncodableMap>(encodable_nullable_map_with_object)); } auto& encodable_a_nullable_enum = list[13]; if (!encodable_a_nullable_enum.IsNull()) { decoded.set_a_nullable_enum( (AnEnum)(std::get<int32_t>(encodable_a_nullable_enum))); } auto& encodable_a_nullable_string = list[14]; if (!encodable_a_nullable_string.IsNull()) { decoded.set_a_nullable_string( std::get<std::string>(encodable_a_nullable_string)); } auto& encodable_a_nullable_object = list[15]; if (!encodable_a_nullable_object.IsNull()) { decoded.set_a_nullable_object(encodable_a_nullable_object); } return decoded; } // AllClassesWrapper AllClassesWrapper::AllClassesWrapper(const AllNullableTypes& all_nullable_types) : all_nullable_types_(all_nullable_types) {} AllClassesWrapper::AllClassesWrapper(const AllNullableTypes& all_nullable_types, const AllTypes* all_types) : all_nullable_types_(all_nullable_types), all_types_(all_types ? std::optional<AllTypes>(*all_types) : std::nullopt) {} const AllNullableTypes& AllClassesWrapper::all_nullable_types() const { return all_nullable_types_; } void AllClassesWrapper::set_all_nullable_types( const AllNullableTypes& value_arg) { all_nullable_types_ = value_arg; } const AllTypes* AllClassesWrapper::all_types() const { return all_types_ ? &(*all_types_) : nullptr; } void AllClassesWrapper::set_all_types(const AllTypes* value_arg) { all_types_ = value_arg ? std::optional<AllTypes>(*value_arg) : std::nullopt; } void AllClassesWrapper::set_all_types(const AllTypes& value_arg) { all_types_ = value_arg; } EncodableList AllClassesWrapper::ToEncodableList() const { EncodableList list; list.reserve(2); list.push_back(EncodableValue(all_nullable_types_.ToEncodableList())); list.push_back(all_types_ ? EncodableValue(all_types_->ToEncodableList()) : EncodableValue()); return list; } AllClassesWrapper AllClassesWrapper::FromEncodableList( const EncodableList& list) { AllClassesWrapper decoded( AllNullableTypes::FromEncodableList(std::get<EncodableList>(list[0]))); auto& encodable_all_types = list[1]; if (!encodable_all_types.IsNull()) { decoded.set_all_types(AllTypes::FromEncodableList( std::get<EncodableList>(encodable_all_types))); } return decoded; } // TestMessage TestMessage::TestMessage() {} TestMessage::TestMessage(const EncodableList* test_list) : test_list_(test_list ? std::optional<EncodableList>(*test_list) : std::nullopt) {} const EncodableList* TestMessage::test_list() const { return test_list_ ? &(*test_list_) : nullptr; } void TestMessage::set_test_list(const EncodableList* value_arg) { test_list_ = value_arg ? std::optional<EncodableList>(*value_arg) : std::nullopt; } void TestMessage::set_test_list(const EncodableList& value_arg) { test_list_ = value_arg; } EncodableList TestMessage::ToEncodableList() const { EncodableList list; list.reserve(1); list.push_back(test_list_ ? EncodableValue(*test_list_) : EncodableValue()); return list; } TestMessage TestMessage::FromEncodableList(const EncodableList& list) { TestMessage decoded; auto& encodable_test_list = list[0]; if (!encodable_test_list.IsNull()) { decoded.set_test_list(std::get<EncodableList>(encodable_test_list)); } return decoded; } HostIntegrationCoreApiCodecSerializer::HostIntegrationCoreApiCodecSerializer() { } EncodableValue HostIntegrationCoreApiCodecSerializer::ReadValueOfType( uint8_t type, flutter::ByteStreamReader* stream) const { switch (type) { case 128: return CustomEncodableValue(AllClassesWrapper::FromEncodableList( std::get<EncodableList>(ReadValue(stream)))); case 129: return CustomEncodableValue(AllNullableTypes::FromEncodableList( std::get<EncodableList>(ReadValue(stream)))); case 130: return CustomEncodableValue(AllTypes::FromEncodableList( std::get<EncodableList>(ReadValue(stream)))); case 131: return CustomEncodableValue(TestMessage::FromEncodableList( std::get<EncodableList>(ReadValue(stream)))); default: return flutter::StandardCodecSerializer::ReadValueOfType(type, stream); } } void HostIntegrationCoreApiCodecSerializer::WriteValue( const EncodableValue& value, flutter::ByteStreamWriter* stream) const { if (const CustomEncodableValue* custom_value = std::get_if<CustomEncodableValue>(&value)) { if (custom_value->type() == typeid(AllClassesWrapper)) { stream->WriteByte(128); WriteValue(EncodableValue(std::any_cast<AllClassesWrapper>(*custom_value) .ToEncodableList()), stream); return; } if (custom_value->type() == typeid(AllNullableTypes)) { stream->WriteByte(129); WriteValue( EncodableValue( std::any_cast<AllNullableTypes>(*custom_value).ToEncodableList()), stream); return; } if (custom_value->type() == typeid(AllTypes)) { stream->WriteByte(130); WriteValue(EncodableValue( std::any_cast<AllTypes>(*custom_value).ToEncodableList()), stream); return; } if (custom_value->type() == typeid(TestMessage)) { stream->WriteByte(131); WriteValue( EncodableValue( std::any_cast<TestMessage>(*custom_value).ToEncodableList()), stream); return; } } flutter::StandardCodecSerializer::WriteValue(value, stream); } /// The codec used by HostIntegrationCoreApi. const flutter::StandardMessageCodec& HostIntegrationCoreApi::GetCodec() { return flutter::StandardMessageCodec::GetInstance( &HostIntegrationCoreApiCodecSerializer::GetInstance()); } // Sets up an instance of `HostIntegrationCoreApi` to handle messages through // the `binary_messenger`. void HostIntegrationCoreApi::SetUp(flutter::BinaryMessenger* binary_messenger, HostIntegrationCoreApi* api) { { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.noop", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { std::optional<FlutterError> output = api->Noop(); if (output.has_value()) { reply(WrapError(output.value())); return; } EncodableList wrapped; wrapped.push_back(EncodableValue()); reply(EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.echoAllTypes", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_everything_arg = args.at(0); if (encodable_everything_arg.IsNull()) { reply(WrapError("everything_arg unexpectedly null.")); return; } const auto& everything_arg = std::any_cast<const AllTypes&>( std::get<CustomEncodableValue>(encodable_everything_arg)); ErrorOr<AllTypes> output = api->EchoAllTypes(everything_arg); if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back( CustomEncodableValue(std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.throwError", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { ErrorOr<std::optional<EncodableValue>> output = api->ThrowError(); if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back( EncodableValue(std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.throwErrorFromVoid", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { std::optional<FlutterError> output = api->ThrowErrorFromVoid(); if (output.has_value()) { reply(WrapError(output.value())); return; } EncodableList wrapped; wrapped.push_back(EncodableValue()); reply(EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.throwFlutterError", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { ErrorOr<std::optional<EncodableValue>> output = api->ThrowFlutterError(); if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back( EncodableValue(std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.echoInt", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_an_int_arg = args.at(0); if (encodable_an_int_arg.IsNull()) { reply(WrapError("an_int_arg unexpectedly null.")); return; } const int64_t an_int_arg = encodable_an_int_arg.LongValue(); ErrorOr<int64_t> output = api->EchoInt(an_int_arg); if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back(EncodableValue(std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.echoDouble", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_double_arg = args.at(0); if (encodable_a_double_arg.IsNull()) { reply(WrapError("a_double_arg unexpectedly null.")); return; } const auto& a_double_arg = std::get<double>(encodable_a_double_arg); ErrorOr<double> output = api->EchoDouble(a_double_arg); if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back(EncodableValue(std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.echoBool", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_bool_arg = args.at(0); if (encodable_a_bool_arg.IsNull()) { reply(WrapError("a_bool_arg unexpectedly null.")); return; } const auto& a_bool_arg = std::get<bool>(encodable_a_bool_arg); ErrorOr<bool> output = api->EchoBool(a_bool_arg); if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back(EncodableValue(std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.echoString", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_string_arg = args.at(0); if (encodable_a_string_arg.IsNull()) { reply(WrapError("a_string_arg unexpectedly null.")); return; } const auto& a_string_arg = std::get<std::string>(encodable_a_string_arg); ErrorOr<std::string> output = api->EchoString(a_string_arg); if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back(EncodableValue(std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.echoUint8List", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_uint8_list_arg = args.at(0); if (encodable_a_uint8_list_arg.IsNull()) { reply(WrapError("a_uint8_list_arg unexpectedly null.")); return; } const auto& a_uint8_list_arg = std::get<std::vector<uint8_t>>(encodable_a_uint8_list_arg); ErrorOr<std::vector<uint8_t>> output = api->EchoUint8List(a_uint8_list_arg); if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back(EncodableValue(std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.echoObject", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_an_object_arg = args.at(0); if (encodable_an_object_arg.IsNull()) { reply(WrapError("an_object_arg unexpectedly null.")); return; } const auto& an_object_arg = encodable_an_object_arg; ErrorOr<EncodableValue> output = api->EchoObject(an_object_arg); if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back(EncodableValue(std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.echoList", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_list_arg = args.at(0); if (encodable_a_list_arg.IsNull()) { reply(WrapError("a_list_arg unexpectedly null.")); return; } const auto& a_list_arg = std::get<EncodableList>(encodable_a_list_arg); ErrorOr<EncodableList> output = api->EchoList(a_list_arg); if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back(EncodableValue(std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.echoMap", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_map_arg = args.at(0); if (encodable_a_map_arg.IsNull()) { reply(WrapError("a_map_arg unexpectedly null.")); return; } const auto& a_map_arg = std::get<EncodableMap>(encodable_a_map_arg); ErrorOr<EncodableMap> output = api->EchoMap(a_map_arg); if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back(EncodableValue(std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.echoClassWrapper", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_wrapper_arg = args.at(0); if (encodable_wrapper_arg.IsNull()) { reply(WrapError("wrapper_arg unexpectedly null.")); return; } const auto& wrapper_arg = std::any_cast<const AllClassesWrapper&>( std::get<CustomEncodableValue>(encodable_wrapper_arg)); ErrorOr<AllClassesWrapper> output = api->EchoClassWrapper(wrapper_arg); if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back( CustomEncodableValue(std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.echoEnum", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_an_enum_arg = args.at(0); if (encodable_an_enum_arg.IsNull()) { reply(WrapError("an_enum_arg unexpectedly null.")); return; } const AnEnum& an_enum_arg = (AnEnum)encodable_an_enum_arg.LongValue(); ErrorOr<AnEnum> output = api->EchoEnum(an_enum_arg); if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back( EncodableValue((int)std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." "echoNamedDefaultString", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_string_arg = args.at(0); if (encodable_a_string_arg.IsNull()) { reply(WrapError("a_string_arg unexpectedly null.")); return; } const auto& a_string_arg = std::get<std::string>(encodable_a_string_arg); ErrorOr<std::string> output = api->EchoNamedDefaultString(a_string_arg); if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back(EncodableValue(std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." "echoOptionalDefaultDouble", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_double_arg = args.at(0); if (encodable_a_double_arg.IsNull()) { reply(WrapError("a_double_arg unexpectedly null.")); return; } const auto& a_double_arg = std::get<double>(encodable_a_double_arg); ErrorOr<double> output = api->EchoOptionalDefaultDouble(a_double_arg); if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back(EncodableValue(std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.echoRequiredInt", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_an_int_arg = args.at(0); if (encodable_an_int_arg.IsNull()) { reply(WrapError("an_int_arg unexpectedly null.")); return; } const int64_t an_int_arg = encodable_an_int_arg.LongValue(); ErrorOr<int64_t> output = api->EchoRequiredInt(an_int_arg); if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back(EncodableValue(std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.echoAllNullableTypes", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_everything_arg = args.at(0); const auto* everything_arg = &(std::any_cast<const AllNullableTypes&>( std::get<CustomEncodableValue>( encodable_everything_arg))); ErrorOr<std::optional<AllNullableTypes>> output = api->EchoAllNullableTypes(everything_arg); if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back( CustomEncodableValue(std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." "extractNestedNullableString", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_wrapper_arg = args.at(0); if (encodable_wrapper_arg.IsNull()) { reply(WrapError("wrapper_arg unexpectedly null.")); return; } const auto& wrapper_arg = std::any_cast<const AllClassesWrapper&>( std::get<CustomEncodableValue>(encodable_wrapper_arg)); ErrorOr<std::optional<std::string>> output = api->ExtractNestedNullableString(wrapper_arg); if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back( EncodableValue(std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." "createNestedNullableString", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_nullable_string_arg = args.at(0); const auto* nullable_string_arg = std::get_if<std::string>(&encodable_nullable_string_arg); ErrorOr<AllClassesWrapper> output = api->CreateNestedNullableString(nullable_string_arg); if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back( CustomEncodableValue(std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." "sendMultipleNullableTypes", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_nullable_bool_arg = args.at(0); const auto* a_nullable_bool_arg = std::get_if<bool>(&encodable_a_nullable_bool_arg); const auto& encodable_a_nullable_int_arg = args.at(1); const int64_t a_nullable_int_arg_value = encodable_a_nullable_int_arg.IsNull() ? 0 : encodable_a_nullable_int_arg.LongValue(); const auto* a_nullable_int_arg = encodable_a_nullable_int_arg.IsNull() ? nullptr : &a_nullable_int_arg_value; const auto& encodable_a_nullable_string_arg = args.at(2); const auto* a_nullable_string_arg = std::get_if<std::string>(&encodable_a_nullable_string_arg); ErrorOr<AllNullableTypes> output = api->SendMultipleNullableTypes( a_nullable_bool_arg, a_nullable_int_arg, a_nullable_string_arg); if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back( CustomEncodableValue(std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.echoNullableInt", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_nullable_int_arg = args.at(0); const int64_t a_nullable_int_arg_value = encodable_a_nullable_int_arg.IsNull() ? 0 : encodable_a_nullable_int_arg.LongValue(); const auto* a_nullable_int_arg = encodable_a_nullable_int_arg.IsNull() ? nullptr : &a_nullable_int_arg_value; ErrorOr<std::optional<int64_t>> output = api->EchoNullableInt(a_nullable_int_arg); if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back( EncodableValue(std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.echoNullableDouble", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_nullable_double_arg = args.at(0); const auto* a_nullable_double_arg = std::get_if<double>(&encodable_a_nullable_double_arg); ErrorOr<std::optional<double>> output = api->EchoNullableDouble(a_nullable_double_arg); if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back( EncodableValue(std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.echoNullableBool", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_nullable_bool_arg = args.at(0); const auto* a_nullable_bool_arg = std::get_if<bool>(&encodable_a_nullable_bool_arg); ErrorOr<std::optional<bool>> output = api->EchoNullableBool(a_nullable_bool_arg); if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back( EncodableValue(std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.echoNullableString", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_nullable_string_arg = args.at(0); const auto* a_nullable_string_arg = std::get_if<std::string>(&encodable_a_nullable_string_arg); ErrorOr<std::optional<std::string>> output = api->EchoNullableString(a_nullable_string_arg); if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back( EncodableValue(std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." "echoNullableUint8List", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_nullable_uint8_list_arg = args.at(0); const auto* a_nullable_uint8_list_arg = std::get_if<std::vector<uint8_t>>( &encodable_a_nullable_uint8_list_arg); ErrorOr<std::optional<std::vector<uint8_t>>> output = api->EchoNullableUint8List(a_nullable_uint8_list_arg); if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back( EncodableValue(std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.echoNullableObject", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_nullable_object_arg = args.at(0); const auto* a_nullable_object_arg = &encodable_a_nullable_object_arg; ErrorOr<std::optional<EncodableValue>> output = api->EchoNullableObject(a_nullable_object_arg); if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back( EncodableValue(std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.echoNullableList", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_nullable_list_arg = args.at(0); const auto* a_nullable_list_arg = std::get_if<EncodableList>(&encodable_a_nullable_list_arg); ErrorOr<std::optional<EncodableList>> output = api->EchoNullableList(a_nullable_list_arg); if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back( EncodableValue(std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.echoNullableMap", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_nullable_map_arg = args.at(0); const auto* a_nullable_map_arg = std::get_if<EncodableMap>(&encodable_a_nullable_map_arg); ErrorOr<std::optional<EncodableMap>> output = api->EchoNullableMap(a_nullable_map_arg); if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back( EncodableValue(std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.echoNullableEnum", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_an_enum_arg = args.at(0); const int64_t an_enum_arg_value = encodable_an_enum_arg.IsNull() ? 0 : encodable_an_enum_arg.LongValue(); const auto an_enum_arg = encodable_an_enum_arg.IsNull() ? std::nullopt : std::make_optional<AnEnum>( static_cast<AnEnum>(an_enum_arg_value)); ErrorOr<std::optional<AnEnum>> output = api->EchoNullableEnum( an_enum_arg ? &(*an_enum_arg) : nullptr); if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back( EncodableValue((int)std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." "echoOptionalNullableInt", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_nullable_int_arg = args.at(0); const int64_t a_nullable_int_arg_value = encodable_a_nullable_int_arg.IsNull() ? 0 : encodable_a_nullable_int_arg.LongValue(); const auto* a_nullable_int_arg = encodable_a_nullable_int_arg.IsNull() ? nullptr : &a_nullable_int_arg_value; ErrorOr<std::optional<int64_t>> output = api->EchoOptionalNullableInt(a_nullable_int_arg); if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back( EncodableValue(std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." "echoNamedNullableString", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_nullable_string_arg = args.at(0); const auto* a_nullable_string_arg = std::get_if<std::string>(&encodable_a_nullable_string_arg); ErrorOr<std::optional<std::string>> output = api->EchoNamedNullableString(a_nullable_string_arg); if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back( EncodableValue(std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.noopAsync", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { api->NoopAsync([reply](std::optional<FlutterError>&& output) { if (output.has_value()) { reply(WrapError(output.value())); return; } EncodableList wrapped; wrapped.push_back(EncodableValue()); reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.echoAsyncInt", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_an_int_arg = args.at(0); if (encodable_an_int_arg.IsNull()) { reply(WrapError("an_int_arg unexpectedly null.")); return; } const int64_t an_int_arg = encodable_an_int_arg.LongValue(); api->EchoAsyncInt(an_int_arg, [reply](ErrorOr<int64_t>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back( EncodableValue(std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.echoAsyncDouble", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_double_arg = args.at(0); if (encodable_a_double_arg.IsNull()) { reply(WrapError("a_double_arg unexpectedly null.")); return; } const auto& a_double_arg = std::get<double>(encodable_a_double_arg); api->EchoAsyncDouble( a_double_arg, [reply](ErrorOr<double>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back( EncodableValue(std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.echoAsyncBool", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_bool_arg = args.at(0); if (encodable_a_bool_arg.IsNull()) { reply(WrapError("a_bool_arg unexpectedly null.")); return; } const auto& a_bool_arg = std::get<bool>(encodable_a_bool_arg); api->EchoAsyncBool(a_bool_arg, [reply](ErrorOr<bool>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back( EncodableValue(std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.echoAsyncString", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_string_arg = args.at(0); if (encodable_a_string_arg.IsNull()) { reply(WrapError("a_string_arg unexpectedly null.")); return; } const auto& a_string_arg = std::get<std::string>(encodable_a_string_arg); api->EchoAsyncString( a_string_arg, [reply](ErrorOr<std::string>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back( EncodableValue(std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.echoAsyncUint8List", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_uint8_list_arg = args.at(0); if (encodable_a_uint8_list_arg.IsNull()) { reply(WrapError("a_uint8_list_arg unexpectedly null.")); return; } const auto& a_uint8_list_arg = std::get<std::vector<uint8_t>>(encodable_a_uint8_list_arg); api->EchoAsyncUint8List( a_uint8_list_arg, [reply](ErrorOr<std::vector<uint8_t>>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back( EncodableValue(std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.echoAsyncObject", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_an_object_arg = args.at(0); if (encodable_an_object_arg.IsNull()) { reply(WrapError("an_object_arg unexpectedly null.")); return; } const auto& an_object_arg = encodable_an_object_arg; api->EchoAsyncObject( an_object_arg, [reply](ErrorOr<EncodableValue>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back( EncodableValue(std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.echoAsyncList", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_list_arg = args.at(0); if (encodable_a_list_arg.IsNull()) { reply(WrapError("a_list_arg unexpectedly null.")); return; } const auto& a_list_arg = std::get<EncodableList>(encodable_a_list_arg); api->EchoAsyncList( a_list_arg, [reply](ErrorOr<EncodableList>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back( EncodableValue(std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.echoAsyncMap", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_map_arg = args.at(0); if (encodable_a_map_arg.IsNull()) { reply(WrapError("a_map_arg unexpectedly null.")); return; } const auto& a_map_arg = std::get<EncodableMap>(encodable_a_map_arg); api->EchoAsyncMap( a_map_arg, [reply](ErrorOr<EncodableMap>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back( EncodableValue(std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.echoAsyncEnum", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_an_enum_arg = args.at(0); if (encodable_an_enum_arg.IsNull()) { reply(WrapError("an_enum_arg unexpectedly null.")); return; } const AnEnum& an_enum_arg = (AnEnum)encodable_an_enum_arg.LongValue(); api->EchoAsyncEnum( an_enum_arg, [reply](ErrorOr<AnEnum>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back( EncodableValue((int)std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.throwAsyncError", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { api->ThrowAsyncError( [reply](ErrorOr<std::optional<EncodableValue>>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back( EncodableValue(std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." "throwAsyncErrorFromVoid", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { api->ThrowAsyncErrorFromVoid( [reply](std::optional<FlutterError>&& output) { if (output.has_value()) { reply(WrapError(output.value())); return; } EncodableList wrapped; wrapped.push_back(EncodableValue()); reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." "throwAsyncFlutterError", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { api->ThrowAsyncFlutterError( [reply](ErrorOr<std::optional<EncodableValue>>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back( EncodableValue(std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.echoAsyncAllTypes", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_everything_arg = args.at(0); if (encodable_everything_arg.IsNull()) { reply(WrapError("everything_arg unexpectedly null.")); return; } const auto& everything_arg = std::any_cast<const AllTypes&>( std::get<CustomEncodableValue>(encodable_everything_arg)); api->EchoAsyncAllTypes( everything_arg, [reply](ErrorOr<AllTypes>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back( CustomEncodableValue(std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." "echoAsyncNullableAllNullableTypes", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_everything_arg = args.at(0); const auto* everything_arg = &(std::any_cast<const AllNullableTypes&>( std::get<CustomEncodableValue>( encodable_everything_arg))); api->EchoAsyncNullableAllNullableTypes( everything_arg, [reply](ErrorOr<std::optional<AllNullableTypes>>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back(CustomEncodableValue( std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.echoAsyncNullableInt", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_an_int_arg = args.at(0); const int64_t an_int_arg_value = encodable_an_int_arg.IsNull() ? 0 : encodable_an_int_arg.LongValue(); const auto* an_int_arg = encodable_an_int_arg.IsNull() ? nullptr : &an_int_arg_value; api->EchoAsyncNullableInt( an_int_arg, [reply](ErrorOr<std::optional<int64_t>>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back( EncodableValue(std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." "echoAsyncNullableDouble", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_double_arg = args.at(0); const auto* a_double_arg = std::get_if<double>(&encodable_a_double_arg); api->EchoAsyncNullableDouble( a_double_arg, [reply](ErrorOr<std::optional<double>>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back( EncodableValue(std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." "echoAsyncNullableBool", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_bool_arg = args.at(0); const auto* a_bool_arg = std::get_if<bool>(&encodable_a_bool_arg); api->EchoAsyncNullableBool( a_bool_arg, [reply](ErrorOr<std::optional<bool>>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back( EncodableValue(std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." "echoAsyncNullableString", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_string_arg = args.at(0); const auto* a_string_arg = std::get_if<std::string>(&encodable_a_string_arg); api->EchoAsyncNullableString( a_string_arg, [reply](ErrorOr<std::optional<std::string>>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back( EncodableValue(std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." "echoAsyncNullableUint8List", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_uint8_list_arg = args.at(0); const auto* a_uint8_list_arg = std::get_if<std::vector<uint8_t>>( &encodable_a_uint8_list_arg); api->EchoAsyncNullableUint8List( a_uint8_list_arg, [reply]( ErrorOr<std::optional<std::vector<uint8_t>>>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back( EncodableValue(std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." "echoAsyncNullableObject", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_an_object_arg = args.at(0); const auto* an_object_arg = &encodable_an_object_arg; api->EchoAsyncNullableObject( an_object_arg, [reply](ErrorOr<std::optional<EncodableValue>>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back( EncodableValue(std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." "echoAsyncNullableList", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_list_arg = args.at(0); const auto* a_list_arg = std::get_if<EncodableList>(&encodable_a_list_arg); api->EchoAsyncNullableList( a_list_arg, [reply](ErrorOr<std::optional<EncodableList>>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back( EncodableValue(std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.echoAsyncNullableMap", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_map_arg = args.at(0); const auto* a_map_arg = std::get_if<EncodableMap>(&encodable_a_map_arg); api->EchoAsyncNullableMap( a_map_arg, [reply](ErrorOr<std::optional<EncodableMap>>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back( EncodableValue(std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." "echoAsyncNullableEnum", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_an_enum_arg = args.at(0); const int64_t an_enum_arg_value = encodable_an_enum_arg.IsNull() ? 0 : encodable_an_enum_arg.LongValue(); const auto an_enum_arg = encodable_an_enum_arg.IsNull() ? std::nullopt : std::make_optional<AnEnum>( static_cast<AnEnum>(an_enum_arg_value)); api->EchoAsyncNullableEnum( an_enum_arg ? &(*an_enum_arg) : nullptr, [reply](ErrorOr<std::optional<AnEnum>>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back(EncodableValue( (int)std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.callFlutterNoop", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { api->CallFlutterNoop( [reply](std::optional<FlutterError>&& output) { if (output.has_value()) { reply(WrapError(output.value())); return; } EncodableList wrapped; wrapped.push_back(EncodableValue()); reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." "callFlutterThrowError", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { api->CallFlutterThrowError( [reply](ErrorOr<std::optional<EncodableValue>>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back( EncodableValue(std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." "callFlutterThrowErrorFromVoid", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { api->CallFlutterThrowErrorFromVoid( [reply](std::optional<FlutterError>&& output) { if (output.has_value()) { reply(WrapError(output.value())); return; } EncodableList wrapped; wrapped.push_back(EncodableValue()); reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." "callFlutterEchoAllTypes", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_everything_arg = args.at(0); if (encodable_everything_arg.IsNull()) { reply(WrapError("everything_arg unexpectedly null.")); return; } const auto& everything_arg = std::any_cast<const AllTypes&>( std::get<CustomEncodableValue>(encodable_everything_arg)); api->CallFlutterEchoAllTypes( everything_arg, [reply](ErrorOr<AllTypes>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back( CustomEncodableValue(std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." "callFlutterEchoAllNullableTypes", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_everything_arg = args.at(0); const auto* everything_arg = &(std::any_cast<const AllNullableTypes&>( std::get<CustomEncodableValue>( encodable_everything_arg))); api->CallFlutterEchoAllNullableTypes( everything_arg, [reply](ErrorOr<std::optional<AllNullableTypes>>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back(CustomEncodableValue( std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." "callFlutterSendMultipleNullableTypes", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_nullable_bool_arg = args.at(0); const auto* a_nullable_bool_arg = std::get_if<bool>(&encodable_a_nullable_bool_arg); const auto& encodable_a_nullable_int_arg = args.at(1); const int64_t a_nullable_int_arg_value = encodable_a_nullable_int_arg.IsNull() ? 0 : encodable_a_nullable_int_arg.LongValue(); const auto* a_nullable_int_arg = encodable_a_nullable_int_arg.IsNull() ? nullptr : &a_nullable_int_arg_value; const auto& encodable_a_nullable_string_arg = args.at(2); const auto* a_nullable_string_arg = std::get_if<std::string>(&encodable_a_nullable_string_arg); api->CallFlutterSendMultipleNullableTypes( a_nullable_bool_arg, a_nullable_int_arg, a_nullable_string_arg, [reply](ErrorOr<AllNullableTypes>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back( CustomEncodableValue(std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.callFlutterEchoBool", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_bool_arg = args.at(0); if (encodable_a_bool_arg.IsNull()) { reply(WrapError("a_bool_arg unexpectedly null.")); return; } const auto& a_bool_arg = std::get<bool>(encodable_a_bool_arg); api->CallFlutterEchoBool( a_bool_arg, [reply](ErrorOr<bool>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back( EncodableValue(std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.callFlutterEchoInt", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_an_int_arg = args.at(0); if (encodable_an_int_arg.IsNull()) { reply(WrapError("an_int_arg unexpectedly null.")); return; } const int64_t an_int_arg = encodable_an_int_arg.LongValue(); api->CallFlutterEchoInt( an_int_arg, [reply](ErrorOr<int64_t>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back( EncodableValue(std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." "callFlutterEchoDouble", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_double_arg = args.at(0); if (encodable_a_double_arg.IsNull()) { reply(WrapError("a_double_arg unexpectedly null.")); return; } const auto& a_double_arg = std::get<double>(encodable_a_double_arg); api->CallFlutterEchoDouble( a_double_arg, [reply](ErrorOr<double>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back( EncodableValue(std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." "callFlutterEchoString", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_string_arg = args.at(0); if (encodable_a_string_arg.IsNull()) { reply(WrapError("a_string_arg unexpectedly null.")); return; } const auto& a_string_arg = std::get<std::string>(encodable_a_string_arg); api->CallFlutterEchoString( a_string_arg, [reply](ErrorOr<std::string>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back( EncodableValue(std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." "callFlutterEchoUint8List", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_list_arg = args.at(0); if (encodable_a_list_arg.IsNull()) { reply(WrapError("a_list_arg unexpectedly null.")); return; } const auto& a_list_arg = std::get<std::vector<uint8_t>>(encodable_a_list_arg); api->CallFlutterEchoUint8List( a_list_arg, [reply](ErrorOr<std::vector<uint8_t>>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back( EncodableValue(std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.callFlutterEchoList", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_list_arg = args.at(0); if (encodable_a_list_arg.IsNull()) { reply(WrapError("a_list_arg unexpectedly null.")); return; } const auto& a_list_arg = std::get<EncodableList>(encodable_a_list_arg); api->CallFlutterEchoList( a_list_arg, [reply](ErrorOr<EncodableList>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back( EncodableValue(std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.callFlutterEchoMap", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_map_arg = args.at(0); if (encodable_a_map_arg.IsNull()) { reply(WrapError("a_map_arg unexpectedly null.")); return; } const auto& a_map_arg = std::get<EncodableMap>(encodable_a_map_arg); api->CallFlutterEchoMap( a_map_arg, [reply](ErrorOr<EncodableMap>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back( EncodableValue(std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel(binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests." "HostIntegrationCoreApi.callFlutterEchoEnum", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_an_enum_arg = args.at(0); if (encodable_an_enum_arg.IsNull()) { reply(WrapError("an_enum_arg unexpectedly null.")); return; } const AnEnum& an_enum_arg = (AnEnum)encodable_an_enum_arg.LongValue(); api->CallFlutterEchoEnum( an_enum_arg, [reply](ErrorOr<AnEnum>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back( EncodableValue((int)std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." "callFlutterEchoNullableBool", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_bool_arg = args.at(0); const auto* a_bool_arg = std::get_if<bool>(&encodable_a_bool_arg); api->CallFlutterEchoNullableBool( a_bool_arg, [reply](ErrorOr<std::optional<bool>>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back( EncodableValue(std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." "callFlutterEchoNullableInt", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_an_int_arg = args.at(0); const int64_t an_int_arg_value = encodable_an_int_arg.IsNull() ? 0 : encodable_an_int_arg.LongValue(); const auto* an_int_arg = encodable_an_int_arg.IsNull() ? nullptr : &an_int_arg_value; api->CallFlutterEchoNullableInt( an_int_arg, [reply](ErrorOr<std::optional<int64_t>>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back( EncodableValue(std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." "callFlutterEchoNullableDouble", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_double_arg = args.at(0); const auto* a_double_arg = std::get_if<double>(&encodable_a_double_arg); api->CallFlutterEchoNullableDouble( a_double_arg, [reply](ErrorOr<std::optional<double>>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back( EncodableValue(std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." "callFlutterEchoNullableString", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_string_arg = args.at(0); const auto* a_string_arg = std::get_if<std::string>(&encodable_a_string_arg); api->CallFlutterEchoNullableString( a_string_arg, [reply](ErrorOr<std::optional<std::string>>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back( EncodableValue(std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." "callFlutterEchoNullableUint8List", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_list_arg = args.at(0); const auto* a_list_arg = std::get_if<std::vector<uint8_t>>(&encodable_a_list_arg); api->CallFlutterEchoNullableUint8List( a_list_arg, [reply]( ErrorOr<std::optional<std::vector<uint8_t>>>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back( EncodableValue(std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." "callFlutterEchoNullableList", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_list_arg = args.at(0); const auto* a_list_arg = std::get_if<EncodableList>(&encodable_a_list_arg); api->CallFlutterEchoNullableList( a_list_arg, [reply](ErrorOr<std::optional<EncodableList>>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back( EncodableValue(std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." "callFlutterEchoNullableMap", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_map_arg = args.at(0); const auto* a_map_arg = std::get_if<EncodableMap>(&encodable_a_map_arg); api->CallFlutterEchoNullableMap( a_map_arg, [reply](ErrorOr<std::optional<EncodableMap>>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back( EncodableValue(std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostIntegrationCoreApi." "callFlutterEchoNullableEnum", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_an_enum_arg = args.at(0); const int64_t an_enum_arg_value = encodable_an_enum_arg.IsNull() ? 0 : encodable_an_enum_arg.LongValue(); const auto an_enum_arg = encodable_an_enum_arg.IsNull() ? std::nullopt : std::make_optional<AnEnum>( static_cast<AnEnum>(an_enum_arg_value)); api->CallFlutterEchoNullableEnum( an_enum_arg ? &(*an_enum_arg) : nullptr, [reply](ErrorOr<std::optional<AnEnum>>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; auto output_optional = std::move(output).TakeValue(); if (output_optional) { wrapped.push_back(EncodableValue( (int)std::move(output_optional).value())); } else { wrapped.push_back(EncodableValue()); } reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } } EncodableValue HostIntegrationCoreApi::WrapError( std::string_view error_message) { return EncodableValue( EncodableList{EncodableValue(std::string(error_message)), EncodableValue("Error"), EncodableValue()}); } EncodableValue HostIntegrationCoreApi::WrapError(const FlutterError& error) { return EncodableValue(EncodableList{EncodableValue(error.code()), EncodableValue(error.message()), error.details()}); } FlutterIntegrationCoreApiCodecSerializer:: FlutterIntegrationCoreApiCodecSerializer() {} EncodableValue FlutterIntegrationCoreApiCodecSerializer::ReadValueOfType( uint8_t type, flutter::ByteStreamReader* stream) const { switch (type) { case 128: return CustomEncodableValue(AllClassesWrapper::FromEncodableList( std::get<EncodableList>(ReadValue(stream)))); case 129: return CustomEncodableValue(AllNullableTypes::FromEncodableList( std::get<EncodableList>(ReadValue(stream)))); case 130: return CustomEncodableValue(AllTypes::FromEncodableList( std::get<EncodableList>(ReadValue(stream)))); case 131: return CustomEncodableValue(TestMessage::FromEncodableList( std::get<EncodableList>(ReadValue(stream)))); default: return flutter::StandardCodecSerializer::ReadValueOfType(type, stream); } } void FlutterIntegrationCoreApiCodecSerializer::WriteValue( const EncodableValue& value, flutter::ByteStreamWriter* stream) const { if (const CustomEncodableValue* custom_value = std::get_if<CustomEncodableValue>(&value)) { if (custom_value->type() == typeid(AllClassesWrapper)) { stream->WriteByte(128); WriteValue(EncodableValue(std::any_cast<AllClassesWrapper>(*custom_value) .ToEncodableList()), stream); return; } if (custom_value->type() == typeid(AllNullableTypes)) { stream->WriteByte(129); WriteValue( EncodableValue( std::any_cast<AllNullableTypes>(*custom_value).ToEncodableList()), stream); return; } if (custom_value->type() == typeid(AllTypes)) { stream->WriteByte(130); WriteValue(EncodableValue( std::any_cast<AllTypes>(*custom_value).ToEncodableList()), stream); return; } if (custom_value->type() == typeid(TestMessage)) { stream->WriteByte(131); WriteValue( EncodableValue( std::any_cast<TestMessage>(*custom_value).ToEncodableList()), stream); return; } } flutter::StandardCodecSerializer::WriteValue(value, stream); } // Generated class from Pigeon that represents Flutter messages that can be // called from C++. FlutterIntegrationCoreApi::FlutterIntegrationCoreApi( flutter::BinaryMessenger* binary_messenger) : binary_messenger_(binary_messenger) {} const flutter::StandardMessageCodec& FlutterIntegrationCoreApi::GetCodec() { return flutter::StandardMessageCodec::GetInstance( &FlutterIntegrationCoreApiCodecSerializer::GetInstance()); } void FlutterIntegrationCoreApi::Noop( std::function<void(void)>&& on_success, std::function<void(const FlutterError&)>&& on_error) { const std::string channel_name = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi." "noop"; BasicMessageChannel<> channel(binary_messenger_, channel_name, &GetCodec()); EncodableValue encoded_api_arguments = EncodableValue(); channel.Send( encoded_api_arguments, [channel_name, on_success = std::move(on_success), on_error = std::move(on_error)]( const uint8_t* reply, size_t reply_size) { std::unique_ptr<EncodableValue> response = GetCodec().DecodeMessage(reply, reply_size); const auto& encodable_return_value = *response; const auto* list_return_value = std::get_if<EncodableList>(&encodable_return_value); if (list_return_value) { if (list_return_value->size() > 1) { on_error( FlutterError(std::get<std::string>(list_return_value->at(0)), std::get<std::string>(list_return_value->at(1)), list_return_value->at(2))); } else { on_success(); } } else { on_error(CreateConnectionError(channel_name)); } }); } void FlutterIntegrationCoreApi::ThrowError( std::function<void(const EncodableValue*)>&& on_success, std::function<void(const FlutterError&)>&& on_error) { const std::string channel_name = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi." "throwError"; BasicMessageChannel<> channel(binary_messenger_, channel_name, &GetCodec()); EncodableValue encoded_api_arguments = EncodableValue(); channel.Send( encoded_api_arguments, [channel_name, on_success = std::move(on_success), on_error = std::move(on_error)]( const uint8_t* reply, size_t reply_size) { std::unique_ptr<EncodableValue> response = GetCodec().DecodeMessage(reply, reply_size); const auto& encodable_return_value = *response; const auto* list_return_value = std::get_if<EncodableList>(&encodable_return_value); if (list_return_value) { if (list_return_value->size() > 1) { on_error( FlutterError(std::get<std::string>(list_return_value->at(0)), std::get<std::string>(list_return_value->at(1)), list_return_value->at(2))); } else { const auto* return_value = &list_return_value->at(0); on_success(return_value); } } else { on_error(CreateConnectionError(channel_name)); } }); } void FlutterIntegrationCoreApi::ThrowErrorFromVoid( std::function<void(void)>&& on_success, std::function<void(const FlutterError&)>&& on_error) { const std::string channel_name = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi." "throwErrorFromVoid"; BasicMessageChannel<> channel(binary_messenger_, channel_name, &GetCodec()); EncodableValue encoded_api_arguments = EncodableValue(); channel.Send( encoded_api_arguments, [channel_name, on_success = std::move(on_success), on_error = std::move(on_error)]( const uint8_t* reply, size_t reply_size) { std::unique_ptr<EncodableValue> response = GetCodec().DecodeMessage(reply, reply_size); const auto& encodable_return_value = *response; const auto* list_return_value = std::get_if<EncodableList>(&encodable_return_value); if (list_return_value) { if (list_return_value->size() > 1) { on_error( FlutterError(std::get<std::string>(list_return_value->at(0)), std::get<std::string>(list_return_value->at(1)), list_return_value->at(2))); } else { on_success(); } } else { on_error(CreateConnectionError(channel_name)); } }); } void FlutterIntegrationCoreApi::EchoAllTypes( const AllTypes& everything_arg, std::function<void(const AllTypes&)>&& on_success, std::function<void(const FlutterError&)>&& on_error) { const std::string channel_name = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi." "echoAllTypes"; BasicMessageChannel<> channel(binary_messenger_, channel_name, &GetCodec()); EncodableValue encoded_api_arguments = EncodableValue(EncodableList{ CustomEncodableValue(everything_arg), }); channel.Send( encoded_api_arguments, [channel_name, on_success = std::move(on_success), on_error = std::move(on_error)]( const uint8_t* reply, size_t reply_size) { std::unique_ptr<EncodableValue> response = GetCodec().DecodeMessage(reply, reply_size); const auto& encodable_return_value = *response; const auto* list_return_value = std::get_if<EncodableList>(&encodable_return_value); if (list_return_value) { if (list_return_value->size() > 1) { on_error( FlutterError(std::get<std::string>(list_return_value->at(0)), std::get<std::string>(list_return_value->at(1)), list_return_value->at(2))); } else { const auto& return_value = std::any_cast<const AllTypes&>( std::get<CustomEncodableValue>(list_return_value->at(0))); on_success(return_value); } } else { on_error(CreateConnectionError(channel_name)); } }); } void FlutterIntegrationCoreApi::EchoAllNullableTypes( const AllNullableTypes* everything_arg, std::function<void(const AllNullableTypes*)>&& on_success, std::function<void(const FlutterError&)>&& on_error) { const std::string channel_name = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi." "echoAllNullableTypes"; BasicMessageChannel<> channel(binary_messenger_, channel_name, &GetCodec()); EncodableValue encoded_api_arguments = EncodableValue(EncodableList{ everything_arg ? CustomEncodableValue(*everything_arg) : EncodableValue(), }); channel.Send( encoded_api_arguments, [channel_name, on_success = std::move(on_success), on_error = std::move(on_error)]( const uint8_t* reply, size_t reply_size) { std::unique_ptr<EncodableValue> response = GetCodec().DecodeMessage(reply, reply_size); const auto& encodable_return_value = *response; const auto* list_return_value = std::get_if<EncodableList>(&encodable_return_value); if (list_return_value) { if (list_return_value->size() > 1) { on_error( FlutterError(std::get<std::string>(list_return_value->at(0)), std::get<std::string>(list_return_value->at(1)), list_return_value->at(2))); } else { const auto* return_value = &(std::any_cast<const AllNullableTypes&>( std::get<CustomEncodableValue>(list_return_value->at(0)))); on_success(return_value); } } else { on_error(CreateConnectionError(channel_name)); } }); } void FlutterIntegrationCoreApi::SendMultipleNullableTypes( const bool* a_nullable_bool_arg, const int64_t* a_nullable_int_arg, const std::string* a_nullable_string_arg, std::function<void(const AllNullableTypes&)>&& on_success, std::function<void(const FlutterError&)>&& on_error) { const std::string channel_name = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi." "sendMultipleNullableTypes"; BasicMessageChannel<> channel(binary_messenger_, channel_name, &GetCodec()); EncodableValue encoded_api_arguments = EncodableValue(EncodableList{ a_nullable_bool_arg ? EncodableValue(*a_nullable_bool_arg) : EncodableValue(), a_nullable_int_arg ? EncodableValue(*a_nullable_int_arg) : EncodableValue(), a_nullable_string_arg ? EncodableValue(*a_nullable_string_arg) : EncodableValue(), }); channel.Send( encoded_api_arguments, [channel_name, on_success = std::move(on_success), on_error = std::move(on_error)]( const uint8_t* reply, size_t reply_size) { std::unique_ptr<EncodableValue> response = GetCodec().DecodeMessage(reply, reply_size); const auto& encodable_return_value = *response; const auto* list_return_value = std::get_if<EncodableList>(&encodable_return_value); if (list_return_value) { if (list_return_value->size() > 1) { on_error( FlutterError(std::get<std::string>(list_return_value->at(0)), std::get<std::string>(list_return_value->at(1)), list_return_value->at(2))); } else { const auto& return_value = std::any_cast<const AllNullableTypes&>( std::get<CustomEncodableValue>(list_return_value->at(0))); on_success(return_value); } } else { on_error(CreateConnectionError(channel_name)); } }); } void FlutterIntegrationCoreApi::EchoBool( bool a_bool_arg, std::function<void(bool)>&& on_success, std::function<void(const FlutterError&)>&& on_error) { const std::string channel_name = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi." "echoBool"; BasicMessageChannel<> channel(binary_messenger_, channel_name, &GetCodec()); EncodableValue encoded_api_arguments = EncodableValue(EncodableList{ EncodableValue(a_bool_arg), }); channel.Send( encoded_api_arguments, [channel_name, on_success = std::move(on_success), on_error = std::move(on_error)]( const uint8_t* reply, size_t reply_size) { std::unique_ptr<EncodableValue> response = GetCodec().DecodeMessage(reply, reply_size); const auto& encodable_return_value = *response; const auto* list_return_value = std::get_if<EncodableList>(&encodable_return_value); if (list_return_value) { if (list_return_value->size() > 1) { on_error( FlutterError(std::get<std::string>(list_return_value->at(0)), std::get<std::string>(list_return_value->at(1)), list_return_value->at(2))); } else { const auto& return_value = std::get<bool>(list_return_value->at(0)); on_success(return_value); } } else { on_error(CreateConnectionError(channel_name)); } }); } void FlutterIntegrationCoreApi::EchoInt( int64_t an_int_arg, std::function<void(int64_t)>&& on_success, std::function<void(const FlutterError&)>&& on_error) { const std::string channel_name = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi." "echoInt"; BasicMessageChannel<> channel(binary_messenger_, channel_name, &GetCodec()); EncodableValue encoded_api_arguments = EncodableValue(EncodableList{ EncodableValue(an_int_arg), }); channel.Send( encoded_api_arguments, [channel_name, on_success = std::move(on_success), on_error = std::move(on_error)]( const uint8_t* reply, size_t reply_size) { std::unique_ptr<EncodableValue> response = GetCodec().DecodeMessage(reply, reply_size); const auto& encodable_return_value = *response; const auto* list_return_value = std::get_if<EncodableList>(&encodable_return_value); if (list_return_value) { if (list_return_value->size() > 1) { on_error( FlutterError(std::get<std::string>(list_return_value->at(0)), std::get<std::string>(list_return_value->at(1)), list_return_value->at(2))); } else { const int64_t return_value = list_return_value->at(0).LongValue(); on_success(return_value); } } else { on_error(CreateConnectionError(channel_name)); } }); } void FlutterIntegrationCoreApi::EchoDouble( double a_double_arg, std::function<void(double)>&& on_success, std::function<void(const FlutterError&)>&& on_error) { const std::string channel_name = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi." "echoDouble"; BasicMessageChannel<> channel(binary_messenger_, channel_name, &GetCodec()); EncodableValue encoded_api_arguments = EncodableValue(EncodableList{ EncodableValue(a_double_arg), }); channel.Send(encoded_api_arguments, [channel_name, on_success = std::move(on_success), on_error = std::move(on_error)]( const uint8_t* reply, size_t reply_size) { std::unique_ptr<EncodableValue> response = GetCodec().DecodeMessage(reply, reply_size); const auto& encodable_return_value = *response; const auto* list_return_value = std::get_if<EncodableList>(&encodable_return_value); if (list_return_value) { if (list_return_value->size() > 1) { on_error(FlutterError(std::get<std::string>(list_return_value->at(0)), std::get<std::string>(list_return_value->at(1)), list_return_value->at(2))); } else { const auto& return_value = std::get<double>(list_return_value->at(0)); on_success(return_value); } } else { on_error(CreateConnectionError(channel_name)); } }); } void FlutterIntegrationCoreApi::EchoString( const std::string& a_string_arg, std::function<void(const std::string&)>&& on_success, std::function<void(const FlutterError&)>&& on_error) { const std::string channel_name = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi." "echoString"; BasicMessageChannel<> channel(binary_messenger_, channel_name, &GetCodec()); EncodableValue encoded_api_arguments = EncodableValue(EncodableList{ EncodableValue(a_string_arg), }); channel.Send( encoded_api_arguments, [channel_name, on_success = std::move(on_success), on_error = std::move(on_error)]( const uint8_t* reply, size_t reply_size) { std::unique_ptr<EncodableValue> response = GetCodec().DecodeMessage(reply, reply_size); const auto& encodable_return_value = *response; const auto* list_return_value = std::get_if<EncodableList>(&encodable_return_value); if (list_return_value) { if (list_return_value->size() > 1) { on_error( FlutterError(std::get<std::string>(list_return_value->at(0)), std::get<std::string>(list_return_value->at(1)), list_return_value->at(2))); } else { const auto& return_value = std::get<std::string>(list_return_value->at(0)); on_success(return_value); } } else { on_error(CreateConnectionError(channel_name)); } }); } void FlutterIntegrationCoreApi::EchoUint8List( const std::vector<uint8_t>& a_list_arg, std::function<void(const std::vector<uint8_t>&)>&& on_success, std::function<void(const FlutterError&)>&& on_error) { const std::string channel_name = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi." "echoUint8List"; BasicMessageChannel<> channel(binary_messenger_, channel_name, &GetCodec()); EncodableValue encoded_api_arguments = EncodableValue(EncodableList{ EncodableValue(a_list_arg), }); channel.Send( encoded_api_arguments, [channel_name, on_success = std::move(on_success), on_error = std::move(on_error)]( const uint8_t* reply, size_t reply_size) { std::unique_ptr<EncodableValue> response = GetCodec().DecodeMessage(reply, reply_size); const auto& encodable_return_value = *response; const auto* list_return_value = std::get_if<EncodableList>(&encodable_return_value); if (list_return_value) { if (list_return_value->size() > 1) { on_error( FlutterError(std::get<std::string>(list_return_value->at(0)), std::get<std::string>(list_return_value->at(1)), list_return_value->at(2))); } else { const auto& return_value = std::get<std::vector<uint8_t>>(list_return_value->at(0)); on_success(return_value); } } else { on_error(CreateConnectionError(channel_name)); } }); } void FlutterIntegrationCoreApi::EchoList( const EncodableList& a_list_arg, std::function<void(const EncodableList&)>&& on_success, std::function<void(const FlutterError&)>&& on_error) { const std::string channel_name = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi." "echoList"; BasicMessageChannel<> channel(binary_messenger_, channel_name, &GetCodec()); EncodableValue encoded_api_arguments = EncodableValue(EncodableList{ EncodableValue(a_list_arg), }); channel.Send( encoded_api_arguments, [channel_name, on_success = std::move(on_success), on_error = std::move(on_error)]( const uint8_t* reply, size_t reply_size) { std::unique_ptr<EncodableValue> response = GetCodec().DecodeMessage(reply, reply_size); const auto& encodable_return_value = *response; const auto* list_return_value = std::get_if<EncodableList>(&encodable_return_value); if (list_return_value) { if (list_return_value->size() > 1) { on_error( FlutterError(std::get<std::string>(list_return_value->at(0)), std::get<std::string>(list_return_value->at(1)), list_return_value->at(2))); } else { const auto& return_value = std::get<EncodableList>(list_return_value->at(0)); on_success(return_value); } } else { on_error(CreateConnectionError(channel_name)); } }); } void FlutterIntegrationCoreApi::EchoMap( const EncodableMap& a_map_arg, std::function<void(const EncodableMap&)>&& on_success, std::function<void(const FlutterError&)>&& on_error) { const std::string channel_name = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi." "echoMap"; BasicMessageChannel<> channel(binary_messenger_, channel_name, &GetCodec()); EncodableValue encoded_api_arguments = EncodableValue(EncodableList{ EncodableValue(a_map_arg), }); channel.Send( encoded_api_arguments, [channel_name, on_success = std::move(on_success), on_error = std::move(on_error)]( const uint8_t* reply, size_t reply_size) { std::unique_ptr<EncodableValue> response = GetCodec().DecodeMessage(reply, reply_size); const auto& encodable_return_value = *response; const auto* list_return_value = std::get_if<EncodableList>(&encodable_return_value); if (list_return_value) { if (list_return_value->size() > 1) { on_error( FlutterError(std::get<std::string>(list_return_value->at(0)), std::get<std::string>(list_return_value->at(1)), list_return_value->at(2))); } else { const auto& return_value = std::get<EncodableMap>(list_return_value->at(0)); on_success(return_value); } } else { on_error(CreateConnectionError(channel_name)); } }); } void FlutterIntegrationCoreApi::EchoEnum( const AnEnum& an_enum_arg, std::function<void(const AnEnum&)>&& on_success, std::function<void(const FlutterError&)>&& on_error) { const std::string channel_name = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi." "echoEnum"; BasicMessageChannel<> channel(binary_messenger_, channel_name, &GetCodec()); EncodableValue encoded_api_arguments = EncodableValue(EncodableList{ EncodableValue((int)an_enum_arg), }); channel.Send( encoded_api_arguments, [channel_name, on_success = std::move(on_success), on_error = std::move(on_error)]( const uint8_t* reply, size_t reply_size) { std::unique_ptr<EncodableValue> response = GetCodec().DecodeMessage(reply, reply_size); const auto& encodable_return_value = *response; const auto* list_return_value = std::get_if<EncodableList>(&encodable_return_value); if (list_return_value) { if (list_return_value->size() > 1) { on_error( FlutterError(std::get<std::string>(list_return_value->at(0)), std::get<std::string>(list_return_value->at(1)), list_return_value->at(2))); } else { const AnEnum& return_value = (AnEnum)list_return_value->at(0).LongValue(); on_success(return_value); } } else { on_error(CreateConnectionError(channel_name)); } }); } void FlutterIntegrationCoreApi::EchoNullableBool( const bool* a_bool_arg, std::function<void(const bool*)>&& on_success, std::function<void(const FlutterError&)>&& on_error) { const std::string channel_name = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi." "echoNullableBool"; BasicMessageChannel<> channel(binary_messenger_, channel_name, &GetCodec()); EncodableValue encoded_api_arguments = EncodableValue(EncodableList{ a_bool_arg ? EncodableValue(*a_bool_arg) : EncodableValue(), }); channel.Send(encoded_api_arguments, [channel_name, on_success = std::move(on_success), on_error = std::move(on_error)]( const uint8_t* reply, size_t reply_size) { std::unique_ptr<EncodableValue> response = GetCodec().DecodeMessage(reply, reply_size); const auto& encodable_return_value = *response; const auto* list_return_value = std::get_if<EncodableList>(&encodable_return_value); if (list_return_value) { if (list_return_value->size() > 1) { on_error(FlutterError(std::get<std::string>(list_return_value->at(0)), std::get<std::string>(list_return_value->at(1)), list_return_value->at(2))); } else { const auto* return_value = std::get_if<bool>(&list_return_value->at(0)); on_success(return_value); } } else { on_error(CreateConnectionError(channel_name)); } }); } void FlutterIntegrationCoreApi::EchoNullableInt( const int64_t* an_int_arg, std::function<void(const int64_t*)>&& on_success, std::function<void(const FlutterError&)>&& on_error) { const std::string channel_name = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi." "echoNullableInt"; BasicMessageChannel<> channel(binary_messenger_, channel_name, &GetCodec()); EncodableValue encoded_api_arguments = EncodableValue(EncodableList{ an_int_arg ? EncodableValue(*an_int_arg) : EncodableValue(), }); channel.Send(encoded_api_arguments, [channel_name, on_success = std::move(on_success), on_error = std::move(on_error)]( const uint8_t* reply, size_t reply_size) { std::unique_ptr<EncodableValue> response = GetCodec().DecodeMessage(reply, reply_size); const auto& encodable_return_value = *response; const auto* list_return_value = std::get_if<EncodableList>(&encodable_return_value); if (list_return_value) { if (list_return_value->size() > 1) { on_error(FlutterError(std::get<std::string>(list_return_value->at(0)), std::get<std::string>(list_return_value->at(1)), list_return_value->at(2))); } else { const int64_t return_value_value = list_return_value->at(0).IsNull() ? 0 : list_return_value->at(0).LongValue(); const auto* return_value = list_return_value->at(0).IsNull() ? nullptr : &return_value_value; on_success(return_value); } } else { on_error(CreateConnectionError(channel_name)); } }); } void FlutterIntegrationCoreApi::EchoNullableDouble( const double* a_double_arg, std::function<void(const double*)>&& on_success, std::function<void(const FlutterError&)>&& on_error) { const std::string channel_name = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi." "echoNullableDouble"; BasicMessageChannel<> channel(binary_messenger_, channel_name, &GetCodec()); EncodableValue encoded_api_arguments = EncodableValue(EncodableList{ a_double_arg ? EncodableValue(*a_double_arg) : EncodableValue(), }); channel.Send( encoded_api_arguments, [channel_name, on_success = std::move(on_success), on_error = std::move(on_error)]( const uint8_t* reply, size_t reply_size) { std::unique_ptr<EncodableValue> response = GetCodec().DecodeMessage(reply, reply_size); const auto& encodable_return_value = *response; const auto* list_return_value = std::get_if<EncodableList>(&encodable_return_value); if (list_return_value) { if (list_return_value->size() > 1) { on_error( FlutterError(std::get<std::string>(list_return_value->at(0)), std::get<std::string>(list_return_value->at(1)), list_return_value->at(2))); } else { const auto* return_value = std::get_if<double>(&list_return_value->at(0)); on_success(return_value); } } else { on_error(CreateConnectionError(channel_name)); } }); } void FlutterIntegrationCoreApi::EchoNullableString( const std::string* a_string_arg, std::function<void(const std::string*)>&& on_success, std::function<void(const FlutterError&)>&& on_error) { const std::string channel_name = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi." "echoNullableString"; BasicMessageChannel<> channel(binary_messenger_, channel_name, &GetCodec()); EncodableValue encoded_api_arguments = EncodableValue(EncodableList{ a_string_arg ? EncodableValue(*a_string_arg) : EncodableValue(), }); channel.Send( encoded_api_arguments, [channel_name, on_success = std::move(on_success), on_error = std::move(on_error)]( const uint8_t* reply, size_t reply_size) { std::unique_ptr<EncodableValue> response = GetCodec().DecodeMessage(reply, reply_size); const auto& encodable_return_value = *response; const auto* list_return_value = std::get_if<EncodableList>(&encodable_return_value); if (list_return_value) { if (list_return_value->size() > 1) { on_error( FlutterError(std::get<std::string>(list_return_value->at(0)), std::get<std::string>(list_return_value->at(1)), list_return_value->at(2))); } else { const auto* return_value = std::get_if<std::string>(&list_return_value->at(0)); on_success(return_value); } } else { on_error(CreateConnectionError(channel_name)); } }); } void FlutterIntegrationCoreApi::EchoNullableUint8List( const std::vector<uint8_t>* a_list_arg, std::function<void(const std::vector<uint8_t>*)>&& on_success, std::function<void(const FlutterError&)>&& on_error) { const std::string channel_name = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi." "echoNullableUint8List"; BasicMessageChannel<> channel(binary_messenger_, channel_name, &GetCodec()); EncodableValue encoded_api_arguments = EncodableValue(EncodableList{ a_list_arg ? EncodableValue(*a_list_arg) : EncodableValue(), }); channel.Send( encoded_api_arguments, [channel_name, on_success = std::move(on_success), on_error = std::move(on_error)]( const uint8_t* reply, size_t reply_size) { std::unique_ptr<EncodableValue> response = GetCodec().DecodeMessage(reply, reply_size); const auto& encodable_return_value = *response; const auto* list_return_value = std::get_if<EncodableList>(&encodable_return_value); if (list_return_value) { if (list_return_value->size() > 1) { on_error( FlutterError(std::get<std::string>(list_return_value->at(0)), std::get<std::string>(list_return_value->at(1)), list_return_value->at(2))); } else { const auto* return_value = std::get_if<std::vector<uint8_t>>(&list_return_value->at(0)); on_success(return_value); } } else { on_error(CreateConnectionError(channel_name)); } }); } void FlutterIntegrationCoreApi::EchoNullableList( const EncodableList* a_list_arg, std::function<void(const EncodableList*)>&& on_success, std::function<void(const FlutterError&)>&& on_error) { const std::string channel_name = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi." "echoNullableList"; BasicMessageChannel<> channel(binary_messenger_, channel_name, &GetCodec()); EncodableValue encoded_api_arguments = EncodableValue(EncodableList{ a_list_arg ? EncodableValue(*a_list_arg) : EncodableValue(), }); channel.Send( encoded_api_arguments, [channel_name, on_success = std::move(on_success), on_error = std::move(on_error)]( const uint8_t* reply, size_t reply_size) { std::unique_ptr<EncodableValue> response = GetCodec().DecodeMessage(reply, reply_size); const auto& encodable_return_value = *response; const auto* list_return_value = std::get_if<EncodableList>(&encodable_return_value); if (list_return_value) { if (list_return_value->size() > 1) { on_error( FlutterError(std::get<std::string>(list_return_value->at(0)), std::get<std::string>(list_return_value->at(1)), list_return_value->at(2))); } else { const auto* return_value = std::get_if<EncodableList>(&list_return_value->at(0)); on_success(return_value); } } else { on_error(CreateConnectionError(channel_name)); } }); } void FlutterIntegrationCoreApi::EchoNullableMap( const EncodableMap* a_map_arg, std::function<void(const EncodableMap*)>&& on_success, std::function<void(const FlutterError&)>&& on_error) { const std::string channel_name = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi." "echoNullableMap"; BasicMessageChannel<> channel(binary_messenger_, channel_name, &GetCodec()); EncodableValue encoded_api_arguments = EncodableValue(EncodableList{ a_map_arg ? EncodableValue(*a_map_arg) : EncodableValue(), }); channel.Send( encoded_api_arguments, [channel_name, on_success = std::move(on_success), on_error = std::move(on_error)]( const uint8_t* reply, size_t reply_size) { std::unique_ptr<EncodableValue> response = GetCodec().DecodeMessage(reply, reply_size); const auto& encodable_return_value = *response; const auto* list_return_value = std::get_if<EncodableList>(&encodable_return_value); if (list_return_value) { if (list_return_value->size() > 1) { on_error( FlutterError(std::get<std::string>(list_return_value->at(0)), std::get<std::string>(list_return_value->at(1)), list_return_value->at(2))); } else { const auto* return_value = std::get_if<EncodableMap>(&list_return_value->at(0)); on_success(return_value); } } else { on_error(CreateConnectionError(channel_name)); } }); } void FlutterIntegrationCoreApi::EchoNullableEnum( const AnEnum* an_enum_arg, std::function<void(const AnEnum*)>&& on_success, std::function<void(const FlutterError&)>&& on_error) { const std::string channel_name = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi." "echoNullableEnum"; BasicMessageChannel<> channel(binary_messenger_, channel_name, &GetCodec()); EncodableValue encoded_api_arguments = EncodableValue(EncodableList{ an_enum_arg ? EncodableValue((int)(*an_enum_arg)) : EncodableValue(), }); channel.Send(encoded_api_arguments, [channel_name, on_success = std::move(on_success), on_error = std::move(on_error)]( const uint8_t* reply, size_t reply_size) { std::unique_ptr<EncodableValue> response = GetCodec().DecodeMessage(reply, reply_size); const auto& encodable_return_value = *response; const auto* list_return_value = std::get_if<EncodableList>(&encodable_return_value); if (list_return_value) { if (list_return_value->size() > 1) { on_error(FlutterError(std::get<std::string>(list_return_value->at(0)), std::get<std::string>(list_return_value->at(1)), list_return_value->at(2))); } else { const int64_t return_value_value = list_return_value->at(0).IsNull() ? 0 : list_return_value->at(0).LongValue(); const AnEnum enum_return_value = (AnEnum)return_value_value; const auto* return_value = list_return_value->at(0).IsNull() ? nullptr : &enum_return_value; on_success(return_value); } } else { on_error(CreateConnectionError(channel_name)); } }); } void FlutterIntegrationCoreApi::NoopAsync( std::function<void(void)>&& on_success, std::function<void(const FlutterError&)>&& on_error) { const std::string channel_name = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi." "noopAsync"; BasicMessageChannel<> channel(binary_messenger_, channel_name, &GetCodec()); EncodableValue encoded_api_arguments = EncodableValue(); channel.Send( encoded_api_arguments, [channel_name, on_success = std::move(on_success), on_error = std::move(on_error)]( const uint8_t* reply, size_t reply_size) { std::unique_ptr<EncodableValue> response = GetCodec().DecodeMessage(reply, reply_size); const auto& encodable_return_value = *response; const auto* list_return_value = std::get_if<EncodableList>(&encodable_return_value); if (list_return_value) { if (list_return_value->size() > 1) { on_error( FlutterError(std::get<std::string>(list_return_value->at(0)), std::get<std::string>(list_return_value->at(1)), list_return_value->at(2))); } else { on_success(); } } else { on_error(CreateConnectionError(channel_name)); } }); } void FlutterIntegrationCoreApi::EchoAsyncString( const std::string& a_string_arg, std::function<void(const std::string&)>&& on_success, std::function<void(const FlutterError&)>&& on_error) { const std::string channel_name = "dev.flutter.pigeon.pigeon_integration_tests.FlutterIntegrationCoreApi." "echoAsyncString"; BasicMessageChannel<> channel(binary_messenger_, channel_name, &GetCodec()); EncodableValue encoded_api_arguments = EncodableValue(EncodableList{ EncodableValue(a_string_arg), }); channel.Send( encoded_api_arguments, [channel_name, on_success = std::move(on_success), on_error = std::move(on_error)]( const uint8_t* reply, size_t reply_size) { std::unique_ptr<EncodableValue> response = GetCodec().DecodeMessage(reply, reply_size); const auto& encodable_return_value = *response; const auto* list_return_value = std::get_if<EncodableList>(&encodable_return_value); if (list_return_value) { if (list_return_value->size() > 1) { on_error( FlutterError(std::get<std::string>(list_return_value->at(0)), std::get<std::string>(list_return_value->at(1)), list_return_value->at(2))); } else { const auto& return_value = std::get<std::string>(list_return_value->at(0)); on_success(return_value); } } else { on_error(CreateConnectionError(channel_name)); } }); } /// The codec used by HostTrivialApi. const flutter::StandardMessageCodec& HostTrivialApi::GetCodec() { return flutter::StandardMessageCodec::GetInstance( &flutter::StandardCodecSerializer::GetInstance()); } // Sets up an instance of `HostTrivialApi` to handle messages through the // `binary_messenger`. void HostTrivialApi::SetUp(flutter::BinaryMessenger* binary_messenger, HostTrivialApi* api) { { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostTrivialApi.noop", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { std::optional<FlutterError> output = api->Noop(); if (output.has_value()) { reply(WrapError(output.value())); return; } EncodableList wrapped; wrapped.push_back(EncodableValue()); reply(EncodableValue(std::move(wrapped))); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } } EncodableValue HostTrivialApi::WrapError(std::string_view error_message) { return EncodableValue( EncodableList{EncodableValue(std::string(error_message)), EncodableValue("Error"), EncodableValue()}); } EncodableValue HostTrivialApi::WrapError(const FlutterError& error) { return EncodableValue(EncodableList{EncodableValue(error.code()), EncodableValue(error.message()), error.details()}); } /// The codec used by HostSmallApi. const flutter::StandardMessageCodec& HostSmallApi::GetCodec() { return flutter::StandardMessageCodec::GetInstance( &flutter::StandardCodecSerializer::GetInstance()); } // Sets up an instance of `HostSmallApi` to handle messages through the // `binary_messenger`. void HostSmallApi::SetUp(flutter::BinaryMessenger* binary_messenger, HostSmallApi* api) { { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostSmallApi.echo", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { const auto& args = std::get<EncodableList>(message); const auto& encodable_a_string_arg = args.at(0); if (encodable_a_string_arg.IsNull()) { reply(WrapError("a_string_arg unexpectedly null.")); return; } const auto& a_string_arg = std::get<std::string>(encodable_a_string_arg); api->Echo(a_string_arg, [reply](ErrorOr<std::string>&& output) { if (output.has_error()) { reply(WrapError(output.error())); return; } EncodableList wrapped; wrapped.push_back( EncodableValue(std::move(output).TakeValue())); reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } { BasicMessageChannel<> channel( binary_messenger, "dev.flutter.pigeon.pigeon_integration_tests.HostSmallApi.voidVoid", &GetCodec()); if (api != nullptr) { channel.SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { api->VoidVoid([reply](std::optional<FlutterError>&& output) { if (output.has_value()) { reply(WrapError(output.value())); return; } EncodableList wrapped; wrapped.push_back(EncodableValue()); reply(EncodableValue(std::move(wrapped))); }); } catch (const std::exception& exception) { reply(WrapError(exception.what())); } }); } else { channel.SetMessageHandler(nullptr); } } } EncodableValue HostSmallApi::WrapError(std::string_view error_message) { return EncodableValue( EncodableList{EncodableValue(std::string(error_message)), EncodableValue("Error"), EncodableValue()}); } EncodableValue HostSmallApi::WrapError(const FlutterError& error) { return EncodableValue(EncodableList{EncodableValue(error.code()), EncodableValue(error.message()), error.details()}); } FlutterSmallApiCodecSerializer::FlutterSmallApiCodecSerializer() {} EncodableValue FlutterSmallApiCodecSerializer::ReadValueOfType( uint8_t type, flutter::ByteStreamReader* stream) const { switch (type) { case 128: return CustomEncodableValue(TestMessage::FromEncodableList( std::get<EncodableList>(ReadValue(stream)))); default: return flutter::StandardCodecSerializer::ReadValueOfType(type, stream); } } void FlutterSmallApiCodecSerializer::WriteValue( const EncodableValue& value, flutter::ByteStreamWriter* stream) const { if (const CustomEncodableValue* custom_value = std::get_if<CustomEncodableValue>(&value)) { if (custom_value->type() == typeid(TestMessage)) { stream->WriteByte(128); WriteValue( EncodableValue( std::any_cast<TestMessage>(*custom_value).ToEncodableList()), stream); return; } } flutter::StandardCodecSerializer::WriteValue(value, stream); } // Generated class from Pigeon that represents Flutter messages that can be // called from C++. FlutterSmallApi::FlutterSmallApi(flutter::BinaryMessenger* binary_messenger) : binary_messenger_(binary_messenger) {} const flutter::StandardMessageCodec& FlutterSmallApi::GetCodec() { return flutter::StandardMessageCodec::GetInstance( &FlutterSmallApiCodecSerializer::GetInstance()); } void FlutterSmallApi::EchoWrappedList( const TestMessage& msg_arg, std::function<void(const TestMessage&)>&& on_success, std::function<void(const FlutterError&)>&& on_error) { const std::string channel_name = "dev.flutter.pigeon.pigeon_integration_tests.FlutterSmallApi." "echoWrappedList"; BasicMessageChannel<> channel(binary_messenger_, channel_name, &GetCodec()); EncodableValue encoded_api_arguments = EncodableValue(EncodableList{ CustomEncodableValue(msg_arg), }); channel.Send( encoded_api_arguments, [channel_name, on_success = std::move(on_success), on_error = std::move(on_error)]( const uint8_t* reply, size_t reply_size) { std::unique_ptr<EncodableValue> response = GetCodec().DecodeMessage(reply, reply_size); const auto& encodable_return_value = *response; const auto* list_return_value = std::get_if<EncodableList>(&encodable_return_value); if (list_return_value) { if (list_return_value->size() > 1) { on_error( FlutterError(std::get<std::string>(list_return_value->at(0)), std::get<std::string>(list_return_value->at(1)), list_return_value->at(2))); } else { const auto& return_value = std::any_cast<const TestMessage&>( std::get<CustomEncodableValue>(list_return_value->at(0))); on_success(return_value); } } else { on_error(CreateConnectionError(channel_name)); } }); } void FlutterSmallApi::EchoString( const std::string& a_string_arg, std::function<void(const std::string&)>&& on_success, std::function<void(const FlutterError&)>&& on_error) { const std::string channel_name = "dev.flutter.pigeon.pigeon_integration_tests.FlutterSmallApi.echoString"; BasicMessageChannel<> channel(binary_messenger_, channel_name, &GetCodec()); EncodableValue encoded_api_arguments = EncodableValue(EncodableList{ EncodableValue(a_string_arg), }); channel.Send( encoded_api_arguments, [channel_name, on_success = std::move(on_success), on_error = std::move(on_error)]( const uint8_t* reply, size_t reply_size) { std::unique_ptr<EncodableValue> response = GetCodec().DecodeMessage(reply, reply_size); const auto& encodable_return_value = *response; const auto* list_return_value = std::get_if<EncodableList>(&encodable_return_value); if (list_return_value) { if (list_return_value->size() > 1) { on_error( FlutterError(std::get<std::string>(list_return_value->at(0)), std::get<std::string>(list_return_value->at(1)), list_return_value->at(2))); } else { const auto& return_value = std::get<std::string>(list_return_value->at(0)); on_success(return_value); } } else { on_error(CreateConnectionError(channel_name)); } }); } } // namespace core_tests_pigeontest
packages/packages/pigeon/platform_tests/test_plugin/windows/pigeon/core_tests.gen.cpp/0
{ "file_path": "packages/packages/pigeon/platform_tests/test_plugin/windows/pigeon/core_tests.gen.cpp", "repo_id": "packages", "token_count": 102837 }
1,062
// Copyright 2013 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:pigeon/ast.dart'; import 'package:pigeon/ast_generator.dart'; import 'package:test/test.dart'; void main() { test('gen one class', () { final Class classDefinition = Class( name: 'Foobar', fields: <NamedType>[ NamedType( type: const TypeDeclaration( baseName: 'dataType1', isNullable: true, ), name: 'field1'), ], ); final Root root = Root( apis: <Api>[], classes: <Class>[classDefinition], enums: <Enum>[], ); final StringBuffer sink = StringBuffer(); generateAst(root, sink); final String code = sink.toString(); expect(code, contains('Foobar')); expect(code, contains('dataType1')); expect(code, contains('field1')); }); }
packages/packages/pigeon/test/ast_generator_test.dart/0
{ "file_path": "packages/packages/pigeon/test/ast_generator_test.dart", "repo_id": "packages", "token_count": 395 }
1,063
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io' show Platform; import 'package:path/path.dart' as p; import 'package:pigeon/generator_tools.dart'; import 'package:pigeon/pigeon.dart'; import 'process_utils.dart'; enum GeneratorLanguage { cpp, dart, java, kotlin, objc, swift, } // A map of pigeons/ files to the languages that they can't yet be generated // for due to limitations of that generator. const Map<String, Set<GeneratorLanguage>> _unsupportedFiles = <String, Set<GeneratorLanguage>>{}; String _snakeToPascalCase(String snake) { final List<String> parts = snake.split('_'); return parts .map((String part) => part.substring(0, 1).toUpperCase() + part.substring(1)) .join(); } // Remaps some file names for Java output, since the filename on Java will be // the name of the generated top-level class. In some cases this is necessary // (e.g., "list", which collides with the Java List class in tests), and in // others it is just preserving previous behavior from the earlier Bash version // of the generation to minimize churn during the migration. // TODO(stuartmorgan): Remove the need for this when addressing // https://github.com/flutter/flutter/issues/115168. String _javaFilenameForName(String inputName) { const Map<String, String> specialCases = <String, String>{ 'message': 'MessagePigeon', }; return specialCases[inputName] ?? _snakeToPascalCase(inputName); } Future<int> generateExamplePigeons() async { return runPigeon( input: './example/app/pigeons/messages.dart', basePath: './example/app', suppressVersion: true, ); } Future<int> generateTestPigeons({required String baseDir}) async { // TODO(stuartmorgan): Make this dynamic rather than hard-coded. Or eliminate // it entirely; see https://github.com/flutter/flutter/issues/115169. const List<String> inputs = <String>[ 'background_platform_channels', 'core_tests', 'enum', 'flutter_unittests', // Only for Dart unit tests in shared_test_plugin_code 'message', 'multiple_arity', 'non_null_fields', 'null_fields', 'nullable_returns', 'primitive', 'proxy_api_tests', ]; final String outputBase = p.join(baseDir, 'platform_tests', 'test_plugin'); final String alternateOutputBase = p.join(baseDir, 'platform_tests', 'alternate_language_test_plugin'); final String sharedDartOutputBase = p.join(baseDir, 'platform_tests', 'shared_test_plugin_code'); for (final String input in inputs) { final String pascalCaseName = _snakeToPascalCase(input); final Set<GeneratorLanguage> skipLanguages = _unsupportedFiles[input] ?? <GeneratorLanguage>{}; final bool kotlinErrorClassGenerationTestFiles = input == 'core_tests' || input == 'background_platform_channels'; final String kotlinErrorName = kotlinErrorClassGenerationTestFiles ? 'FlutterError' : '${pascalCaseName}Error'; // Generate the default language test plugin output. int generateCode = await runPigeon( input: './pigeons/$input.dart', dartOut: '$sharedDartOutputBase/lib/src/generated/$input.gen.dart', // Android kotlinOut: skipLanguages.contains(GeneratorLanguage.kotlin) ? null : '$outputBase/android/src/main/kotlin/com/example/test_plugin/$pascalCaseName.gen.kt', kotlinPackage: 'com.example.test_plugin', kotlinErrorClassName: kotlinErrorName, kotlinIncludeErrorClass: input != 'core_tests', // iOS swiftOut: skipLanguages.contains(GeneratorLanguage.swift) ? null : '$outputBase/ios/Classes/$pascalCaseName.gen.swift', // Windows cppHeaderOut: skipLanguages.contains(GeneratorLanguage.cpp) ? null : '$outputBase/windows/pigeon/$input.gen.h', cppSourceOut: skipLanguages.contains(GeneratorLanguage.cpp) ? null : '$outputBase/windows/pigeon/$input.gen.cpp', cppNamespace: '${input}_pigeontest', suppressVersion: true, dartPackageName: 'pigeon_integration_tests', ); if (generateCode != 0) { return generateCode; } // macOS has to be run as a separate generation, since currently Pigeon // doesn't have a way to output separate macOS and iOS Swift output in a // single invocation. generateCode = await runPigeon( input: './pigeons/$input.dart', swiftOut: skipLanguages.contains(GeneratorLanguage.swift) ? null : '$outputBase/macos/Classes/$pascalCaseName.gen.swift', suppressVersion: true, dartPackageName: 'pigeon_integration_tests', ); if (generateCode != 0) { return generateCode; } // Generate the alternate language test plugin output. generateCode = await runPigeon( input: './pigeons/$input.dart', // Android // This doesn't use the '.gen' suffix since Java has strict file naming // rules. javaOut: skipLanguages.contains(GeneratorLanguage.java) ? null : '$alternateOutputBase/android/src/main/java/com/example/' 'alternate_language_test_plugin/${_javaFilenameForName(input)}.java', javaPackage: 'com.example.alternate_language_test_plugin', // iOS objcHeaderOut: skipLanguages.contains(GeneratorLanguage.objc) ? null : '$alternateOutputBase/ios/Classes/$pascalCaseName.gen.h', objcSourceOut: skipLanguages.contains(GeneratorLanguage.objc) ? null : '$alternateOutputBase/ios/Classes/$pascalCaseName.gen.m', objcPrefix: input == 'core_tests' ? 'FLT' : '', suppressVersion: true, dartPackageName: 'pigeon_integration_tests', ); if (generateCode != 0) { return generateCode; } // macOS has to be run as a separate generation, since currently Pigeon // doesn't have a way to output separate macOS and iOS Swift output in a // single invocation. generateCode = await runPigeon( input: './pigeons/$input.dart', objcHeaderOut: skipLanguages.contains(GeneratorLanguage.objc) ? null : '$alternateOutputBase/macos/Classes/$pascalCaseName.gen.h', objcSourceOut: skipLanguages.contains(GeneratorLanguage.objc) ? null : '$alternateOutputBase/macos/Classes/$pascalCaseName.gen.m', suppressVersion: true, dartPackageName: 'pigeon_integration_tests', ); if (generateCode != 0) { return generateCode; } } return 0; } Future<int> runPigeon({ required String input, String? kotlinOut, String? kotlinPackage, String? kotlinErrorClassName, bool kotlinIncludeErrorClass = true, String? swiftOut, String? cppHeaderOut, String? cppSourceOut, String? cppNamespace, String? dartOut, String? dartTestOut, String? javaOut, String? javaPackage, String? objcHeaderOut, String? objcSourceOut, String objcPrefix = '', bool suppressVersion = false, String copyrightHeader = './copyright_header.txt', String? basePath, String? dartPackageName, }) async { // Temporarily suppress the version output via the global flag if requested. // This is done because having the version in all the generated test output // means every version bump updates every test file, which is problematic in // review. For files where CI validates that this generation is up to date, // having the version in these files isn't useful. // TODO(stuartmorgan): Remove the option and do this unconditionally once // all the checked in files are being validated; currently only // generatePigeons is being checked in CI. final bool originalWarningSetting = includeVersionInGeneratedWarning; if (suppressVersion) { includeVersionInGeneratedWarning = false; } final int result = await Pigeon.runWithOptions(PigeonOptions( input: input, copyrightHeader: copyrightHeader, dartOut: dartOut, dartTestOut: dartTestOut, dartOptions: const DartOptions(), cppHeaderOut: cppHeaderOut, cppSourceOut: cppSourceOut, cppOptions: CppOptions(namespace: cppNamespace), javaOut: javaOut, javaOptions: JavaOptions(package: javaPackage), kotlinOut: kotlinOut, kotlinOptions: KotlinOptions( package: kotlinPackage, errorClassName: kotlinErrorClassName, includeErrorClass: kotlinIncludeErrorClass, ), objcHeaderOut: objcHeaderOut, objcSourceOut: objcSourceOut, objcOptions: ObjcOptions(prefix: objcPrefix), swiftOut: swiftOut, swiftOptions: const SwiftOptions(), basePath: basePath, dartPackageName: dartPackageName, )); includeVersionInGeneratedWarning = originalWarningSetting; return result; } /// Runs the repository tooling's format command on this package. /// /// This is intended for formatting generated output, but since there's no /// way to filter to specific files in with the repo tooling it runs over the /// entire package. Future<int> formatAllFiles({ required String repositoryRoot, Set<GeneratorLanguage> languages = const <GeneratorLanguage>{ GeneratorLanguage.cpp, GeneratorLanguage.dart, GeneratorLanguage.java, GeneratorLanguage.kotlin, GeneratorLanguage.objc, GeneratorLanguage.swift, }, }) { final String dartCommand = Platform.isWindows ? 'dart.exe' : 'dart'; return runProcess( dartCommand, <String>[ 'run', 'script/tool/bin/flutter_plugin_tools.dart', 'format', '--packages=pigeon', if (languages.contains(GeneratorLanguage.cpp) || languages.contains(GeneratorLanguage.objc)) '--clang-format' else '--no-clang-format', if (languages.contains(GeneratorLanguage.java)) '--java' else '--no-java', if (languages.contains(GeneratorLanguage.dart)) '--dart' else '--no-dart', if (languages.contains(GeneratorLanguage.kotlin)) '--kotlin' else '--no-kotlin', if (languages.contains(GeneratorLanguage.swift)) '--swift' else '--no-swift', ], workingDirectory: repositoryRoot, streamOutput: false, logFailure: true); }
packages/packages/pigeon/tool/shared/generation.dart/0
{ "file_path": "packages/packages/pigeon/tool/shared/generation.dart", "repo_id": "packages", "token_count": 3850 }
1,064
pluginManagement { def flutterSdkPath = { def properties = new Properties() file("local.properties").withInputStream { properties.load(it) } def flutterSdkPath = properties.getProperty("flutter.sdk") assert flutterSdkPath != null, "flutter.sdk not set in local.properties" return flutterSdkPath } settings.ext.flutterSdkPath = flutterSdkPath() includeBuild("${settings.ext.flutterSdkPath}/packages/flutter_tools/gradle") plugins { id "dev.flutter.flutter-gradle-plugin" version "1.0.0" apply false } } include ":app" // See https://github.com/flutter/flutter/wiki/Plugins-and-Packages-repository-structure#gradle-structure for more info. buildscript { repositories { maven { url "https://plugins.gradle.org/m2/" } } dependencies { classpath "gradle.plugin.com.google.cloud.artifactregistry:artifactregistry-gradle-plugin:2.2.1" } } apply plugin: "com.google.cloud.artifactregistry.gradle-plugin"
packages/packages/platform/example/android/settings.gradle/0
{ "file_path": "packages/packages/platform/example/android/settings.gradle", "repo_id": "packages", "token_count": 386 }
1,065
#include "ephemeral/Flutter-Generated.xcconfig"
packages/packages/platform/example/macos/Flutter/Flutter-Debug.xcconfig/0
{ "file_path": "packages/packages/platform/example/macos/Flutter/Flutter-Debug.xcconfig", "repo_id": "packages", "token_count": 19 }
1,066
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io' as io; import 'package:platform/platform.dart'; import 'package:test/test.dart'; void _expectPlatformsEqual(Platform actual, Platform expected) { expect(actual.numberOfProcessors, expected.numberOfProcessors); expect(actual.pathSeparator, expected.pathSeparator); expect(actual.operatingSystem, expected.operatingSystem); expect(actual.operatingSystemVersion, expected.operatingSystemVersion); expect(actual.localHostname, expected.localHostname); expect(actual.environment, expected.environment); expect(actual.executable, expected.executable); expect(actual.resolvedExecutable, expected.resolvedExecutable); expect(actual.script, expected.script); expect(actual.executableArguments, expected.executableArguments); expect(actual.packageConfig, expected.packageConfig); expect(actual.version, expected.version); expect(actual.localeName, expected.localeName); } void main() { group('FakePlatform', () { late FakePlatform fake; late LocalPlatform local; setUp(() { fake = FakePlatform(); local = const LocalPlatform(); }); group('fromPlatform', () { setUp(() { fake = FakePlatform.fromPlatform(local); }); test('copiesAllProperties', () { _expectPlatformsEqual(fake, local); }); test('convertsPropertiesToMutable', () { final String key = fake.environment.keys.first; expect(fake.environment[key], local.environment[key]); fake.environment[key] = 'FAKE'; expect(fake.environment[key], 'FAKE'); expect( fake.executableArguments.length, local.executableArguments.length); fake.executableArguments.add('ARG'); expect(fake.executableArguments.last, 'ARG'); }); }); group('copyWith', () { setUp(() { fake = FakePlatform.fromPlatform(local); }); test('overrides a value, but leaves others intact', () { final FakePlatform copy = fake.copyWith( numberOfProcessors: -1, ); expect(copy.numberOfProcessors, equals(-1)); expect(copy.pathSeparator, local.pathSeparator); expect(copy.operatingSystem, local.operatingSystem); expect(copy.operatingSystemVersion, local.operatingSystemVersion); expect(copy.localHostname, local.localHostname); expect(copy.environment, local.environment); expect(copy.executable, local.executable); expect(copy.resolvedExecutable, local.resolvedExecutable); expect(copy.script, local.script); expect(copy.executableArguments, local.executableArguments); expect(copy.packageConfig, local.packageConfig); expect(copy.version, local.version); expect(copy.localeName, local.localeName); }); test('can override all values', () { fake = FakePlatform( numberOfProcessors: 8, pathSeparator: ':', operatingSystem: 'fake', operatingSystemVersion: '0.1.0', localHostname: 'host', environment: <String, String>{'PATH': '.'}, executable: 'executable', resolvedExecutable: '/executable', script: Uri.file('/platform/test/fake_platform_test.dart'), executableArguments: <String>['scriptarg'], version: '0.1.1', stdinSupportsAnsi: false, stdoutSupportsAnsi: true, localeName: 'local', ); final FakePlatform copy = fake.copyWith( numberOfProcessors: local.numberOfProcessors, pathSeparator: local.pathSeparator, operatingSystem: local.operatingSystem, operatingSystemVersion: local.operatingSystemVersion, localHostname: local.localHostname, environment: local.environment, executable: local.executable, resolvedExecutable: local.resolvedExecutable, script: local.script, executableArguments: local.executableArguments, packageConfig: local.packageConfig, version: local.version, stdinSupportsAnsi: local.stdinSupportsAnsi, stdoutSupportsAnsi: local.stdoutSupportsAnsi, localeName: local.localeName, ); _expectPlatformsEqual(copy, local); }); }); group('json', () { test('fromJson', () { final String json = io.File('test/platform.json').readAsStringSync(); fake = FakePlatform.fromJson(json); expect(fake.numberOfProcessors, 8); expect(fake.pathSeparator, '/'); expect(fake.operatingSystem, 'macos'); expect(fake.operatingSystemVersion, '10.14.5'); expect(fake.localHostname, 'platform.test.org'); expect(fake.environment, <String, String>{ 'PATH': '/bin', 'PWD': '/platform', }); expect(fake.executable, '/bin/dart'); expect(fake.resolvedExecutable, '/bin/dart'); expect(fake.script, Uri.file('/platform/test/fake_platform_test.dart')); expect(fake.executableArguments, <String>['--checked']); expect(fake.packageConfig, null); expect(fake.version, '1.22.0'); expect(fake.localeName, 'de/de'); }); test('fromJsonToJson', () { fake = FakePlatform.fromJson(local.toJson()); _expectPlatformsEqual(fake, local); }); }); }); test('Throws when unset non-null values are read', () { final FakePlatform platform = FakePlatform(); expect(() => platform.numberOfProcessors, throwsA(isStateError)); expect(() => platform.pathSeparator, throwsA(isStateError)); expect(() => platform.operatingSystem, throwsA(isStateError)); expect(() => platform.operatingSystemVersion, throwsA(isStateError)); expect(() => platform.localHostname, throwsA(isStateError)); expect(() => platform.environment, throwsA(isStateError)); expect(() => platform.executable, throwsA(isStateError)); expect(() => platform.resolvedExecutable, throwsA(isStateError)); expect(() => platform.script, throwsA(isStateError)); expect(() => platform.executableArguments, throwsA(isStateError)); expect(() => platform.version, throwsA(isStateError)); expect(() => platform.localeName, throwsA(isStateError)); }); }
packages/packages/platform/test/fake_platform_test.dart/0
{ "file_path": "packages/packages/platform/test/fake_platform_test.dart", "repo_id": "packages", "token_count": 2484 }
1,067
# pointer_interceptor | | iOS | Web | |-------------|---------|-----| | **Support** | iOS 12+ | Any | `PointerInterceptor` is a widget that prevents mouse events from being captured by an underlying [`HtmlElementView`](https://api.flutter.dev/flutter/widgets/HtmlElementView-class.html) in web, or an underlying [`PlatformView`](https://api.flutter.dev/flutter/widgets/PlatformViewLink-class.html) on iOS. ## What is the problem? When overlaying Flutter widgets on top of `HtmlElementView`/`PlatformView` widgets that respond to mouse gestures (handle clicks, for example), the clicks will be consumed by the `HtmlElementView`/`PlatformView`, and not relayed to Flutter. The result is that Flutter widget's `onTap` (and other) handlers won't fire as expected, but they'll affect the underlying native platform view. |The problem...| |:-:| |![Depiction of problematic areas](https://raw.githubusercontent.com/flutter/packages/cb6dbcdd230528c0c246c81d93386c512f9a23d0/packages/pointer_interceptor/pointer_interceptor/doc/img/affected-areas.png)| |_In the dashed areas, mouse events won't work as expected. The `HtmlElementView` will consume them before Flutter sees them._| ## How does this work? In web, `PointerInterceptor` creates a platform view consisting of an empty HTML element, while on iOS it creates an empty `UIView` instead. The element has the size of its `child` widget, and is inserted in the layer tree _behind_ its child in paint order. This empty platform view doesn't do anything with mouse events, other than preventing them from reaching other platform views underneath it. This gives an opportunity to the Flutter framework to handle the click, as expected: |The solution...| |:-:| |![Depiction of the solution](https://raw.githubusercontent.com/flutter/packages/cb6dbcdd230528c0c246c81d93386c512f9a23d0/packages/pointer_interceptor/pointer_interceptor/doc/img/fixed-areas.png)| |_Each `PointerInterceptor` (green) renders between Flutter widgets and the underlying `HtmlElementView`. Mouse events now can't reach the background HtmlElementView, and work as expected._| ## How to use Some common scenarios where this widget may come in handy: * [FAB](https://api.flutter.dev/flutter/material/FloatingActionButton-class.html) unclickable in an app that renders a full-screen background Map * Custom Play/Pause buttons on top of a video element don't work * Drawer contents not interactive when it overlaps an iframe element * ... All the cases above have in common that they attempt to render Flutter widgets *on top* of platform views that handle pointer events. There's two ways that the `PointerInterceptor` widget can be used to solve the problems above: 1. Wrapping your button element directly (FAB, Custom Play/Pause button...): ```dart PointerInterceptor( child: ElevatedButton(...), ) ``` 2. As a root container for a "layout" element, wrapping a bunch of other elements (like a Drawer): ```dart Scaffold( ... drawer: PointerInterceptor( child: Drawer( child: ... ), ), ... ) ``` ### `intercepting` A common use of the `PointerInterceptor` widget is to block clicks only under certain conditions (`isVideoShowing`, `isPanelOpen`...). The `intercepting` property allows the `PointerInterceptor` widget to render itself (or not) depending on a boolean value, instead of having to manually write an `if/else` on the Flutter App widget tree, so code like this: ```dart if (someCondition) { return PointerInterceptor( child: ElevatedButton(...), ) } else { return ElevatedButton(...), } ``` can be rewritten as: ```dart return PointerInterceptor( intercepting: someCondition, child: ElevatedButton(...), ) ``` Note: when `intercepting` is false, the `PointerInterceptor` will not render _anything_ in flutter, and just return its `child`. The code is exactly equivalent to the example above. ### `debug` The `PointerInterceptor` widget has a `debug` property, that will render it visibly on the screen (similar to the images above). This may be useful to see what the widget is actually covering when used as a layout element.
packages/packages/pointer_interceptor/pointer_interceptor/README.md/0
{ "file_path": "packages/packages/pointer_interceptor/pointer_interceptor/README.md", "repo_id": "packages", "token_count": 1285 }
1,068
// Copyright 2013 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:flutter/material.dart'; import 'package:flutter/services.dart'; /// A widget representing an underlying platform view. class NativeWidget extends StatelessWidget { /// Constructor const NativeWidget({super.key, required this.onClick}); /// Placeholder param to allow web example to work - /// onClick functionality for iOS is in the PlatformView final VoidCallback onClick; @override Widget build(BuildContext context) { const String viewType = 'dummy_platform_view'; final Map<String, dynamic> creationParams = <String, dynamic>{}; return UiKitView( viewType: viewType, layoutDirection: TextDirection.ltr, creationParams: creationParams, creationParamsCodec: const StandardMessageCodec(), ); } }
packages/packages/pointer_interceptor/pointer_interceptor/example/lib/platforms/native_widget_ios.dart/0
{ "file_path": "packages/packages/pointer_interceptor/pointer_interceptor/example/lib/platforms/native_widget_ios.dart", "repo_id": "packages", "token_count": 279 }
1,069
// Copyright 2013 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:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:pointer_interceptor_platform_interface/pointer_interceptor_platform_interface.dart'; void main() { runApp(const MaterialApp(home: PointerInterceptorIOSExample())); } class _DummyPlatformView extends StatelessWidget { const _DummyPlatformView(); @override Widget build(BuildContext context) { const String viewType = 'dummy_platform_view'; final Map<String, dynamic> creationParams = <String, dynamic>{}; return UiKitView( viewType: viewType, layoutDirection: TextDirection.ltr, creationParams: creationParams, creationParamsCodec: const StandardMessageCodec(), ); } } /// Example flutter app with a button overlaying the native view. class PointerInterceptorIOSExample extends StatefulWidget { /// Constructor const PointerInterceptorIOSExample({super.key}); @override State<StatefulWidget> createState() { return _PointerInterceptorIOSExampleState(); } } class _PointerInterceptorIOSExampleState extends State<PointerInterceptorIOSExample> { bool _buttonTapped = false; @override Widget build(BuildContext context) { return Scaffold( body: Center( child: Stack( alignment: AlignmentDirectional.center, children: <Widget>[ const _DummyPlatformView(), PointerInterceptorPlatform.instance.buildWidget( child: TextButton( style: TextButton.styleFrom(foregroundColor: Colors.red), child: _buttonTapped ? const Text('Tapped') : const Text('Initial'), onPressed: () { setState(() { _buttonTapped = !_buttonTapped; }); })), ], ), )); } }
packages/packages/pointer_interceptor/pointer_interceptor_ios/example/lib/main.dart/0
{ "file_path": "packages/packages/pointer_interceptor/pointer_interceptor_ios/example/lib/main.dart", "repo_id": "packages", "token_count": 804 }
1,070
# pointer_interceptor_platform_interface A common platform interface for the [`pointer_interceptor`][1] plugin. This interface allows platform-specific implementations of the `pointer_interceptor` plugin, as well as the plugin itself, to ensure they are supporting the same interface. # Usage To implement a new platform-specific implementation of `pointer_interceptor`, extend [`PointerInterceptorPlatform`][2] with an implementation that performs the platform-specific behavior, and when you register your plugin, set the default `PointerInterceptorPlatform` by calling `PointerInterceptorPlatform.instance = MyPointerInterceptorPlatform()`. # Note on breaking changes Strongly prefer non-breaking changes (such as adding a method to the interface) over breaking changes for this package. See https://flutter.dev/go/platform-interface-breaking-changes for a discussion on why a less-clean interface is preferable to a breaking change. [1]: https://pub.dev/packages/pointer_interceptor [2]: lib/src/pointer_interceptor_platform.dart
packages/packages/pointer_interceptor/pointer_interceptor_platform_interface/README.md/0
{ "file_path": "packages/packages/pointer_interceptor/pointer_interceptor_platform_interface/README.md", "repo_id": "packages", "token_count": 255 }
1,071
// Copyright 2013 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:file/file.dart'; import 'package:file/local.dart'; import 'package:path/path.dart' show Context; import 'package:platform/platform.dart'; import 'exceptions.dart'; const Map<String, String> _osToPathStyle = <String, String>{ 'linux': 'posix', 'macos': 'posix', 'android': 'posix', 'ios': 'posix', 'fuchsia': 'posix', 'windows': 'windows', }; /// Sanitizes the executable path on Windows. /// https://github.com/dart-lang/sdk/issues/37751 String sanitizeExecutablePath(String executable, {Platform platform = const LocalPlatform()}) { if (executable.isEmpty) { return executable; } if (!platform.isWindows) { return executable; } if (executable.contains(' ') && !executable.contains('"')) { // Use quoted strings to indicate where the file name ends and the arguments begin; // otherwise, the file name is ambiguous. return '"$executable"'; } return executable; } /// Searches the `PATH` for the executable that [executable] is supposed to launch. /// /// This first builds a list of candidate paths where the executable may reside. /// If [executable] is already an absolute path, then the `PATH` environment /// variable will not be consulted, and the specified absolute path will be the /// only candidate that is considered. /// /// Once the list of candidate paths has been constructed, this will pick the /// first such path that represents an existent file. /// /// Return `null` if there were no viable candidates, meaning the executable /// could not be found. /// /// If [platform] is not specified, it will default to the current platform. String? getExecutablePath( String executable, String? workingDirectory, { Platform platform = const LocalPlatform(), FileSystem fs = const LocalFileSystem(), bool throwOnFailure = false, }) { assert(_osToPathStyle[platform.operatingSystem] == fs.path.style.name); try { workingDirectory ??= fs.currentDirectory.path; } on FileSystemException { // The `currentDirectory` getter can throw a FileSystemException for example // when the process doesn't have read/list permissions in each component of // the cwd path. In this case, fall back on '.'. workingDirectory ??= '.'; } final Context context = Context(style: fs.path.style, current: workingDirectory); // TODO(goderbauer): refactor when github.com/google/platform.dart/issues/2 // is available. final String pathSeparator = platform.isWindows ? ';' : ':'; List<String> extensions = <String>[]; if (platform.isWindows && context.extension(executable).isEmpty) { extensions = platform.environment['PATHEXT']!.split(pathSeparator); } List<String> candidates = <String>[]; List<String> searchPath; if (executable.contains(context.separator)) { // Deal with commands that specify a relative or absolute path differently. searchPath = <String>[workingDirectory]; } else { searchPath = platform.environment['PATH']!.split(pathSeparator); } candidates = _getCandidatePaths(executable, searchPath, extensions, context); final List<String> foundCandidates = <String>[]; for (final String path in candidates) { final File candidate = fs.file(path); final FileStat stat = candidate.statSync(); // Only return files or links that exist. if (stat.type == FileSystemEntityType.notFound || stat.type == FileSystemEntityType.directory) { continue; } // File exists, but we don't know if it's readable/executable yet. foundCandidates.add(candidate.path); const int isExecutable = 0x40; const int isReadable = 0x100; const int isExecutableAndReadable = isExecutable | isReadable; // Should only return files or links that are readable and executable by the // user. // On Windows it's not actually possible to only return files that are // readable, since Dart reports files that have had read permission removed // as being readable, but not checking for it is the same as checking for it // and finding it readable, so we use the same check here on all platforms, // so that if Dart ever gets fixed, it'll just work. if (stat.mode & isExecutableAndReadable == isExecutableAndReadable) { return path; } } if (throwOnFailure) { if (foundCandidates.isNotEmpty) { throw ProcessPackageExecutableNotFoundException( executable, message: 'Found candidates, but lacked sufficient permissions to execute "$executable".', workingDirectory: workingDirectory, candidates: foundCandidates, searchPath: searchPath, ); } else { throw ProcessPackageExecutableNotFoundException( executable, message: 'Failed to find "$executable" in the search path.', workingDirectory: workingDirectory, searchPath: searchPath, ); } } return null; } /// Returns all possible combinations of `$searchPath\$command.$ext` for /// `searchPath` in [searchPaths] and `ext` in [extensions]. /// /// If [extensions] is empty, it will just enumerate all /// `$searchPath\$command`. /// If [command] is an absolute path, it will just enumerate /// `$command.$ext`. List<String> _getCandidatePaths( String command, List<String> searchPaths, List<String> extensions, Context context, ) { final List<String> withExtensions = extensions.isNotEmpty ? extensions.map((String ext) => '$command$ext').toList() : <String>[command]; if (context.isAbsolute(command)) { return withExtensions; } return searchPaths .map((String path) => withExtensions.map((String command) => context.join(path, command))) .expand((Iterable<String> e) => e) .toList() .cast<String>(); }
packages/packages/process/lib/src/interface/common.dart/0
{ "file_path": "packages/packages/process/lib/src/interface/common.dart", "repo_id": "packages", "token_count": 1865 }
1,072
<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="io.flutter.plugins.quickactions"> <uses-sdk tools:overrideLibrary="android_libs.ub_uiautomator"/> </manifest>
packages/packages/quick_actions/quick_actions_android/android/src/main/AndroidManifest.xml/0
{ "file_path": "packages/packages/quick_actions/quick_actions_android/android/src/main/AndroidManifest.xml", "repo_id": "packages", "token_count": 104 }
1,073
There are several examples. * `hello` shows how `RemoteWidget` can render some widgets from a description interpreted at runtime. * `local` shows how to create new local widget definitions for use in remote widget descriptions. * `remote` is a proof-of-concept showing files being obtained from a remote server and rendered by the application at runtime. * `wasm` shows how package:rfw can be combined with package:wasm to configure logic as well as the user interface at runtime.
packages/packages/rfw/example/README.md/0
{ "file_path": "packages/packages/rfw/example/README.md", "repo_id": "packages", "token_count": 120 }
1,074
name: hello description: Hello World example for RFW publish_to: 'none' # Remove this line if you wish to publish to pub.dev version: 1.0.0+1 environment: sdk: ^3.2.0 flutter: ">=3.16.0" dependencies: flutter: sdk: flutter rfw: path: ../../
packages/packages/rfw/example/hello/pubspec.yaml/0
{ "file_path": "packages/packages/rfw/example/hello/pubspec.yaml", "repo_id": "packages", "token_count": 107 }
1,075
#include "Generated.xcconfig"
packages/packages/rfw/example/local/ios/Flutter/Debug.xcconfig/0
{ "file_path": "packages/packages/rfw/example/local/ios/Flutter/Debug.xcconfig", "repo_id": "packages", "token_count": 12 }
1,076
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
packages/packages/rfw/example/local/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "packages/packages/rfw/example/local/macos/Runner/Configs/Release.xcconfig", "repo_id": "packages", "token_count": 32 }
1,077
buildFlags: global: - "--no-tree-shake-icons"
packages/packages/rfw/example/remote/.pluginToolsConfig.yaml/0
{ "file_path": "packages/packages/rfw/example/remote/.pluginToolsConfig.yaml", "repo_id": "packages", "token_count": 23 }
1,078
This directory contains the source files (.rfwtxt) for the binary UI descriptions (.rfw) that are used by the demo. To convert the source files to binary files run `encode.dart` in this directory.
packages/packages/rfw/example/remote/remote_widget_libraries/README.md/0
{ "file_path": "packages/packages/rfw/example/remote/remote_widget_libraries/README.md", "repo_id": "packages", "token_count": 53 }
1,079
# Example of using Wasm with RFW In this example, the application downloads both RFW descriptions of UI and Wasm logic to drive it. The Flutter application itself does not contain any of the calculator UI or logic. Currently this only runs on macOS, Windows, and Linux, since `package:wasm` does not yet support Android, iOS, or web. ## Building Before running this package, you must run `flutter pub run wasm:setup` in this directory. Before doing this, you will need to have installed Rust and clang. To rebuild the files in the logic/ directory (which are the files that the application downloads at runtime), you will additionally need to have installed clang and lld, and dart must be on your path. ## Conventions The application renders the remote widget named `root` defined in the `logic/calculator.rfw` file, and loads the Wasm module defined in the `logic/calculator.wasm` file. The Wasm module must implement a function `value` that takes no arguments and returns an integer, which is the data to pass to the interface. This will be the first function called. That data is stored in the `value` key of the data exposed to the remote widgets, as a map with two values, `numeric` (which stores the integer as-is) and `string` (which stores its string representation, e.g. for display using a `Text` widget). The remote widgets can signal events. The names of such events are looked up as functions in the Wasm module. The `arguments` key, if present, must be a list of integers to pass to the function. Only the `core.widgets` local library is loaded into the runtime. ## Application behavior The demo application fetches the RFW and Wasm files on startup, if it has not downloaded them before or if they were downloaded more than six hours earlier.
packages/packages/rfw/example/wasm/README.md/0
{ "file_path": "packages/packages/rfw/example/wasm/README.md", "repo_id": "packages", "token_count": 454 }
1,080
// Copyright 2013 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. // This file is hand-formatted. // This file must not import `dart:ui`, directly or indirectly, as it is // intended to function even in pure Dart server or CLI environments. import 'package:meta/meta.dart'; /// A map whose keys are strings and whose values are [DynamicMap], /// [DynamicList], int, double, bool, string, and [BlobNode] objects. /// /// Part of the data type for [DynamicContent] objects. typedef DynamicMap = Map<String, Object?>; /// A list whose values are [DynamicMap], [DynamicList], int, double, bool, /// string, and [BlobNode] objects. /// /// Part of the data type for [DynamicContent] objects. typedef DynamicList = List<Object?>; /// Reference to a location in a source file. /// /// This is used in a [SourceRange] object to indicate the location of a /// [BlobNode] in the original source text. /// /// Locations are given as offsets (in UTF-16 code units) into the decoded /// string. /// /// See also: /// /// * [BlobNode.source], which exposes the source location of a [BlobNode]. @immutable class SourceLocation implements Comparable<SourceLocation> { /// Create a [SourceLocation] object. /// /// The [source] and [offset] properties are initialized from the /// given arguments. const SourceLocation(this.source, this.offset); /// An object that identifies the file or other origin of the source. /// /// For files parsed using [parseLibraryFile], this is the value that /// is given as the `sourceIdentifier` argument. final Object source; /// The offset of the given source location, in UTF-16 code units. final int offset; @override int compareTo(SourceLocation other) { if (source != other.source) { throw StateError('Cannot compare locations from different sources.'); } return offset - other.offset; } @override bool operator ==(Object other) { if (other.runtimeType != SourceLocation) { return false; } return other is SourceLocation && source == other.source && offset == other.offset; } @override int get hashCode => Object.hash(source, offset); /// Whether this location is earlier in the file than `other`. /// /// Can only be used to compare locations in the same [source]. bool operator <(SourceLocation other) { if (source != other.source) { throw StateError('Cannot compare locations from different sources.'); } return offset < other.offset; } /// Whether this location is later in the file than `other`. /// /// Can only be used to compare locations in the same [source]. bool operator >(SourceLocation other) { if (source != other.source) { throw StateError('Cannot compare locations from different sources.'); } return offset > other.offset; } /// Whether this location is earlier in the file than `other`, or equal to /// `other`. /// /// Can only be used to compare locations in the same [source]. bool operator <=(SourceLocation other) { if (source != other.source) { throw StateError('Cannot compare locations from different sources.'); } return offset <= other.offset; } /// Whether this location is later in the file than `other`, or equal to /// `other`. /// /// Can only be used to compare locations in the same [source]. bool operator >=(SourceLocation other) { if (source != other.source) { throw StateError('Cannot compare locations from different sources.'); } return offset >= other.offset; } @override String toString() { return '$source@$offset'; } } /// Reference to a range of a source file. /// /// This is used to indicate the region of a source file that corresponds to a /// particular [BlobNode]. /// /// By default, [BlobNode]s are not associated with [SourceRange]s. Source /// location information can be enabled for the [parseLibraryFile] parser by /// providing the `sourceIdentifier` argument. /// /// See also: /// /// * [BlobNode.source], which exposes the source location of a [BlobNode]. @immutable class SourceRange { /// Create a [SourceRange] object. /// /// The [start] and [end] locations are initialized from the given arguments. /// /// They must have identical [SourceLocation.source] objects. SourceRange(this.start, this.end) : assert(start.source == end.source, 'The start and end locations have inconsistent source information.'), assert(start < end, 'The start location must be before the end location.'); /// The start of a contiguous region of a source file that corresponds to a /// particular [BlobNode]. /// /// The range contains the start. final SourceLocation start; /// The end of a contiguous region of a source file that corresponds to a /// particular [BlobNode]. /// /// The range does not contain the end. final SourceLocation end; @override bool operator ==(Object other) { if (other.runtimeType != SourceRange) { return false; } return other is SourceRange && start == other.start && end == other.end; } @override int get hashCode => Object.hash(start, end); @override String toString() { return '${start.source}@${start.offset}..${end.offset}'; } } /// Base class of nodes that appear in the output of [decodeDataBlob] and /// [decodeLibraryBlob]. /// /// In addition to this, the following types can be found in that output: /// /// * [DynamicMap] /// * [DynamicList] /// * [int] /// * [double] /// * [bool] /// * [String] abstract class BlobNode { /// Abstract const constructor. This constructor enables subclasses to provide /// const constructors so that they can be used in const expressions. const BlobNode(); // We use an [Expando] so that there is no (or minimal) overhead in production // environments that don't need to track source locations. It would be cleaner // to store the information directly on the [BlobNode], as then we could enforce // that that information is always propagated, instead of relying on remembering // to do so. However, that would require growing the size of every [BlobNode] // object, and would require additional logic even in the binary parser (which // does not track source locations currently). static final Expando<SourceRange> _sources = Expando<SourceRange>('BlobNode._sources'); /// The source location that corresponds to this [BlobNode], if known. /// /// In normal use, this returns null. However, if source location tracking is /// enabled (e.g. by specifying the `sourceIdentifier` argument to /// [parseLibraryFile]), then this will return the range of the source file /// that corresponds to this [BlobNode]. /// /// A [BlobNode] can also be manually associated with a given [SourceRange] /// using [associateSource] or [propagateSource]. SourceRange? get source { return _sources[this]; } /// Assign a [SourceRange] to this [BlobNode]'s [source] property. /// /// Typically, this is used exclusively by the parser (notably, /// [parseLibraryFile]). /// /// Tracking source location information introduces a memory overhead and /// should therefore only be used when necessary (e.g. for creating IDEs). /// /// Calling this method replaces any existing association. void associateSource(SourceRange source) { _sources[this] = source; } /// Assign another [BlobNode]'s [SourceRange] to this [BlobNode]'s [source] /// property. /// /// Typically, this is used exclusively by the [Runtime]. /// /// If the `original` [BlobNode] is null or has no [source], then this has no /// effect. Otherwise, the [source] for this [BlobNode] is set to match that /// of the given `original` [BlobNode], replacing any existing association. void propagateSource(BlobNode? original) { if (original == null) { return; } final SourceRange? source = _sources[original]; if (source != null) { _sources[this] = source; } } } bool _listEquals<T>(List<T>? a, List<T>? b) { if (identical(a, b)) { return true; } if (a == null || b == null || a.length != b.length) { return false; } for (int index = 0; index < a.length; index += 1) { if (a[index] != b[index]) { return false; } } return true; } /// The name of a widgets library in the RFW package. /// /// Libraries are typically referred to with names like "core.widgets" or /// "com.example.shopping.cart". This class represents these names as lists of /// tokens, in those cases `['core', 'widgets']` and `['com', 'example', /// 'shopping', 'cart']`, for example. @immutable class LibraryName implements Comparable<LibraryName> { /// Wrap the given list as a [LibraryName]. /// /// The given list is not copied; it is an error to modify it after creating /// the [LibraryName]. const LibraryName(this.parts); /// The components of the structured library name. final List<String> parts; @override bool operator ==(Object other) { if (other.runtimeType != runtimeType) { return false; } return other is LibraryName && _listEquals<String>(parts, other.parts); } @override int get hashCode => Object.hashAll(parts); @override String toString() => parts.join('.'); @override int compareTo(LibraryName other) { for (int index = 0; index < parts.length; index += 1) { if (other.parts.length <= index) { return 1; } final int result = parts[index].compareTo(other.parts[index]); if (result != 0) { return result; } } assert(other.parts.length >= parts.length); return parts.length - other.parts.length; } } /// The name of a widget used by the RFW package, including its library name. /// /// This can be used to identify both local widgets and remote widgets. @immutable class FullyQualifiedWidgetName implements Comparable<FullyQualifiedWidgetName> { /// Wrap the given library name and widget name in a [FullyQualifiedWidgetName]. const FullyQualifiedWidgetName(this.library, this.widget); /// The name of the library in which [widget] can be found. final LibraryName library; /// The name of the widget, which should be in the specified [library]. final String widget; @override bool operator ==(Object other) { if (other.runtimeType != runtimeType) { return false; } return other is FullyQualifiedWidgetName && library == other.library && widget == other.widget; } @override int get hashCode => Object.hash(library, widget); @override String toString() => '$library:$widget'; @override int compareTo(FullyQualifiedWidgetName other) { final int result = library.compareTo(other.library); if (result != 0) { return result; } return widget.compareTo(other.widget); } } /// The type of the [missing] value. /// /// This is used internally by the RFW package to avoid needing to use nullable /// types. class Missing extends BlobNode { const Missing._(); @override String toString() => '<missing>'; } /// The value used by [DynamicContent] to represent missing data. /// /// This is return from [DynamicContent.subscribe] when the specified key is not /// present. /// /// Content in a [DynamicContent] should not contain [missing] values. const Missing missing = Missing._(); /// Representation of the `...for` construct in Remote Flutter Widgets library /// blobs. class Loop extends BlobNode { /// Creates a [Loop] with the given [input] and [output]. /// /// The provided objects must not be mutated after being given to the /// constructor (e.g. the ownership of any lists and maps passes to this /// object). const Loop(this.input, this.output); /// The list on which to iterate. /// /// This is typically some sort of [Reference], but could be a [DynamicList]. /// /// It is an error for this to be a value that does not resolve to a list. final Object input; /// The template to apply for each value on [input]. final Object output; @override String toString() => '...for loop in $input: $output'; } /// Representation of the `switch` construct in Remote Flutter Widgets library /// blobs. class Switch extends BlobNode { /// Creates a [Switch] with the given [input] and [outputs]. /// /// The provided objects must not be mutated after being given to the /// constructor. In particular, changing the [outputs] map after creating the /// [Switch] is an error. const Switch(this.input, this.outputs); /// The value to switch on. This is typically a reference, e.g. an /// [ArgsReference], which must be resolved by the runtime to determine the /// actual value on which to switch. final Object input; /// The cases for this switch. Keys correspond to values to compare with /// [input]. The null value is used as the default case. /// /// At runtime, if none of the keys match [input] and there is no null key, /// the [Switch] as a whole is treated as if it was [missing]. If the [Switch] /// is used where a [ConstructorCall] was expected, the result is an /// [ErrorWidget]. final Map<Object?, Object> outputs; @override String toString() => 'switch $input $outputs'; } /// Representation of references to widgets in Remote Flutter Widgets library /// blobs. class ConstructorCall extends BlobNode { /// Creates a [ConstructorCall] for a widget of the given name in the current /// library's scope, with the given [arguments]. /// /// The [arguments] must not be mutated after the object is created. const ConstructorCall(this.name, this.arguments); /// The name of the widget to create. /// /// The name is looked up in the current library, or, failing that, in a /// depth-first search of this library's dependencies. final String name; /// The arguments to pass to the constructor. /// /// Constructors in RFW only have named arguments. This differs from Dart /// (where arguments can also be positional.) final DynamicMap arguments; @override String toString() => '$name($arguments)'; } /// Representation of functions that return widgets in Remote Flutter Widgets library blobs. class WidgetBuilderDeclaration extends BlobNode { /// Represents a callback that takes a single argument [argumentName] and returns the [widget]. const WidgetBuilderDeclaration(this.argumentName, this.widget); /// The callback single argument name. /// /// In `Builder(builder: (scope) => Container());`, [argumentName] is "scope". final String argumentName; /// The widget that will be returned when the builder callback is called. /// /// This is usually a [ConstructorCall], but may be a [Switch] (so long as /// that [Switch] resolves to a [ConstructorCall]. Other values (or a [Switch] /// that does not resolve to a constructor call) will result in an /// [ErrorWidget] being used. final BlobNode widget; @override String toString() => '($argumentName) => $widget'; } /// Base class for various kinds of references in the RFW data structures. abstract class Reference extends BlobNode { /// Abstract const constructor. This constructor enables subclasses to provide /// const constructors so that they can be used in const expressions. /// /// The [parts] must not be mutated after the object is created. const Reference(this.parts); /// The components of the reference. Each entry must be either a String (to /// index into a [DynamicMap]) an integer (to index into a [DynamicList]). /// /// It is an error for any of the parts to be of any other type. final List<Object> parts; } /// Unbound reference to arguments. /// /// This class is used to represent references of the form "args.foo.bar" after /// parsing, before the arguments are bound. class ArgsReference extends Reference { /// Wraps the given [parts] as an [ArgsReference]. /// /// The [parts] must not be mutated after the object is created. const ArgsReference(super.parts); /// Binds the arguments reference to a specific set of arguments. /// /// Returns a [BoundArgsReference] with the same [parts] and whose /// [BoundArgsReference.arguments] is given by `arguments`. BoundArgsReference bind(Object arguments) { return BoundArgsReference(arguments, parts); } @override String toString() => 'args.${parts.join(".")}'; } /// Bound reference to arguments. /// /// This class is used to represent references of the form "args.foo.bar" after /// a widget declaration has been bound to specific arguments via a constructor /// call. The [arguments] property is a reference to the /// [ConstructorCall.arguments] object (or, more typically, a clone of that /// object that itself has had references within it bound). /// /// This class is an internal detail of the RFW [Runtime] and is generally not /// used directly. class BoundArgsReference extends Reference { /// Wraps the given [parts] and [arguments] as a [BoundArgsReference]. /// /// The parameters must not be mutated after the object is created. /// /// Generally this class is created using [ArgsReference.bind]. const BoundArgsReference(this.arguments, List<Object> parts): super(parts); /// The object into which [parts] will be indexed. /// /// This could contain [Loop]s, which is why it cannot be indexed immediately /// upon creation. final Object arguments; @override String toString() => 'args($arguments).${parts.join(".")}'; } /// Reference to the [DynamicContent] data that is passed into the widget (see /// [Runtime.build]'s `data` argument). class DataReference extends Reference { /// Wraps the given [parts] as a [DataReference]. /// /// The [parts] must not be mutated after the object is created. const DataReference(super.parts); /// Creates a new [DataRefererence] that indexes even deeper than this one. /// /// For example, suppose a widget's arguments consisted of a map with one key, /// "a", whose value was a [DataRefererence] referencing "data.foo.bar". Now /// suppose that the widget itself has an [ArgsReference] that references /// "args.a.baz". The "args.a" part identifies the aforementioned /// [DataReference], and so the resulting reference is actually to /// "data.foo.bar.baz". /// /// In this example, the [DataReference] to "data.foo.bar" would have its /// [constructReference] method invoked by the runtime, with `["baz"]` as the /// `moreParts` argument, so that the resulting [DataReference]'s [parts] is a /// combination of the original's (`["foo", "bar"]`) and the additional parts /// provided to the method. DataReference constructReference(List<Object> moreParts) { return DataReference(parts + moreParts); } @override String toString() => 'data.${parts.join(".")}'; } /// Reference to the single argument of type [DynamicMap] passed into the widget builder. /// /// This class is used to represent references to a function argument. /// In `(scope) => Container(width: scope.width)`, this represents "scope.width". /// /// See also: /// /// * [WidgetBuilderDeclaration], which represents a widget builder definition. class WidgetBuilderArgReference extends Reference { /// Wraps the given [argumentName] and [parts] as a [WidgetBuilderArgReference]. /// /// The parts must not be mutated after the object is created. const WidgetBuilderArgReference(this.argumentName, super.parts); /// A reference to a [WidgetBuilderDeclaration.argumentName]. /// /// In `Builder(builder: (scope) => Text(text: scope.result.text));`, /// "scope.result.text" is the [WidgetBuilderArgReference]. /// The [argumentName] is "scope" and its [parts] are `["result", "text"]`. final String argumentName; @override String toString() => '$argumentName.${parts.join('.')}'; } /// Unbound reference to a [Loop]. class LoopReference extends Reference { /// Wraps the given [loop] and [parts] as a [LoopReference]. /// /// The [parts] must not be mutated after the object is created. const LoopReference(this.loop, List<Object> parts): super(parts); /// The index to the referenced loop. /// /// Loop indices count up, so the nearest loop ancestor of the reference has /// index zero, with indices counting up when going up the tree towards the /// root. final int loop; // this is basically a De Bruijn index /// Creates a new [LoopRefererence] that indexes even deeper than this one. /// /// For example, suppose a widget's arguments consisted of a map with one key, /// "a", whose value was a [LoopRefererence] referencing "loop0.foo.bar". Now /// suppose that the widget itself has an [ArgsReference] that references /// "args.a.baz". The "args.a" part identifies the aforementioned /// [LoopReference], and so the resulting reference is actually to /// "loop0.foo.bar.baz". /// /// In this example, the [LoopReference] to "loop0.foo.bar" would have its /// [constructReference] method invoked by the runtime, with `["baz"]` as the /// `moreParts` argument, so that the resulting [LoopReference]'s [parts] is a /// combination of the original's (`["foo", "bar"]`) and the additional parts /// provided to the method. /// /// The [loop] index is maintained in the new object. LoopReference constructReference(List<Object> moreParts) { return LoopReference(loop, parts + moreParts); } /// Binds the loop reference to a specific value. /// /// Returns a [BoundLoopReference] with the same [parts] and whose /// [BoundLoopReference.value] is given by `value`. The [loop] index is /// dropped in the process. BoundLoopReference bind(Object value) { return BoundLoopReference(value, parts); } @override String toString() => 'loop$loop.${parts.join(".")}'; } /// Bound reference to a [Loop]. /// /// This class is used to represent references of the form "loopvar.foo.bar" /// after the list containing the relevant loop has been dereferenced so that /// the loop variable refers to a specific value in the list. The [value] is /// that resolved value. /// /// This class is an internal detail of the RFW [Runtime] and is generally not /// used directly. class BoundLoopReference extends Reference { /// Wraps the given [value] and [parts] as a [BoundLoopReference]. /// /// The [parts] must not be mutated after the object is created. /// /// Generally this class is created using [LoopReference.bind]. const BoundLoopReference(this.value, List<Object> parts): super(parts); /// The object into which [parts] will index. /// /// This could contain further [Loop]s or unbound [LoopReference]s, which is /// why it cannot be indexed immediately upon creation. final Object value; /// Creates a new [BoundLoopRefererence] that indexes even deeper than this /// one. /// /// For example, suppose a widget's arguments consisted of a map with one key, /// "a", whose value was a [BoundLoopRefererence] referencing "loop0.foo.bar". /// Now suppose that the widget itself has an [ArgsReference] that references /// "args.a.baz". The "args.a" part identifies the aforementioned /// [BoundLoopReference], and so the resulting reference is actually to /// "loop0.foo.bar.baz". /// /// In this example, the [BoundLoopReference] to "loop0.foo.bar" would have /// its [constructReference] method invoked by the runtime, with `["baz"]` as /// the `moreParts` argument, so that the resulting [BoundLoopReference]'s /// [parts] is a combination of the original's (`["foo", "bar"]`) and the /// additional parts provided to the method. /// /// The resolved [value] (which is what the [parts] will eventually index /// into) is maintained in the new object. BoundLoopReference constructReference(List<Object> moreParts) { return BoundLoopReference(value, parts + moreParts); } @override String toString() => 'loop($value).${parts.join(".")}'; } /// Base class for [StateReference] and [BoundStateReference]. /// /// This is used to ensure [SetStateHandler]'s [SetStateHandler.stateReference] /// property can only hold a state reference. abstract class AnyStateReference extends Reference { /// Abstract const constructor. This constructor enables subclasses to provide /// const constructors so that they can be used in const expressions. /// /// The [parts] must not be mutated after the object is created. const AnyStateReference(super.parts); } /// Unbound reference to remote widget's state. /// /// This class is used to represent references of the form "state.foo.bar". class StateReference extends AnyStateReference { /// Wraps the given [parts] as a [StateReference]. /// /// The [parts] must not be mutated after the object is created. const StateReference(super.parts); /// Binds the state reference to a specific widget (identified by depth). /// /// Returns a [BoundStateReference] with the same [parts] and whose /// [BoundLoopReference.depth] is given by `depth`. BoundStateReference bind(int depth) { return BoundStateReference(depth, parts); } @override String toString() => 'state.${parts.join(".")}'; } /// Bound reference to a remote widget's state. /// /// This class is used to represent references of the form "state.foo.bar" after /// the widgets have been constructed, so that the right state can be /// identified. /// /// This class is an internal detail of the RFW [Runtime] and is generally not /// used directly. class BoundStateReference extends AnyStateReference { /// Wraps the given [depth] and [parts] as a [BoundStateReference]. /// /// The [parts] must not be mutated after the object is created. /// /// Generally this class is created using [StateReference.bind]. const BoundStateReference(this.depth, List<Object> parts): super(parts); /// The widget to whose state the state reference refers. /// /// This identifies the widget by depth starting at the widget that was /// created by [Runtime.build] (or a [RemoteWidget], which uses that method). /// /// Since state references always go up the tree, this is an unambiguous way /// to reference state, even though in practice in the entire tree multiple /// widgets may be stateful at the same depth. final int depth; /// Creates a new [BoundStateRefererence] that indexes even deeper than this /// one (deeper into the specified widget's state, not into a deeper widget!). /// /// For example, suppose a widget's arguments consisted of a map with one key, /// "a", whose value was a [BoundStateRefererence] referencing "state.foo.bar". /// Now suppose that the widget itself has an [ArgsReference] that references /// "args.a.baz". The "args.a" part identifies the aforementioned /// [BoundStateReference], and so the resulting reference is actually to /// "state.foo.bar.baz". /// /// In this example, the [BoundStateReference] to "state.foo.bar" would have /// its [constructReference] method invoked by the runtime, with `["baz"]` as /// the `moreParts` argument, so that the resulting [BoundStateReference]'s /// [parts] is a combination of the original's (`["foo", "bar"]`) and the /// additional parts provided to the method. /// /// The [depth] is maintained in the new object. BoundStateReference constructReference(List<Object> moreParts) { return BoundStateReference(depth, parts + moreParts); } @override String toString() => 'state^$depth.${parts.join(".")}'; } /// Base class for [EventHandler] and [SetStateHandler]. /// /// This is used by the [Runtime] to quickly filter out objects that are not /// event handlers of any kind. abstract class AnyEventHandler extends BlobNode { /// Abstract const constructor. This constructor enables subclasses to provide /// const constructors so that they can be used in const expressions. const AnyEventHandler(); } /// Description of a callback in an RFW widget declaration. /// /// This represents a signal to send to the application using the RFW package. /// Typically applications either handle such messages locally, or forward them /// to a server for further processing. class EventHandler extends AnyEventHandler { /// Wraps the given event name and arguments in an [EventHandler] object. /// /// The [eventArguments] must not be mutated after the object is created. const EventHandler(this.eventName, this.eventArguments); /// A string to identify the event. This provides an unambiguous identifier /// for the event, avoiding the need to establish a convention in the /// [eventArguments]. final String eventName; /// The payload to provide with the event. final DynamicMap eventArguments; @override String toString() => 'event $eventName $eventArguments'; } /// Description of a state setter in an RFW widget declaration. /// /// This event handler is handled by the RFW [Runtime] itself by setting the /// state referenced by [stateReference] to the value represented by [value] /// when the event handler would be invoked. class SetStateHandler extends AnyEventHandler { /// Wraps the given [stateReference] and [value] in a [SetStateHandler] object. /// /// The [value] must not be mutated after the object is created (e.g. in the /// event that it is a [DynamicMap] or [DynamicList]). const SetStateHandler(this.stateReference, this.value); /// Identifies the member in the widget's state to mutate. final AnyStateReference stateReference; /// The value to which the specified state will be set. final Object value; @override String toString() => 'set $stateReference = $value'; } /// A library import. /// /// Used to describe which libraries a remote widget libraries depends on. The /// identified libraries can be local or remote. Import loops are invalid. // TODO(ianh): eventually people will probably want a way to disambiguate imports // with a prefix. class Import extends BlobNode { /// Wraps the given library [name] in an [Import] object. const Import(this.name); /// The name of the library to import. final LibraryName name; @override String toString() => 'import $name;'; } /// A description of a widget in a remote widget library. /// /// The [root] must be either a [ConstructorCall] or a [Switch] that evaluates /// to a [ConstructorCall]. (In principle one can imagine that an /// [ArgsReference] that evaluates to a [ConstructorCall] would also be valid, /// but such a construct would be redundant and would not provide any additional /// expressivity, so it is disallowed.) /// /// The tree rooted at [root] must not contain (directly or indirectly) a /// [ConstructorCall] that references the widget declared by this /// [WidgetDeclaration]: widget loops, even indirect loops or loops that would /// in principle be terminated by use of a [Switch], are not allowed. class WidgetDeclaration extends BlobNode { /// Binds the given [name] to the definition given by [root]. /// /// The [initialState] may be null. If it is not, this represents a stateful widget. const WidgetDeclaration(this.name, this.initialState, this.root) : assert(root is ConstructorCall || root is Switch); /// The name of the widget that this declaration represents. /// /// This is the left hand side of a widget declaration. final String name; /// If non-null, this is a stateful widget; the value is used to create the /// initial copy of the state when the widget is created. final DynamicMap? initialState; /// The widget to return when this widget is used. /// /// This is usually a [ConstructorCall], but may be a [Switch] (so long as /// that [Switch] resolves to a [ConstructorCall]. Other values (or a [Switch] /// that does not resolve to a constructor call) will result in an /// [ErrorWidget] being used. final BlobNode root; // ConstructorCall or Switch @override String toString() => 'widget $name = $root;'; } /// Base class for widget libraries. abstract class WidgetLibrary { /// Abstract const constructor. This constructor enables subclasses to provide /// const constructors so that they can be used in const expressions. const WidgetLibrary(); } /// The in-memory representation of the output of [parseTextLibraryFile] or /// [decodeLibraryBlob]. class RemoteWidgetLibrary extends WidgetLibrary { /// Wraps a set of [imports] and [widgets] (widget declarations) in a /// [RemoteWidgetLibrary] object. /// /// The provided lists must not be mutated once the library is created. const RemoteWidgetLibrary(this.imports, this.widgets); /// The list of libraries that this library depends on. /// /// This must not be empty, since at least one local widget library must be in /// scope in order for the remote widget library to be useful. final List<Import> imports; /// The list of widgets declared by this library. /// /// This can be empty. final List<WidgetDeclaration> widgets; @override String toString() => const Iterable<Object>.empty().followedBy(imports).followedBy(widgets).join('\n'); }
packages/packages/rfw/lib/src/dart/model.dart/0
{ "file_path": "packages/packages/rfw/lib/src/dart/model.dart", "repo_id": "packages", "token_count": 9206 }
1,081
// Copyright 2013 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:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:rfw/formats.dart' show parseLibraryFile; import 'package:rfw/rfw.dart'; void main() { testWidgets('RemoteWidget', (WidgetTester tester) async { final Runtime runtime1 = Runtime() ..update(const LibraryName(<String>['core']), createCoreWidgets()) ..update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = Placeholder(); ''')); final Runtime runtime2 = Runtime() ..update(const LibraryName(<String>['core']), createCoreWidgets()) ..update(const LibraryName(<String>['test']), parseLibraryFile(''' import core; widget root = Container(); ''')); final DynamicContent data = DynamicContent(); await tester.pumpWidget( RemoteWidget( runtime: runtime1, data: data, widget: const FullyQualifiedWidgetName( LibraryName(<String>['test']), 'root'), ), ); expect(find.byType(RemoteWidget), findsOneWidget); expect(find.byType(Placeholder), findsOneWidget); expect(find.byType(Container), findsNothing); await tester.pumpWidget( RemoteWidget( runtime: runtime2, data: data, widget: const FullyQualifiedWidgetName( LibraryName(<String>['test']), 'root'), ), ); expect(find.byType(RemoteWidget), findsOneWidget); expect(find.byType(Placeholder), findsNothing); expect(find.byType(Container), findsOneWidget); }); }
packages/packages/rfw/test/remote_widget_test.dart/0
{ "file_path": "packages/packages/rfw/test/remote_widget_test.dart", "repo_id": "packages", "token_count": 646 }
1,082
// Copyright 2013 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:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart'; import 'package:shared_preferences_platform_interface/types.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); const String testString = 'hello world'; const bool testBool = true; const int testInt = 42; const double testDouble = 3.14159; const List<String> testList = <String>['foo', 'bar']; const Map<String, Object> testValues = <String, Object>{ 'flutter.String': testString, 'flutter.bool': testBool, 'flutter.int': testInt, 'flutter.double': testDouble, 'flutter.List': testList, }; const String testString2 = 'goodbye world'; const bool testBool2 = false; const int testInt2 = 1337; const double testDouble2 = 2.71828; const List<String> testList2 = <String>['baz', 'quox']; const Map<String, dynamic> testValues2 = <String, dynamic>{ 'flutter.String': testString2, 'flutter.bool': testBool2, 'flutter.int': testInt2, 'flutter.double': testDouble2, 'flutter.List': testList2, }; late FakeSharedPreferencesStore store; late SharedPreferences preferences; setUp(() async { store = FakeSharedPreferencesStore(testValues); SharedPreferencesStorePlatform.instance = store; preferences = await SharedPreferences.getInstance(); store.log.clear(); }); test('reading', () async { expect(preferences.get('String'), testString); expect(preferences.get('bool'), testBool); expect(preferences.get('int'), testInt); expect(preferences.get('double'), testDouble); expect(preferences.get('List'), testList); expect(preferences.getString('String'), testString); expect(preferences.getBool('bool'), testBool); expect(preferences.getInt('int'), testInt); expect(preferences.getDouble('double'), testDouble); expect(preferences.getStringList('List'), testList); expect(store.log, <Matcher>[]); }); test('writing', () async { await Future.wait(<Future<bool>>[ preferences.setString('String', testString2), preferences.setBool('bool', testBool2), preferences.setInt('int', testInt2), preferences.setDouble('double', testDouble2), preferences.setStringList('List', testList2) ]); expect( store.log, <Matcher>[ isMethodCall('setValue', arguments: <dynamic>[ 'String', 'flutter.String', testString2, ]), isMethodCall('setValue', arguments: <dynamic>[ 'Bool', 'flutter.bool', testBool2, ]), isMethodCall('setValue', arguments: <dynamic>[ 'Int', 'flutter.int', testInt2, ]), isMethodCall('setValue', arguments: <dynamic>[ 'Double', 'flutter.double', testDouble2, ]), isMethodCall('setValue', arguments: <dynamic>[ 'StringList', 'flutter.List', testList2, ]), ], ); store.log.clear(); expect(preferences.getString('String'), testString2); expect(preferences.getBool('bool'), testBool2); expect(preferences.getInt('int'), testInt2); expect(preferences.getDouble('double'), testDouble2); expect(preferences.getStringList('List'), testList2); expect(store.log, equals(<MethodCall>[])); }); test('removing', () async { const String key = 'testKey'; await preferences.remove(key); expect( store.log, List<Matcher>.filled( 1, isMethodCall( 'remove', arguments: 'flutter.$key', ), growable: true, )); }); test('containsKey', () async { const String key = 'testKey'; expect(false, preferences.containsKey(key)); await preferences.setString(key, 'test'); expect(true, preferences.containsKey(key)); }); test('clearing', () async { await preferences.clear(); expect(preferences.getString('String'), null); expect(preferences.getBool('bool'), null); expect(preferences.getInt('int'), null); expect(preferences.getDouble('double'), null); expect(preferences.getStringList('List'), null); expect(store.log, <Matcher>[isMethodCall('clear', arguments: null)]); }); test('reloading', () async { await preferences.setString('String', testString); expect(preferences.getString('String'), testString); SharedPreferences.setMockInitialValues(testValues2.cast<String, Object>()); expect(preferences.getString('String'), testString); await preferences.reload(); expect(preferences.getString('String'), testString2); }); test('back to back calls should return same instance.', () async { final Future<SharedPreferences> first = SharedPreferences.getInstance(); final Future<SharedPreferences> second = SharedPreferences.getInstance(); expect(await first, await second); }); test('string list type is dynamic (usually from method channel)', () async { SharedPreferences.setMockInitialValues(<String, Object>{ 'dynamic_list': <dynamic>['1', '2'] }); final SharedPreferences prefs = await SharedPreferences.getInstance(); final List<String>? value = prefs.getStringList('dynamic_list'); expect(value, <String>['1', '2']); }); group('mocking', () { const String key = 'dummy'; const String prefixedKey = 'flutter.$key'; test('test 1', () async { SharedPreferences.setMockInitialValues( <String, Object>{prefixedKey: 'my string'}); final SharedPreferences prefs = await SharedPreferences.getInstance(); final String? value = prefs.getString(key); expect(value, 'my string'); }); test('test 2', () async { SharedPreferences.setMockInitialValues( <String, Object>{prefixedKey: 'my other string'}); final SharedPreferences prefs = await SharedPreferences.getInstance(); final String? value = prefs.getString(key); expect(value, 'my other string'); }); }); test('writing copy of strings list', () async { final List<String> myList = <String>[]; await preferences.setStringList('myList', myList); myList.add('foobar'); final List<String> cachedList = preferences.getStringList('myList')!; expect(cachedList, <String>[]); cachedList.add('foobar2'); expect(preferences.getStringList('myList'), <String>[]); }); test('calling mock initial values with non-prefixed keys succeeds', () async { SharedPreferences.setMockInitialValues(<String, Object>{ 'test': 'foo', }); final SharedPreferences prefs = await SharedPreferences.getInstance(); final String? value = prefs.getString('test'); expect(value, 'foo'); }); test('getInstance always returns the same instance', () async { SharedPreferencesStorePlatform.instance = SlowInitSharedPreferencesStore(); final Future<SharedPreferences> firstFuture = SharedPreferences.getInstance(); final Future<SharedPreferences> secondFuture = SharedPreferences.getInstance(); expect(identical(await firstFuture, await secondFuture), true); }); test('calling setPrefix after getInstance throws', () async { const String newPrefix = 'newPrefix'; await SharedPreferences.getInstance(); Object? err; try { SharedPreferences.setPrefix(newPrefix); } catch (e) { err = e; } expect(err, isA<StateError>()); }); test('using setPrefix allows setting and getting', () async { const String newPrefix = 'newPrefix'; SharedPreferences.resetStatic(); SharedPreferences.setPrefix(newPrefix); final SharedPreferences prefs = await SharedPreferences.getInstance(); await prefs.setString('stringKey', 'test'); await prefs.setBool('boolKey', true); await prefs.setDouble('doubleKey', 3.14); final String? testString = prefs.getString('stringKey'); expect(testString, 'test'); final bool? testBool = prefs.getBool('boolKey'); expect(testBool, true); final double? testDouble = prefs.getDouble('doubleKey'); expect(testDouble, 3.14); }); test('allowList only gets allowed items', () async { const Set<String> allowList = <String>{'stringKey', 'boolKey'}; SharedPreferences.resetStatic(); SharedPreferences.setPrefix('', allowList: allowList); final SharedPreferences prefs = await SharedPreferences.getInstance(); await prefs.setString('stringKey', 'test'); await prefs.setBool('boolKey', true); await prefs.setDouble('doubleKey', 3.14); await prefs.reload(); final String? testString = prefs.getString('stringKey'); expect(testString, 'test'); final bool? testBool = prefs.getBool('boolKey'); expect(testBool, true); final double? testDouble = prefs.getDouble('doubleKey'); expect(testDouble, null); }); test('using reload after setPrefix properly reloads the cache', () async { const String newPrefix = 'newPrefix'; SharedPreferences.resetStatic(); SharedPreferences.setPrefix(newPrefix); final SharedPreferences prefs = await SharedPreferences.getInstance(); String? testString = prefs.getString('stringKey'); await prefs.setString('stringKey', 'test'); testString = prefs.getString('stringKey'); expect(testString, 'test'); await prefs.reload(); final String? testStrings = prefs.getString('stringKey'); expect(testStrings, 'test'); }); test('unimplemented errors in withParameters methods are updated', () async { final UnimplementedSharedPreferencesStore localStore = UnimplementedSharedPreferencesStore(); SharedPreferencesStorePlatform.instance = localStore; SharedPreferences.resetStatic(); SharedPreferences.setPrefix(''); Object? err; try { await SharedPreferences.getInstance(); } catch (e) { err = e; } expect(err, isA<UnimplementedError>()); expect( err.toString(), contains( "Shared Preferences doesn't yet support the setPrefix method")); }); test('non-Unimplemented errors pass through withParameters methods correctly', () async { final ThrowingSharedPreferencesStore localStore = ThrowingSharedPreferencesStore(); SharedPreferencesStorePlatform.instance = localStore; SharedPreferences.resetStatic(); SharedPreferences.setPrefix(''); Object? err; try { await SharedPreferences.getInstance(); } catch (e) { err = e; } expect(err, isA<StateError>()); expect(err.toString(), contains('State Error')); }); } class FakeSharedPreferencesStore extends SharedPreferencesStorePlatform { FakeSharedPreferencesStore(Map<String, Object> data) : backend = InMemorySharedPreferencesStore.withData(data); final InMemorySharedPreferencesStore backend; final List<MethodCall> log = <MethodCall>[]; @override Future<bool> clear() { log.add(const MethodCall('clear')); return backend.clear(); } @override Future<bool> clearWithParameters(ClearParameters parameters) { log.add(const MethodCall('clearWithParameters')); return backend.clearWithParameters(parameters); } @override Future<Map<String, Object>> getAll() { log.add(const MethodCall('getAll')); return backend.getAll(); } @override Future<Map<String, Object>> getAllWithParameters( GetAllParameters parameters) { log.add(const MethodCall('getAllWithParameters')); return backend.getAllWithParameters(parameters); } @override Future<bool> remove(String key) { log.add(MethodCall('remove', key)); return backend.remove(key); } @override Future<bool> setValue(String valueType, String key, Object value) { log.add(MethodCall('setValue', <dynamic>[valueType, key, value])); return backend.setValue(valueType, key, value); } } class UnimplementedSharedPreferencesStore extends SharedPreferencesStorePlatform { @override Future<bool> clear() { throw UnimplementedError(); } @override Future<Map<String, Object>> getAll() { throw UnimplementedError(); } @override Future<bool> remove(String key) { throw UnimplementedError(); } @override Future<bool> setValue(String valueType, String key, Object value) { throw UnimplementedError(); } } class SlowInitSharedPreferencesStore extends UnimplementedSharedPreferencesStore { @override Future<Map<String, Object>> getAll() async { await Future<void>.delayed(const Duration(seconds: 1)); return <String, Object>{}; } } class ThrowingSharedPreferencesStore extends SharedPreferencesStorePlatform { @override Future<bool> clear() { throw UnimplementedError(); } @override Future<Map<String, Object>> getAll() { throw UnimplementedError(); } @override Future<bool> remove(String key) { throw UnimplementedError(); } @override Future<bool> setValue(String valueType, String key, Object value) { throw UnimplementedError(); } @override Future<Map<String, Object>> getAllWithParameters( GetAllParameters parameters) { throw StateError('State Error'); } }
packages/packages/shared_preferences/shared_preferences/test/shared_preferences_test.dart/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences/test/shared_preferences_test.dart", "repo_id": "packages", "token_count": 4784 }
1,083
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:flutter/services.dart'; import 'shared_preferences_platform_interface.dart'; import 'types.dart'; const MethodChannel _kChannel = MethodChannel('plugins.flutter.io/shared_preferences'); /// Wraps NSUserDefaults (on iOS) and SharedPreferences (on Android), providing /// a persistent store for simple data. /// /// Data is persisted to disk asynchronously. class MethodChannelSharedPreferencesStore extends SharedPreferencesStorePlatform { @override Future<bool> remove(String key) async { return (await _kChannel.invokeMethod<bool>( 'remove', <String, dynamic>{'key': key}, ))!; } @override Future<bool> setValue(String valueType, String key, Object value) async { return (await _kChannel.invokeMethod<bool>( 'set$valueType', <String, dynamic>{'key': key, 'value': value}, ))!; } @override Future<bool> clear() async { return (await _kChannel.invokeMethod<bool>('clear'))!; } @override @Deprecated('Use clearWithParameters instead') Future<bool> clearWithPrefix(String prefix) async { return clearWithParameters( ClearParameters( filter: PreferencesFilter(prefix: prefix), ), ); } @override Future<bool> clearWithParameters(ClearParameters parameters) async { final PreferencesFilter filter = parameters.filter; return (await _kChannel.invokeMethod<bool>( 'clearWithParameters', <String, dynamic>{ 'prefix': filter.prefix, 'allowList': filter.allowList?.toList(), }, ))!; } @override Future<Map<String, Object>> getAll() async { return await _kChannel.invokeMapMethod<String, Object>('getAll') ?? <String, Object>{}; } @override @Deprecated('Use getAllWithParameters instead') Future<Map<String, Object>> getAllWithPrefix( String prefix, { Set<String>? allowList, }) async { return getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: prefix), ), ); } @override Future<Map<String, Object>> getAllWithParameters( GetAllParameters parameters) async { final PreferencesFilter filter = parameters.filter; final List<String>? allowListAsList = filter.allowList?.toList(); return await _kChannel.invokeMapMethod<String, Object>( 'getAllWithParameters', <String, dynamic>{ 'prefix': filter.prefix, 'allowList': allowListAsList }, ) ?? <String, Object>{}; } }
packages/packages/shared_preferences/shared_preferences_platform_interface/lib/method_channel_shared_preferences.dart/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_platform_interface/lib/method_channel_shared_preferences.dart", "repo_id": "packages", "token_count": 964 }
1,084
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:convert' show json; import 'package:flutter_web_plugins/flutter_web_plugins.dart'; import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart'; import 'package:shared_preferences_platform_interface/types.dart'; import 'package:web/web.dart' as html; import 'src/keys_extension.dart'; /// The web implementation of [SharedPreferencesStorePlatform]. /// /// This class implements the `package:shared_preferences` functionality for the web. class SharedPreferencesPlugin extends SharedPreferencesStorePlatform { /// Registers this class as the default instance of [SharedPreferencesStorePlatform]. static void registerWith(Registrar? registrar) { SharedPreferencesStorePlatform.instance = SharedPreferencesPlugin(); } static const String _defaultPrefix = 'flutter.'; @override Future<bool> clear() async { return clearWithParameters( ClearParameters( filter: PreferencesFilter(prefix: _defaultPrefix), ), ); } @override Future<bool> clearWithPrefix(String prefix) async { return clearWithParameters( ClearParameters(filter: PreferencesFilter(prefix: prefix))); } @override Future<bool> clearWithParameters(ClearParameters parameters) async { final PreferencesFilter filter = parameters.filter; // IMPORTANT: Do not use html.window.localStorage.clear() as that will // remove _all_ local data, not just the keys prefixed with // _prefix _getFilteredKeys(filter.prefix, allowList: filter.allowList) .forEach(remove); return true; } @override Future<Map<String, Object>> getAll() async { return getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: _defaultPrefix), ), ); } @override Future<Map<String, Object>> getAllWithPrefix(String prefix) async { return getAllWithParameters( GetAllParameters(filter: PreferencesFilter(prefix: prefix))); } @override Future<Map<String, Object>> getAllWithParameters( GetAllParameters parameters) async { final PreferencesFilter filter = parameters.filter; final Map<String, Object> allData = <String, Object>{}; for (final String key in _getFilteredKeys(filter.prefix, allowList: filter.allowList)) { allData[key] = _decodeValue(html.window.localStorage.getItem(key)!); } return allData; } @override Future<bool> remove(String key) async { html.window.localStorage.removeItem(key); return true; } @override Future<bool> setValue(String valueType, String key, Object? value) async { html.window.localStorage.setItem(key, _encodeValue(value)); return true; } Iterable<String> _getFilteredKeys( String prefix, { Set<String>? allowList, }) { return html.window.localStorage.keys.where((String key) => key.startsWith(prefix) && (allowList?.contains(key) ?? true)); } String _encodeValue(Object? value) { return json.encode(value); } Object _decodeValue(String encodedValue) { final Object? decodedValue = json.decode(encodedValue); if (decodedValue is List) { // JSON does not preserve generics. The encode/decode roundtrip is // `List<String>` => JSON => `List<dynamic>`. We have to explicitly // restore the RTTI. return decodedValue.cast<String>(); } return decodedValue!; } }
packages/packages/shared_preferences/shared_preferences_web/lib/shared_preferences_web.dart/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_web/lib/shared_preferences_web.dart", "repo_id": "packages", "token_count": 1208 }
1,085