text
stringlengths
6
13.6M
id
stringlengths
13
176
metadata
dict
__index_level_0__
int64
0
1.69k
<?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.network.client</key> <true/> <key>com.apple.security.app-sandbox</key> <true/> </dict> </plist>
packages/packages/flutter_image/example/macos/Runner/Release.entitlements/0
{ "file_path": "packages/packages/flutter_image/example/macos/Runner/Release.entitlements", "repo_id": "packages", "token_count": 131 }
954
// 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'; const int _kTestServerPort = 11111; Future<void> main() async { final HttpServer testServer = await HttpServer.bind(InternetAddress.loopbackIPv4, _kTestServerPort); await for (final HttpRequest request in testServer) { if (request.uri.path.endsWith('/immediate_success.png')) { request.response.add(_kTransparentImage); } else if (request.uri.path.endsWith('/error.png')) { request.response.statusCode = 500; } else if (request.uri.path.endsWith('/extra_header.png') && request.headers.value('ExtraHeader') == 'special') { request.response.add(_kTransparentImage); } else { request.response.statusCode = 404; } await request.response.flush(); await request.response.close(); } } const List<int> _kTransparentImage = <int>[ 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4, 0x89, 0x00, 0x00, 0x00, 0x0A, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, 0x00, 0x01, 0x0D, 0x0A, 0x2D, 0xB4, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, ];
packages/packages/flutter_image/test/network_test_server.dart/0
{ "file_path": "packages/packages/flutter_image/test/network_test_server.dart", "repo_id": "packages", "token_count": 750 }
955
# Flutter Markdown [![pub package](https://img.shields.io/pub/v/flutter_markdown.svg)](https://pub.dartlang.org/packages/flutter_markdown) A markdown renderer for Flutter. It supports the [original format](https://daringfireball.net/projects/markdown/), but no inline HTML. ## Overview The [`flutter_markdown`](https://pub.dev/packages/flutter_markdown) package renders Markdown, a lightweight markup language, into a Flutter widget containing a rich text representation. `flutter_markdown` is built on top of the Dart [`markdown`](https://pub.dev/packages/markdown) package, which parses the Markdown into an abstract syntax tree (AST). The nodes of the AST are an HTML representation of the Markdown data. ## Flutter Isn't an HTML Renderer While this approach to creating a rich text representation of Markdown source text in Flutter works well, Flutter isn't an HTML renderer like a web browser. Markdown was developed by John Gruber in 2004 to allow users to turn readable, plain text content into rich text HTML. This close association with HTML allows for the injection of HTML into the Markdown source data. Markdown parsers generally ignore hand-tuned HTML and pass it through to be included in the generated HTML. This *trick* has allowed users to perform some customization or tweaking of the HTML output. A common HTML tweak is to insert HTML line-break elements **\<br />** in Markdown source to force additional line breaks not supported by the Markdown syntax. This HTML *trick* doesn't apply to Flutter. The `flutter_markdown` package doesn't support inline HTML. ## Markdown Specifications and `flutter_markdown` Compliance There are three seminal documents regarding Markdown syntax; the [original Markdown syntax documentation](https://daringfireball.net/projects/markdown/syntax) specified by John Gruber, the [CommonMark specification](https://spec.commonmark.org/0.29/), and the [GitHub Flavored Markdown specification](https://github.github.com/gfm/). The CommonMark specification brings order to and clarifies the Markdown syntax cases left ambiguous or unclear in the Gruber document. GitHub Flavored Markdown (GFM) is a strict superset of CommonMark used by GitHub. The `markdown` package, and in extension, the `flutter_markdown` package, supports four levels of Markdown syntax; basic, CommonMark, GitHub Flavored, and GitHub Web. Basic, CommonMark, and GitHub Flavored adhere to the three Markdown documents, respectively. GitHub Web adds header ID and emoji support. The `flutter_markdown` package defaults to GitHub Flavored Markdown. ## Getting Started Using the Markdown widget is simple, just pass in the source markdown as a string: <?code-excerpt "example/lib/readme_excerpts.dart (CreateMarkdown)"?> ```dart const Markdown(data: markdownSource); ``` If you do not want the padding or scrolling behavior, use the MarkdownBody instead: <?code-excerpt "example/lib/readme_excerpts.dart (CreateMarkdownBody)"?> ```dart const MarkdownBody(data: markdownSource); ``` By default, Markdown uses the formatting from the current material design theme, but it's possible to create your own custom styling. Use the MarkdownStyle class to pass in your own style. If you don't want to use Markdown outside of material design, use the MarkdownRaw class. ## Selection By default, Markdown is not selectable. A caller may use the following ways to customize the selection behavior of Markdown: * Set `selectable` to true, and use `onTapText` and `onSelectionChanged` to handle tapping and selecting events. * Set `selectable` to false, and wrap Markdown with [`SelectionArea`](https://api.flutter.dev/flutter/material/SelectionArea-class.html) or [`SelectionRegion`](https://api.flutter.dev/flutter/widgets/SelectableRegion-class.html). ## Emoji Support Emoji glyphs can be included in the formatted text displayed by the Markdown widget by either inserting the emoji glyph directly or using the inline emoji tag syntax in the source Markdown document. Markdown documents using UTF-8 encoding can insert emojis, symbols, and other Unicode characters directly in the source document. Emoji glyphs inserted directly in the Markdown source data are treated as text and preserved in the formatted output of the Markdown widget. For example, in the following Markdown widget constructor, a text string with a smiley face emoji is passed in as the source Markdown data. <?code-excerpt "example/lib/readme_excerpts.dart (CreateMarkdownWithEmoji)"?> ```dart Markdown( controller: controller, selectable: true, data: 'Insert emoji here😀 ', ); ``` The resulting Markdown widget will contain a single line of text with the emoji preserved in the formatted text output. The second method for including emoji glyphs is to provide the Markdown widget with a syntax extension for inline emoji tags. The Markdown package includes a syntax extension for emojis, EmojiSyntax. The default extension set used by the Markdown widget is the GitHub flavored extension set. This pre-defined extension set approximates the GitHub supported Markdown tags, providing syntax handlers for fenced code blocks, tables, auto-links, and strike-through. To include the inline emoji tag syntax while maintaining the default GitHub flavored Markdown behavior, define an extension set that combines EmojiSyntax with ExtensionSet.gitHubFlavored. <?code-excerpt "example/lib/readme_excerpts.dart (CreateMarkdownWithEmojiExtension)"?> ```dart import 'package:markdown/markdown.dart' as md; // ··· Markdown( controller: controller, selectable: true, data: 'Insert emoji :smiley: here', extensionSet: md.ExtensionSet( md.ExtensionSet.gitHubFlavored.blockSyntaxes, <md.InlineSyntax>[ md.EmojiSyntax(), ...md.ExtensionSet.gitHubFlavored.inlineSyntaxes ], ), ); ``` ## Image Support The `Img` tag only supports the following image locations: * From the network: Use a URL prefixed by either `http://` or `https://`. * From local files on the device: Use an absolute path to the file, for example by concatenating the file name with the path returned by a known storage location, such as those provided by the [`path_provider`](https://pub.dartlang.org/packages/path_provider) plugin. * From image locations referring to bundled assets: Use an asset name prefixed by `resource:`. like `resource:assets/image.png`. ## Verifying Markdown Behavior Verifying Markdown behavior in other applications can often be useful to track down or identify unexpected output from the `flutter_markdown` package. Two valuable resources are the [Dart Markdown Live Editor](https://dart-lang.github.io/markdown/) and the [Markdown Live Preview](https://markdownlivepreview.com/). These two resources are dynamic, online Markdown viewers. ## Markdown Resources Here are some additional Markdown syntax resources: - [Markdown Guide](https://www.markdownguide.org/) - [CommonMark Markdown Reference](https://commonmark.org/help/) - [GitHub Guides - Mastering Markdown](https://guides.github.com/features/mastering-markdown/#GitHub-flavored-markdown) - [Download PDF cheatsheet version](https://guides.github.com/pdfs/markdown-cheatsheet-online.pdf)
packages/packages/flutter_markdown/README.md/0
{ "file_path": "packages/packages/flutter_markdown/README.md", "repo_id": "packages", "token_count": 1990 }
956
// 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:markdown/markdown.dart' as md; // ignore_for_file: public_member_api_docs enum MarkdownExtensionSet { none, commonMark, githubFlavored, githubWeb } extension MarkdownExtensionSetExtension on MarkdownExtensionSet { String get displayTitle => () { switch (this) { case MarkdownExtensionSet.none: return 'None'; case MarkdownExtensionSet.commonMark: return 'Common Mark'; case MarkdownExtensionSet.githubFlavored: return 'GitHub Flavored'; case MarkdownExtensionSet.githubWeb: return 'GitHub Web'; } }(); md.ExtensionSet get value => () { switch (this) { case MarkdownExtensionSet.none: return md.ExtensionSet.none; case MarkdownExtensionSet.commonMark: return md.ExtensionSet.commonMark; case MarkdownExtensionSet.githubFlavored: return md.ExtensionSet.gitHubFlavored; case MarkdownExtensionSet.githubWeb: return md.ExtensionSet.gitHubWeb; } }(); } extension WrapAlignmentExtension on WrapAlignment { String get displayTitle => () { switch (this) { case WrapAlignment.center: return 'Center'; case WrapAlignment.end: return 'End'; case WrapAlignment.spaceAround: return 'Space Around'; case WrapAlignment.spaceBetween: return 'Space Between'; case WrapAlignment.spaceEvenly: return 'Space Evenly'; case WrapAlignment.start: return 'Start'; } }(); }
packages/packages/flutter_markdown/example/lib/shared/markdown_extensions.dart/0
{ "file_path": "packages/packages/flutter_markdown/example/lib/shared/markdown_extensions.dart", "repo_id": "packages", "token_count": 793 }
957
name: flutter_markdown description: A Markdown renderer for Flutter. Create rich text output, including text styles, tables, links, and more, from plain text data formatted with simple Markdown tags. repository: https://github.com/flutter/packages/tree/main/packages/flutter_markdown issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+flutter_markdown%22 version: 0.6.22 environment: sdk: ^3.3.0 flutter: ">=3.19.0" dependencies: flutter: sdk: flutter markdown: ^7.1.1 meta: ^1.3.0 path: ^1.8.0 dev_dependencies: flutter_test: sdk: flutter mockito: 5.4.4 standard_message_codec: ^0.0.1+3 topics: - markdown - widgets
packages/packages/flutter_markdown/pubspec.yaml/0
{ "file_path": "packages/packages/flutter_markdown/pubspec.yaml", "repo_id": "packages", "token_count": 281 }
958
// 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/gestures.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_markdown/flutter_markdown.dart'; import 'package:flutter_test/flutter_test.dart'; import 'utils.dart'; void main() => defineTests(); void defineTests() { group('Link', () { testWidgets( 'should work with nested elements', (WidgetTester tester) async { final List<MarkdownLink> linkTapResults = <MarkdownLink>[]; const String data = '[Link `with nested code` Text](href)'; await tester.pumpWidget( boilerplate( Markdown( data: data, onTapLink: (String text, String? href, String title) => linkTapResults.add(MarkdownLink(text, href, title)), ), ), ); final Text textWidget = tester.widget(find.byType(Text)); final TextSpan span = textWidget.textSpan! as TextSpan; final List<Type> gestureRecognizerTypes = <Type>[]; span.visitChildren((InlineSpan inlineSpan) { if (inlineSpan is TextSpan) { final TapGestureRecognizer? recognizer = inlineSpan.recognizer as TapGestureRecognizer?; gestureRecognizerTypes.add(recognizer?.runtimeType ?? Null); if (recognizer != null) { recognizer.onTap!(); } } return true; }); expect(span.children!.length, 3); expect(gestureRecognizerTypes.length, 3); expect(gestureRecognizerTypes, everyElement(TapGestureRecognizer)); expect(linkTapResults.length, 3); // Each of the child text span runs should return the same link info. for (final MarkdownLink tapResult in linkTapResults) { expectLinkTap(tapResult, const MarkdownLink('Link with nested code Text', 'href')); } }, ); testWidgets( 'should work next to other links', (WidgetTester tester) async { final List<MarkdownLink> linkTapResults = <MarkdownLink>[]; const String data = '[First Link](firstHref) and [Second Link](secondHref)'; await tester.pumpWidget( boilerplate( Markdown( data: data, onTapLink: (String text, String? href, String title) => linkTapResults.add(MarkdownLink(text, href, title)), ), ), ); final Text textWidget = tester.widget(find.byType(Text)); final TextSpan span = textWidget.textSpan! as TextSpan; final List<Type> gestureRecognizerTypes = <Type>[]; span.visitChildren((InlineSpan inlineSpan) { if (inlineSpan is TextSpan) { final TapGestureRecognizer? recognizer = inlineSpan.recognizer as TapGestureRecognizer?; gestureRecognizerTypes.add(recognizer?.runtimeType ?? Null); if (recognizer != null) { recognizer.onTap!(); } } return true; }); expect(span.children!.length, 3); expect( gestureRecognizerTypes, orderedEquals( <Type>[TapGestureRecognizer, Null, TapGestureRecognizer]), ); expectLinkTap( linkTapResults[0], const MarkdownLink('First Link', 'firstHref')); expectLinkTap( linkTapResults[1], const MarkdownLink('Second Link', 'secondHref')); }, ); testWidgets( 'multiple inline links with same name but different urls - unique keys are assigned automatically', (WidgetTester tester) async { //Arange final Widget toBePumped = boilerplate( Column( children: <Widget>[ MarkdownBody( data: '[link](link1.com)', onTapLink: (String text, String? href, String title) {}, ), MarkdownBody( data: '[link](link2.com)', onTapLink: (String text, String? href, String title) {}, ), ], ), ); //Act await tester.pumpWidget(toBePumped); //Assert final Finder widgetFinder = find.byType(Text); final List<Element> elements = widgetFinder.evaluate().toList(); final List<Widget> widgets = elements.map((Element e) => e.widget).toList(); final List<String> keys = widgets .where((Widget w) => w.key != null && w.key.toString().isNotEmpty) .map((Widget w) => w.key.toString()) .toList(); expect(keys.length, 2); //Not empty expect(keys.toSet().length, 2); // Unique }, ); testWidgets( 'multiple inline links with same content should not throw an exception', (WidgetTester tester) async { //Arange final Widget toBePumped = boilerplate( Column( children: <Widget>[ Expanded( child: MarkdownBody( data: '''links: [![first](image.png)](https://link.com) [![second](image.png)](https://link.com) [![third](image.png)](https://link.com)''', onTapLink: (String text, String? href, String title) {}, ), ), ], ), ); //Act await tester.pumpWidget(toBePumped); //Assert final Finder widgetFinder = find.byType(Text, skipOffstage: false); final List<Element> elements = widgetFinder.evaluate().toList(); final List<Widget> widgets = elements.map((Element e) => e.widget).toList(); final List<String> keys = widgets .where((Widget w) => w.key != null && w.key.toString().isNotEmpty) .map((Widget w) => w.key.toString()) .toList(); expect(keys.length, 3); //all three links. expect(keys.toSet().length, 3); // all three unique. }, ); testWidgets( // Example 493 from GFM. 'simple inline link', (WidgetTester tester) async { const String data = '[link](/uri "title")'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('link'); expectLinkTap( linkTapResults, const MarkdownLink('link', '/uri', 'title')); }, ); testWidgets( 'empty inline link', (WidgetTester tester) async { const String data = '[](/uri "title")'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expect(find.byType(RichText), findsNothing); expect(linkTapResults, isNull); }, ); testWidgets( // Example 494 from GFM. 'simple inline link - title omitted', (WidgetTester tester) async { const String data = '[link](/uri)'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('link'); expectLinkTap(linkTapResults, const MarkdownLink('link', '/uri')); }, ); testWidgets( // Example 495 from GFM. 'simple inline link - both destination and title omitted', (WidgetTester tester) async { const String data = '[link]()'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('link'); expectLinkTap(linkTapResults, const MarkdownLink('link', '')); }, ); testWidgets( // Example 496 from GFM. 'simple inline link - both < > enclosed destination and title omitted', (WidgetTester tester) async { const String data = '[link](<>)'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('link'); expectLinkTap(linkTapResults, const MarkdownLink('link', '')); }, ); testWidgets( // Example 497 from GFM. 'link destination with space and not < > enclosed', (WidgetTester tester) async { const String data = '[link](/my url)'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); // Link is treated as ordinary text. expectInvalidLink('[link](/my url)'); expect(linkTapResults, isNull); }, ); testWidgets( // Example 498 from GFM. 'link destination with space and < > enclosed', (WidgetTester tester) async { const String data = '[link](</my url>)'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('link'); expectLinkTap(linkTapResults, const MarkdownLink('link', '/my%20url')); }, ); testWidgets( // Example 499 from GFM. 'link destination cannot contain line breaks - not < > enclosed', (WidgetTester tester) async { const String data = '[link](foo\nbar)'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); // Link is treated as ordinary text. expectInvalidLink('[link](foo bar)'); expect(linkTapResults, isNull); }, ); testWidgets( // Example 500 from GFM. 'link destination cannot contain line breaks - < > enclosed', (WidgetTester tester) async { const String data = '[link](<foo\nbar>)'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); // Link is treated as ordinary text. expectInvalidLink('[link](<foo bar>)'); expect(linkTapResults, isNull); }, ); testWidgets( // Example 501 from GFM. 'link destination containing ")" and < > enclosed', (WidgetTester tester) async { const String data = '[link](</my)url>)'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('link'); expectLinkTap(linkTapResults, const MarkdownLink('link', '/my)url')); }, ); testWidgets( // Example 502 from GFM. 'pointy brackets that enclose links must be unescaped', (WidgetTester tester) async { const String data = r'[link](<foo\>)'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); // Link is treated as ordinary text. expectInvalidLink('[link](<foo>)'); expect(linkTapResults, isNull); }, ); testWidgets( // Example 503 from GFM. 'opening pointy brackets are not properly matched', (WidgetTester tester) async { const String data = '[link](<foo)bar\n[link](<foo)bar>\n[link](<foo>bar)'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); // Link is treated as ordinary text. expectInvalidLink('[link](<foo)bar [link](<foo)bar> [link](<foo>bar)'); expect(linkTapResults, isNull); }, ); testWidgets( // Example 504 from GFM. 'parentheses inside link destination may be escaped', (WidgetTester tester) async { const String data = r'[link](\(foo\))'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('link'); expectLinkTap(linkTapResults, const MarkdownLink('link', '(foo)')); }, ); testWidgets( // Example 505 from GFM. 'multiple balanced parentheses are allowed without escaping', (WidgetTester tester) async { const String data = '[link](foo(and(bar)))'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('link'); expectLinkTap( linkTapResults, const MarkdownLink('link', 'foo(and(bar))')); }, ); testWidgets( // Example 506 from GFM. 'escaped unbalanced parentheses', (WidgetTester tester) async { // Use raw string so backslash isn't treated as an escape character. const String data = r'[link](foo\(and\(bar\))'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('link'); expectLinkTap( linkTapResults, const MarkdownLink('link', 'foo(and(bar)')); }, ); testWidgets( // Example 507 from GFM. 'pointy brackets enclosed unbalanced parentheses', (WidgetTester tester) async { const String data = '[link](<foo(and(bar)>)'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('link'); expectLinkTap( linkTapResults, const MarkdownLink('link', 'foo(and(bar)')); }, ); testWidgets( // Example 508 from GFM. 'parentheses and other symbols can be escaped', (WidgetTester tester) async { // Use raw string so backslash isn't treated as an escape character. const String data = r'[link](foo\)\:)'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('link'); expectLinkTap(linkTapResults, const MarkdownLink('link', 'foo):')); }, ); testWidgets( // Example 509 case 1 from GFM. 'link destinations with just fragment identifier', (WidgetTester tester) async { const String data = '[link](#fragment)'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('link'); expectLinkTap(linkTapResults, const MarkdownLink('link', '#fragment')); }, ); testWidgets( // Example 509 case 2 from GFM. 'link destinations with URL and fragment identifier', (WidgetTester tester) async { const String data = '[link](http://example.com#fragment)'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('link'); expectLinkTap(linkTapResults, const MarkdownLink('link', 'http://example.com#fragment')); }, ); testWidgets( // Example 509 case 3 from GFM. 'link destinations with URL, fragment identifier, and query', (WidgetTester tester) async { const String data = '[link](http://example.com?foo=3#fragment)'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('link'); expectLinkTap(linkTapResults, const MarkdownLink('link', 'http://example.com?foo=3#fragment')); }, ); testWidgets( // Example 510 from GFM. 'link destinations with backslash before non-escapable character', (WidgetTester tester) async { const String data = '[link](foo\bar)'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('link'); expectLinkTap(linkTapResults, const MarkdownLink('link', 'foo%08ar')); }, ); testWidgets( // Example 511 from GFM. 'URL escaping should be left alone inside link destination', (WidgetTester tester) async { const String data = '[link](foo%20b&auml;)'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('link'); expectLinkTap( linkTapResults, const MarkdownLink('link', 'foo%20b%C3%A4')); }, ); testWidgets( // Example 512 from GFM. 'omitting link destination uses title for destination', (WidgetTester tester) async { const String data = '[link]("title")'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('link'); expectLinkTap( linkTapResults, const MarkdownLink('link', '%22title%22')); }, ); testWidgets( // Example 513a from GFM. 'link title in double quotes', (WidgetTester tester) async { const String data = '[link](/url "title")'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('link'); expectLinkTap( linkTapResults, const MarkdownLink('link', '/url', 'title')); }, ); testWidgets( // Example 513b from GFM. 'link title in single quotes', (WidgetTester tester) async { const String data = "[link](/url 'title')"; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('link'); expectLinkTap( linkTapResults, const MarkdownLink('link', '/url', 'title')); }, ); testWidgets( // Example 513c from GFM. 'link title in parentheses', (WidgetTester tester) async { const String data = '[link](/url (title))'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('link'); expectLinkTap( linkTapResults, const MarkdownLink('link', '/url', 'title')); }, ); testWidgets( // Example 514 from GFM. 'backslash escapes, entity, and numeric character references are allowed in title', (WidgetTester tester) async { const String data = r'[link](/url "title \"&quot;")'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('link'); expectLinkTap(linkTapResults, const MarkdownLink('link', '/url', 'title &quot;&quot;')); }, ); testWidgets( // Example 515 from GFM. 'link title must be separated with whitespace and not Unicode whitespace', (WidgetTester tester) async { const String data = '[link](/url\u{C2A0}"title")'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('link'); expectLinkTap(linkTapResults, const MarkdownLink('link', '/url%EC%8A%A0%22title%22')); }, ); testWidgets( // Example 516 from GFM. 'nested balanced quotes are not allowed without escaping', (WidgetTester tester) async { const String data = '[link](/url "title "and" title")'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); // Link is treated as ordinary text. expectInvalidLink('[link](/url "title "and" title")'); expect(linkTapResults, isNull); }, ); testWidgets( // Example 517 from GFM. 'nested balanced quotes using different quote type', (WidgetTester tester) async { const String data = '[link](/url \'title "and" title\')'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('link'); expectLinkTap( linkTapResults, const MarkdownLink('link', '/url', 'title &quot;and&quot; title'), ); }, ); testWidgets( // Example 518 from GFM. 'whitespace is allowed around the destination and title', (WidgetTester tester) async { const String data = '[link]( /url "title")'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('link'); expectLinkTap( linkTapResults, const MarkdownLink('link', '/url', 'title')); }, ); testWidgets( // Example 519 from GFM. 'whitespace is not allowed between link text and following parentheses', (WidgetTester tester) async { const String data = '[link] (/url)'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); // Link is treated as ordinary text. expectInvalidLink('[link] (/url)'); expect(linkTapResults, isNull); }, ); testWidgets( // Example 520 from GFM. 'link text may contain balanced brackets', (WidgetTester tester) async { const String data = '[link [foo [bar]]](/uri)'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('link [foo [bar]]'); expectLinkTap( linkTapResults, const MarkdownLink('link [foo [bar]]', '/uri')); }, ); testWidgets( // Example 521 from GFM. 'link text may not contain unbalanced brackets', (WidgetTester tester) async { const String data = '[link] bar](/uri)'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); // Link is treated as ordinary text. expectInvalidLink('[link] bar](/uri)'); expect(linkTapResults, isNull); }, ); testWidgets( // Example 522 from GFM. 'link text may not contain unbalanced brackets - unintended link text', (WidgetTester tester) async { const String data = '[link [bar](/uri)'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); final Text textWidget = tester.widget(find.byType(Text)); final TextSpan span = textWidget.textSpan! as TextSpan; expect(span.children!.length, 2); expect(span.children![0], isA<TextSpan>()); expect(span.children![0].toPlainText(), '[link '); expectLinkTextSpan(span.children![1] as TextSpan, 'bar'); expectLinkTap(linkTapResults, const MarkdownLink('bar', '/uri')); }, ); testWidgets( // Example 523 from GFM. 'link text with escaped open square bracket', (WidgetTester tester) async { const String data = r'[link \[bar](/uri)'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('link [bar'); expectLinkTap(linkTapResults, const MarkdownLink('link [bar', '/uri')); }, ); testWidgets( // Example 524 from GFM. 'link text with inline emphasis and code', (WidgetTester tester) async { const String data = '[link *foo **bar** `#`*](/uri)'; final List<MarkdownLink> linkTapResults = <MarkdownLink>[]; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults.add(MarkdownLink(text, href, title)), ), ), ); final Text textWidget = tester.widget(find.byType(Text)); final TextSpan span = textWidget.textSpan! as TextSpan; expect(span.children!.length, 5); expectTextSpanStyle( span.children![0] as TextSpan, null, FontWeight.normal); expectTextSpanStyle( span.children![1] as TextSpan, FontStyle.italic, FontWeight.normal); expectTextSpanStyle( span.children![2] as TextSpan, FontStyle.italic, FontWeight.bold); expectTextSpanStyle( span.children![3] as TextSpan, FontStyle.italic, FontWeight.normal); expect((span.children![4] as TextSpan).style!.fontFamily, 'monospace'); final List<Type> gestureRecognizerTypes = <Type>[]; span.visitChildren((InlineSpan inlineSpan) { if (inlineSpan is TextSpan) { final TapGestureRecognizer? recognizer = inlineSpan.recognizer as TapGestureRecognizer?; gestureRecognizerTypes.add(recognizer.runtimeType); recognizer!.onTap!(); } return true; }); expect(gestureRecognizerTypes.length, 5); expect(gestureRecognizerTypes, everyElement(TapGestureRecognizer)); expect(linkTapResults.length, 5); // Each of the child text span runs should return the same link info. for (final MarkdownLink tapResult in linkTapResults) { expectLinkTap( tapResult, const MarkdownLink('link foo bar #', '/uri')); } }, ); testWidgets( // Example 525 from GFM. 'inline image link text', (WidgetTester tester) async { const String data = '[![moon](moon.jpg)](/uri)'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); final Finder gestureFinder = find.byType(GestureDetector); expect(gestureFinder, findsOneWidget); final GestureDetector gestureWidget = gestureFinder.evaluate().first.widget as GestureDetector; expect(gestureWidget.child, isA<Image>()); expect(gestureWidget.onTap, isNotNull); gestureWidget.onTap!(); expectLinkTap(linkTapResults, const MarkdownLink('moon', '/uri')); }, ); testWidgets( // Example 526 from GFM. 'links cannot be nested - outter link ignored', (WidgetTester tester) async { const String data = '[foo [bar](/uri)](/uri)'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); final Text textWidget = tester.widget(find.byType(Text)); final TextSpan span = textWidget.textSpan! as TextSpan; expect(span.children!.length, 3); expect(span.children![0], isA<TextSpan>()); expect(span.children![0].toPlainText(), '[foo '); expectLinkTextSpan(span.children![1] as TextSpan, 'bar'); expectLinkTap(linkTapResults, const MarkdownLink('bar', '/uri')); expect(span.children![2], isA<TextSpan>()); expect(span.children![2].toPlainText(), '](/uri)'); }, ); testWidgets( // Example 527 from GFM. 'links cannot be nested - outter link ignored with emphasis', (WidgetTester tester) async { const String data = '[foo *[bar [baz](/uri)](/uri)*](/uri)'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); final Text textWidget = tester.widget(find.byType(Text)); final TextSpan span = textWidget.textSpan! as TextSpan; expect(span.children!.length, 5); expect(span.children, everyElement(isA<TextSpan>())); expect(span.children![0].toPlainText(), '[foo '); expectTextSpanStyle( span.children![0] as TextSpan, null, FontWeight.normal); expect(span.children![1].toPlainText(), '[bar '); expectTextSpanStyle( span.children![1] as TextSpan, FontStyle.italic, FontWeight.normal); expect(span.children![2].toPlainText(), 'baz'); expectTextSpanStyle( span.children![2] as TextSpan, FontStyle.italic, FontWeight.normal); expect(span.children![3].toPlainText(), '](/uri)'); expectTextSpanStyle( span.children![3] as TextSpan, FontStyle.italic, FontWeight.normal); expect(span.children![4].toPlainText(), '](/uri)'); expectTextSpanStyle( span.children![4] as TextSpan, null, FontWeight.normal); expectLinkTextSpan(span.children![2] as TextSpan, 'baz'); expectLinkTap(linkTapResults, const MarkdownLink('baz', '/uri')); }, ); testWidgets( // Example 528 from GFM. 'links cannot be nested in image linksinline image link text', (WidgetTester tester) async { const String data = '![[[foo](uri1)](uri2)](uri3)'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); final Finder gestureFinder = find.byType(GestureDetector); expect(gestureFinder, findsNothing); final Finder imageFinder = find.byType(Image); expect(imageFinder, findsOneWidget); final Image image = imageFinder.evaluate().first.widget as Image; if (kIsWeb) { final NetworkImage fi = image.image as NetworkImage; expect(fi.url.endsWith('uri3'), true); } else { final FileImage fi = image.image as FileImage; expect(fi.file.path, equals('uri3')); } expect(linkTapResults, isNull); }, ); testWidgets( // Example 529 from GFM. 'link text grouping has precedence over emphasis grouping example 1', (WidgetTester tester) async { const String data = r'*[foo*](/uri)'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); final Text textWidget = tester.widget(find.byType(Text)); final TextSpan span = textWidget.textSpan! as TextSpan; expect(span.children!.length, 2); expect(span.children![0], isA<TextSpan>()); expect(span.children![0].toPlainText(), '*'); expectTextSpanStyle( span.children![0] as TextSpan, null, FontWeight.normal); expectLinkTextSpan(span.children![1] as TextSpan, 'foo*'); expectLinkTap(linkTapResults, const MarkdownLink('foo*', '/uri')); }, ); testWidgets( // Example 530 from GFM. 'link text grouping has precedence over emphasis grouping example 2', (WidgetTester tester) async { const String data = '[foo *bar](baz*)'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('foo *bar'); expectLinkTap(linkTapResults, const MarkdownLink('foo *bar', 'baz*')); }, ); testWidgets( // Example 531 from GFM. "brackets that aren't part of links do not take precedence", (WidgetTester tester) async { const String data = '*foo [bar* baz]'; await tester.pumpWidget( boilerplate( const MarkdownBody(data: data), ), ); final Text textWidget = tester.widget(find.byType(Text)); final TextSpan span = textWidget.textSpan! as TextSpan; expect(span.children!.length, 2); expect(span.children, everyElement(isA<TextSpan>())); expect(span.children![0].toPlainText(), 'foo [bar'); expectTextSpanStyle( span.children![0] as TextSpan, FontStyle.italic, FontWeight.normal); expect(span.children![1].toPlainText(), ' baz]'); expectTextSpanStyle( span.children![1] as TextSpan, null, FontWeight.normal); }, ); testWidgets( // Example 532 from GFM. 'HTML tag takes precedence over link grouping', (WidgetTester tester) async { const String data = '[foo <bar attr="](baz)">'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); // Link is treated as ordinary text. expectInvalidLink('[foo <bar attr="](baz)">'); expect(linkTapResults, isNull); }, ); testWidgets( // Example 533 from GFM. 'code span takes precedence over link grouping', (WidgetTester tester) async { const String data = '[foo`](/uri)`'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); final Finder gestureFinder = find.byType(GestureDetector); expect(gestureFinder, findsNothing); final Text textWidget = tester.widget(find.byType(Text)); final TextSpan span = textWidget.textSpan! as TextSpan; expect(span.children!.length, 2); expect(span.children, everyElement(isA<TextSpan>())); expect(span.children![0], isA<TextSpan>()); expect(span.children![0].toPlainText(), '[foo'); expectTextSpanStyle( span.children![0] as TextSpan, null, FontWeight.normal); expectTextSpanStyle( span.children![0] as TextSpan, null, FontWeight.normal); expect((span.children![1] as TextSpan).style!.fontFamily, 'monospace'); expect(linkTapResults, isNull); }, ); testWidgets( // Example 534 from GFM. 'autolinks take precedence over link grouping', (WidgetTester tester) async { const String data = '[foo<http://example.com/?search=](uri)>'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); final Text textWidget = tester.widget(find.byType(Text)); final TextSpan span = textWidget.textSpan! as TextSpan; expect(span.children!.length, 2); expect(span.children, everyElement(isA<TextSpan>())); expect(span.children![0].toPlainText(), '[foo'); expectTextSpanStyle( span.children![0] as TextSpan, null, FontWeight.normal); expectLinkTextSpan( span.children![1] as TextSpan, 'http://example.com/?search=](uri)'); expectLinkTap( linkTapResults, const MarkdownLink('http://example.com/?search=](uri)', 'http://example.com/?search=%5D(uri)')); }, ); }); group('Reference Link', () { testWidgets( // Example 535 from GFM. 'simple reference link', (WidgetTester tester) async { const String data = '[foo][bar]\n\n[bar]: /url "title"'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('foo'); expectLinkTap( linkTapResults, const MarkdownLink('foo', '/url', 'title')); }, ); testWidgets( // Example 536 from GFM. 'reference link with balanced brackets in link text', (WidgetTester tester) async { const String data = '[link [foo [bar]]][ref]\n\n[ref]: /uri'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('link [foo [bar]]'); expectLinkTap( linkTapResults, const MarkdownLink('link [foo [bar]]', '/uri')); }, ); testWidgets( // Example 537 from GFM. 'reference link with unbalanced but escaped bracket in link text', (WidgetTester tester) async { const String data = '[link \\[bar][ref]\n\n[ref]: /uri'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('link [bar'); expectLinkTap(linkTapResults, const MarkdownLink('link [bar', '/uri')); }, ); testWidgets( // Example 538 from GFM. 'reference link with inline emphasis and code span in link text', (WidgetTester tester) async { const String data = '[link *foo **bar** `#`*][ref]\n\n[ref]: /uri'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); final Text textWidget = tester.widget(find.byType(Text)); final TextSpan span = textWidget.textSpan! as TextSpan; expect(span.children!.length, 5); expect(span.children, everyElement(isA<TextSpan>())); expect(span.children![0].toPlainText(), 'link '); expectTextSpanStyle( span.children![0] as TextSpan, null, FontWeight.normal); expect(span.children![1].toPlainText(), 'foo '); expectTextSpanStyle( span.children![1] as TextSpan, FontStyle.italic, FontWeight.normal); expect(span.children![2].toPlainText(), 'bar'); expectTextSpanStyle( span.children![2] as TextSpan, FontStyle.italic, FontWeight.bold); expect(span.children![3].toPlainText(), ' '); expectTextSpanStyle( span.children![3] as TextSpan, FontStyle.italic, FontWeight.normal); expect(span.children![4].toPlainText(), '#'); expectTextSpanStyle( span.children![4] as TextSpan, null, FontWeight.normal); expect((span.children![4] as TextSpan).style!.fontFamily, 'monospace'); for (final InlineSpan element in span.children!) { final TextSpan textSpan = element as TextSpan; expect(textSpan.recognizer, isNotNull); expect(textSpan.recognizer, isA<TapGestureRecognizer>()); final TapGestureRecognizer? tapRecognizer = textSpan.recognizer as TapGestureRecognizer?; expect(tapRecognizer?.onTap, isNotNull); tapRecognizer!.onTap!(); expectLinkTap( linkTapResults, const MarkdownLink('link foo bar #', '/uri')); // Clear link tap results. linkTapResults = null; } }, ); testWidgets( // Example 539 from GFM. 'referenence link with inline image link text', (WidgetTester tester) async { const String data = '[![moon](moon.jpg)][ref]\n\n[ref]: /uri'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); final Finder gestureFinder = find.byType(GestureDetector); expect(gestureFinder, findsOneWidget); final GestureDetector gestureWidget = gestureFinder.evaluate().first.widget as GestureDetector; expect(gestureWidget.child, isA<Image>()); expect(gestureWidget.onTap, isNotNull); gestureWidget.onTap!(); expectLinkTap(linkTapResults, const MarkdownLink('moon', '/uri')); }, ); testWidgets( // Example 540 from GFM. 'reference links cannot have nested links', (WidgetTester tester) async { const String data = '[foo [bar](/uri)][ref]\n\n[ref]: /uri'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); final Text textWidget = tester.widget(find.byType(Text)); final TextSpan span = textWidget.textSpan! as TextSpan; expect(span.children!.length, 4); expect(span.children![0], isA<TextSpan>()); expect(span.children![0].toPlainText(), '[foo '); expectLinkTextSpan(span.children![1] as TextSpan, 'bar'); expectLinkTap(linkTapResults, const MarkdownLink('bar', '/uri')); expect(span.children![2], isA<TextSpan>()); expect(span.children![2].toPlainText(), ']'); expectLinkTextSpan(span.children![3] as TextSpan, 'ref'); expectLinkTap(linkTapResults, const MarkdownLink('ref', '/uri')); }, ); testWidgets( // Example 541 from GFM. 'reference links cannot have nested reference links', (WidgetTester tester) async { const String data = '[foo *bar [baz][ref]*][ref]\n\n[ref]: /uri'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); final Text textWidget = tester.widget(find.byType(Text)); final TextSpan span = textWidget.textSpan! as TextSpan; expect(span.children!.length, 5); expect(span.children![0], isA<TextSpan>()); expect(span.children![0].toPlainText(), '[foo '); expectTextSpanStyle( span.children![0] as TextSpan, null, FontWeight.normal); expect(span.children![1], isA<TextSpan>()); expect(span.children![1].toPlainText(), 'bar '); expectTextSpanStyle( span.children![1] as TextSpan, FontStyle.italic, FontWeight.normal); expectLinkTextSpan(span.children![2] as TextSpan, 'baz'); expectTextSpanStyle( span.children![2] as TextSpan, FontStyle.italic, FontWeight.normal); expectLinkTap(linkTapResults, const MarkdownLink('baz', '/uri')); expect(span.children![3], isA<TextSpan>()); expect(span.children![3].toPlainText(), ']'); expectTextSpanStyle( span.children![3] as TextSpan, null, FontWeight.normal); expectLinkTextSpan(span.children![4] as TextSpan, 'ref'); expectTextSpanStyle( span.children![4] as TextSpan, null, FontWeight.normal); expectLinkTap(linkTapResults, const MarkdownLink('ref', '/uri')); }, ); testWidgets( // Example 542 from GFM. 'reference link text grouping has precedence over emphasis grouping example 1', (WidgetTester tester) async { const String data = '*[foo*][ref]\n\n[ref]: /uri'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); final Text textWidget = tester.widget(find.byType(Text)); final TextSpan span = textWidget.textSpan! as TextSpan; expect(span.children!.length, 2); expect(span.children![0], isA<TextSpan>()); expect(span.children![0].toPlainText(), '*'); expectTextSpanStyle( span.children![0] as TextSpan, null, FontWeight.normal); expectLinkTextSpan(span.children![1] as TextSpan, 'foo*'); expectLinkTap(linkTapResults, const MarkdownLink('foo*', '/uri')); }, ); testWidgets( // Example 543 from GFM. 'reference link text grouping has precedence over emphasis grouping example 2', (WidgetTester tester) async { const String data = '[foo *bar][ref]*\n\n[ref]: /uri'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); final Text textWidget = tester.widget(find.byType(Text)); final TextSpan span = textWidget.textSpan! as TextSpan; expect(span.children!.length, 2); expectLinkTextSpan(span.children![0] as TextSpan, 'foo *bar'); expectTextSpanStyle( span.children![0] as TextSpan, null, FontWeight.normal); expectLinkTap(linkTapResults, const MarkdownLink('foo *bar', '/uri')); expect(span.children![1], isA<TextSpan>()); expect(span.children![1].toPlainText(), '*'); expectTextSpanStyle( span.children![0] as TextSpan, null, FontWeight.normal); }, ); testWidgets( // Example 544 from GFM. 'HTML tag takes precedence over reference link grouping', (WidgetTester tester) async { const String data = '[foo <bar attr="][ref]">\n\n[ref]: /uri'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); // Link is treated as ordinary text. expectInvalidLink('[foo <bar attr="][ref]">'); expect(linkTapResults, isNull); }, ); testWidgets( // Example 545 from GFM. 'code span takes precedence over reference link grouping', (WidgetTester tester) async { const String data = '[foo`][ref]`\n\n[ref]: /uri'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); final Finder gestureFinder = find.byType(GestureDetector); expect(gestureFinder, findsNothing); final Text textWidget = tester.widget(find.byType(Text)); final TextSpan span = textWidget.textSpan! as TextSpan; expect(span.children!.length, 2); expect(span.children, everyElement(isA<TextSpan>())); expect(span.children![0], isA<TextSpan>()); expect(span.children![0].toPlainText(), '[foo'); expectTextSpanStyle( span.children![0] as TextSpan, null, FontWeight.normal); expect(span.children![1].toPlainText(), '][ref]'); expect((span.children![1] as TextSpan).style!.fontFamily, 'monospace'); expect(linkTapResults, isNull); }, ); testWidgets( // Example 534 from GFM. 'autolinks take precedence over reference link grouping', (WidgetTester tester) async { const String data = '[foo<http://example.com/?search=][ref]>\n\n[ref]: /uri'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); final Text textWidget = tester.widget(find.byType(Text)); final TextSpan span = textWidget.textSpan! as TextSpan; expect(span.children!.length, 2); expect(span.children, everyElement(isA<TextSpan>())); expect(span.children![0].toPlainText(), '[foo'); expectTextSpanStyle( span.children![0] as TextSpan, null, FontWeight.normal); expectLinkTextSpan( span.children![1] as TextSpan, 'http://example.com/?search=][ref]'); expectLinkTap( linkTapResults, const MarkdownLink('http://example.com/?search=][ref]', 'http://example.com/?search=%5D%5Bref%5D')); }, ); testWidgets( // Example 547 from GFM. 'reference link matching is case-insensitive', (WidgetTester tester) async { const String data = '[foo][BaR]\n\n[bar]: /url "title"'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('foo'); expectLinkTap( linkTapResults, const MarkdownLink('foo', '/url', 'title')); }, ); testWidgets( // Example 548 from GFM. 'reference link support Unicode case fold - GFM', (WidgetTester tester) async { const String data = '[ẞ]\n\n[SS]: /url'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('ẞ'); expectLinkTap(linkTapResults, const MarkdownLink('ẞ', '/url', 'title')); }, // TODO(mjordan56): Remove skip once the issue #333 in the markdown package // is fixed and released. https://github.com/dart-lang/markdown/issues/333 skip: true, ); testWidgets( // Example 536 from CommonMark. NOTE: The CommonMark and GFM specifications // use different examples for Unicode case folding. Both are being added // to the test suite since each example produces different cases to test. 'reference link support Unicode case fold - CommonMark', (WidgetTester tester) async { const String data = '[Толпой][Толпой] is a Russian word.\n\n[ТОЛПОЙ]: /url'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); final Text textWidget = tester.widget(find.byType(Text)); final TextSpan span = textWidget.textSpan! as TextSpan; expect(span.children!.length, 2); expectLinkTextSpan(span.children![0] as TextSpan, 'Толпой'); expectLinkTap(linkTapResults, const MarkdownLink('Толпой', '/url')); expect(span.children![1], isA<TextSpan>()); expect(span.children![1].toPlainText(), ' is a Russian word.'); expectTextSpanStyle( span.children![0] as TextSpan, null, FontWeight.normal); }, ); testWidgets( // Example 549 from GFM. 'reference link with internal whitespace', (WidgetTester tester) async { const String data = '[Foo\n bar]: /url\n\n[Baz][Foo bar]'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('Baz'); expectLinkTap(linkTapResults, const MarkdownLink('Baz', '/url')); }, ); testWidgets( // Example 550 from GFM. 'reference link no whitespace between link text and link label', (WidgetTester tester) async { const String data = '[foo] [bar]\n\n[bar]: /url "title"'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); final Text textWidget = tester.widget(find.byType(Text)); final TextSpan span = textWidget.textSpan! as TextSpan; expect(span.children!.length, 2); expect(span.children![0], isA<TextSpan>()); expect(span.children![0].toPlainText(), '[foo] '); expectTextSpanStyle( span.children![0] as TextSpan, null, FontWeight.normal); expectLinkTextSpan(span.children![1] as TextSpan, 'bar'); expectLinkTap( linkTapResults, const MarkdownLink('bar', '/url', 'title')); }, ); testWidgets( // Example 551 from GFM. 'reference link no line break between link text and link label', (WidgetTester tester) async { const String data = '[foo]\n[bar]\n\n[bar]: /url "title"'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); final Text textWidget = tester.widget(find.byType(Text)); final TextSpan span = textWidget.textSpan! as TextSpan; expect(span.children!.length, 2); expect(span.children![0], isA<TextSpan>()); expect(span.children![0].toPlainText(), '[foo] '); expectTextSpanStyle( span.children![0] as TextSpan, null, FontWeight.normal); expectLinkTextSpan(span.children![1] as TextSpan, 'bar'); expectLinkTap( linkTapResults, const MarkdownLink('bar', '/url', 'title')); }, ); testWidgets( // Example 552 from GFM. 'multiple matching reference link definitions use first definition', (WidgetTester tester) async { const String data = '[foo]: /url1\n\n[foo]: /url2\n\n[bar][foo]'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('bar'); expectLinkTap(linkTapResults, const MarkdownLink('bar', '/url1')); }, ); testWidgets( // Example 553 from GFM. 'reference link matching is performed on normalized strings', (WidgetTester tester) async { const String data = '[bar][foo\\!]\n\n[foo!]: /url'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); // Link is treated as ordinary text. expectInvalidLink('[bar][foo!]'); expect(linkTapResults, isNull); }, ); testWidgets( // Example 554 from GFM. 'reference link labels cannot contain brackets - case 1', (WidgetTester tester) async { const String data = '[foo][ref[]\n\n[ref[]: /uri'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); final List<RichText> textWidgets = tester.widgetList(find.byType(RichText)).toList().cast<RichText>(); expect(textWidgets.length, 2); expect(textWidgets[0].text, isA<TextSpan>()); expect(textWidgets[0].text.toPlainText(), '[foo][ref[]'); expectTextSpanStyle( textWidgets[0].text as TextSpan, null, FontWeight.normal); expect(textWidgets[1].text, isA<TextSpan>()); expect(textWidgets[1].text.toPlainText(), '[ref[]: /uri'); expectTextSpanStyle( textWidgets[1].text as TextSpan, null, FontWeight.normal); expect(linkTapResults, isNull); }, // TODO(mjordan56): Remove skip once the issue #335 in the markdown package // is fixed and released. https://github.com/dart-lang/markdown/issues/335 skip: true, ); testWidgets( // Example 555 from GFM. 'reference link labels cannot contain brackets - case 2', (WidgetTester tester) async { const String data = '[foo][ref[bar]]\n\n[ref[bar]]: /uri'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); final List<Text> textWidgets = tester.widgetList(find.byType(Text)).toList().cast<Text>(); expect(textWidgets.length, 2); expect(textWidgets[0].textSpan, isNotNull); expect(textWidgets[0].textSpan, isA<TextSpan>()); expect(textWidgets[0].textSpan!.toPlainText(), '[foo][ref[bar]]'); expectTextSpanStyle( textWidgets[0].textSpan! as TextSpan, null, FontWeight.normal); expect(textWidgets[1].textSpan, isNotNull); expect(textWidgets[1].textSpan, isA<TextSpan>()); expect(textWidgets[1].textSpan!.toPlainText(), '[ref[bar]]: /uri'); expectTextSpanStyle( textWidgets[1].textSpan! as TextSpan, null, FontWeight.normal); expect(linkTapResults, isNull); }, ); testWidgets( // Example 556 from GFM. 'reference link labels cannot contain brackets - case 3', (WidgetTester tester) async { const String data = '[[[foo]]]\n\n[[[foo]]]: /url'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); final List<Text> textWidgets = tester.widgetList(find.byType(Text)).toList().cast<Text>(); expect(textWidgets.length, 2); expect(textWidgets[0].textSpan, isNotNull); expect(textWidgets[0].textSpan, isA<TextSpan>()); expect(textWidgets[0].textSpan!.toPlainText(), '[[[foo]]]'); expectTextSpanStyle( textWidgets[0].textSpan! as TextSpan, null, FontWeight.normal); expect(textWidgets[1].textSpan, isNotNull); expect(textWidgets[1].textSpan, isA<TextSpan>()); expect(textWidgets[1].textSpan!.toPlainText(), '[[[foo]]]: /url'); expectTextSpanStyle( textWidgets[1].textSpan! as TextSpan, null, FontWeight.normal); expect(linkTapResults, isNull); }, ); testWidgets( // Example 557 from GFM. 'reference link labels can have escaped brackets', (WidgetTester tester) async { const String data = '[foo][ref\\[]\n\n[ref\\[]: /uri'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('foo'); expectLinkTap(linkTapResults, const MarkdownLink('foo', '/uri')); }, ); testWidgets( // Example 558 from GFM. 'reference link labels can have escaped characters', (WidgetTester tester) async { const String data = '[bar\\]: /uri\n\n[bar\\]'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink(r'bar\'); expectLinkTap(linkTapResults, const MarkdownLink(r'bar\', '/uri')); }, // TODO(mjordan56): Remove skip once the issue #336 in the markdown package // is fixed and released. https://github.com/dart-lang/markdown/issues/336 skip: true, ); testWidgets( // Example 559 from GFM. 'reference link labels must contain at least on non-whitespace character - case 1', (WidgetTester tester) async { const String data = '[]\n\n[]: /uri'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); final List<Text> textWidgets = tester.widgetList(find.byType(Text)).toList().cast<Text>(); expect(textWidgets.length, 2); expect(textWidgets[0].textSpan, isNotNull); expect(textWidgets[0].textSpan, isA<TextSpan>()); expect(textWidgets[0].textSpan!.toPlainText(), '[]'); expectTextSpanStyle( textWidgets[0].textSpan! as TextSpan, null, FontWeight.normal); expect(textWidgets[1].textSpan, isNotNull); expect(textWidgets[1].textSpan, isA<TextSpan>()); expect(textWidgets[1].textSpan!.toPlainText(), '[]: /uri'); expectTextSpanStyle( textWidgets[1].textSpan! as TextSpan, null, FontWeight.normal); expect(linkTapResults, isNull); }, ); testWidgets( // Example 560 from GFM. 'reference link labels must contain at least on non-whitespace character - case 2', (WidgetTester tester) async { const String data = '[\n ]\n\n[\n ]: /uri'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); final List<Text> textWidgets = tester.widgetList(find.byType(Text)).toList().cast<Text>(); expect(textWidgets.length, 2); expect(textWidgets[0].textSpan, isNotNull); expect(textWidgets[0].textSpan, isA<TextSpan>()); expect(textWidgets[0].textSpan!.toPlainText(), '[ ]'); expectTextSpanStyle( textWidgets[0].textSpan! as TextSpan, null, FontWeight.normal); expect(textWidgets[1].textSpan, isNotNull); expect(textWidgets[1].textSpan, isA<TextSpan>()); expect(textWidgets[1].textSpan!.toPlainText(), '[ ]: /uri'); expectTextSpanStyle( textWidgets[1].textSpan! as TextSpan, null, FontWeight.normal); expect(linkTapResults, isNull); }, ); testWidgets( // Example 561 from GFM. 'collapsed reference link', (WidgetTester tester) async { const String data = '[foo][]\n\n[foo]: /url "title"'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('foo'); expectLinkTap( linkTapResults, const MarkdownLink('foo', '/url', 'title')); }, ); testWidgets( // Example 562 from GFM. 'collapsed reference link with inline emphasis in link text', (WidgetTester tester) async { const String data = '[*foo* bar][]\n\n[*foo* bar]: /url "title"'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); final Text textWidget = tester.widget(find.byType(Text)); final TextSpan span = textWidget.textSpan! as TextSpan; expect(span.children!.length, 2); expect(span.children, everyElement(isA<TextSpan>())); expect(span.children![0].toPlainText(), 'foo'); expectTextSpanStyle( span.children![0] as TextSpan, FontStyle.italic, FontWeight.normal); expect(span.children![1].toPlainText(), ' bar'); expectTextSpanStyle( span.children![1] as TextSpan, null, FontWeight.normal); for (final InlineSpan element in span.children!) { final TextSpan textSpan = element as TextSpan; expect(textSpan.recognizer, isNotNull); expect(textSpan.recognizer, isA<TapGestureRecognizer>()); final TapGestureRecognizer? tapRecognizer = textSpan.recognizer as TapGestureRecognizer?; expect(tapRecognizer?.onTap, isNotNull); tapRecognizer!.onTap!(); expectLinkTap( linkTapResults, const MarkdownLink('foo bar', '/url', 'title')); // Clear link tap results. linkTapResults = null; } }, ); testWidgets( // Example 563 from GFM. 'collapsed reference links are case-insensitive', (WidgetTester tester) async { const String data = '[Foo][]\n\n[foo]: /url "title"'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('Foo'); expectLinkTap( linkTapResults, const MarkdownLink('Foo', '/url', 'title')); }, ); testWidgets( // Example 564 from GFM. 'collapsed reference link no whitespace between link text and link label', (WidgetTester tester) async { const String data = '[foo] \n\n[]\n\n[foo]: /url "title"'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); final List<Text> textWidgets = tester.widgetList(find.byType(Text)).toList().cast<Text>(); expect(textWidgets.length, 2); expect(textWidgets[0].textSpan, isNotNull); expect(textWidgets[0].textSpan, isA<TextSpan>()); expect(textWidgets[0].textSpan!.toPlainText(), 'foo'); expect(textWidgets[0].textSpan, isNotNull); expect(textWidgets[0].textSpan, isA<TextSpan>()); expectLinkTextSpan(textWidgets[0].textSpan! as TextSpan, 'foo'); expectLinkTap( linkTapResults, const MarkdownLink('foo', '/url', 'title')); expect(textWidgets[1].textSpan, isNotNull); expect(textWidgets[1].textSpan, isA<TextSpan>()); expect(textWidgets[1].textSpan!.toPlainText(), '[]'); expectTextSpanStyle( textWidgets[1].textSpan! as TextSpan, null, FontWeight.normal); }, ); testWidgets( // Example 565 from GFM. 'shortcut reference link', (WidgetTester tester) async { const String data = '[foo]\n\n[foo]: /url "title"'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('foo'); expectLinkTap( linkTapResults, const MarkdownLink('foo', '/url', 'title')); }, ); testWidgets( // Example 566 from GFM. 'shortcut reference link with inline emphasis in link text', (WidgetTester tester) async { const String data = '[*foo* bar]\n\n[*foo* bar]: /url "title"'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); final Text textWidget = tester.widget(find.byType(Text)); final TextSpan span = textWidget.textSpan! as TextSpan; expect(span.children!.length, 2); expect(span.children, everyElement(isA<TextSpan>())); expect(span.children![0].toPlainText(), 'foo'); expectTextSpanStyle( span.children![0] as TextSpan, FontStyle.italic, FontWeight.normal); expect(span.children![1].toPlainText(), ' bar'); expectTextSpanStyle( span.children![1] as TextSpan, null, FontWeight.normal); for (final InlineSpan element in span.children!) { final TextSpan textSpan = element as TextSpan; expect(textSpan.recognizer, isNotNull); expect(textSpan.recognizer, isA<TapGestureRecognizer>()); final TapGestureRecognizer? tapRecognizer = textSpan.recognizer as TapGestureRecognizer?; expect(tapRecognizer?.onTap, isNotNull); tapRecognizer!.onTap!(); expectLinkTap( linkTapResults, const MarkdownLink('foo bar', '/url', 'title')); // Clear link tap results. linkTapResults = null; } }, ); testWidgets( // Example 567 from GFM. 'shortcut reference link with inline emphasis nested in link text', (WidgetTester tester) async { const String data = '[*foo* bar]\n\n[*foo* bar]: /url "title"'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); final Text textWidget = tester.widget(find.byType(Text)); final TextSpan span = textWidget.textSpan! as TextSpan; expect(span.children!.length, 2); expect(span.children, everyElement(isA<TextSpan>())); expect(span.children![0].toPlainText(), 'foo'); expectTextSpanStyle( span.children![0] as TextSpan, FontStyle.italic, FontWeight.normal); expect(span.children![1].toPlainText(), ' bar'); expectTextSpanStyle( span.children![1] as TextSpan, null, FontWeight.normal); for (final InlineSpan element in span.children!) { final TextSpan textSpan = element as TextSpan; expect(textSpan.recognizer, isNotNull); expect(textSpan.recognizer, isA<TapGestureRecognizer>()); final TapGestureRecognizer? tapRecognizer = textSpan.recognizer as TapGestureRecognizer?; expect(tapRecognizer?.onTap, isNotNull); tapRecognizer!.onTap!(); expectLinkTap( linkTapResults, const MarkdownLink('foo bar', '/url', 'title')); // Clear link tap results. linkTapResults = null; } }, ); testWidgets( // Example 568 from GFM. 'shortcut reference link with unbalanced open square brackets', (WidgetTester tester) async { const String data = '[[bar [foo]\n\n[foo]: /url'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); final Text textWidget = tester.widget(find.byType(Text)); final TextSpan span = textWidget.textSpan! as TextSpan; expect(span.children!.length, 2); expect(span.children![0], isA<TextSpan>()); expect(span.children![0].toPlainText(), '[[bar '); expectTextSpanStyle( span.children![0] as TextSpan, null, FontWeight.normal); expectLinkTextSpan(span.children![1] as TextSpan, 'foo'); expectLinkTap(linkTapResults, const MarkdownLink('foo', '/url')); }, ); testWidgets( // Example 569 from GFM. 'shortcut reference links are case-insensitive', (WidgetTester tester) async { const String data = '[Foo]\n\n[foo]: /url "title"'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('Foo'); expectLinkTap( linkTapResults, const MarkdownLink('Foo', '/url', 'title')); }, ); testWidgets( // Example 570 from GFM. 'shortcut reference link should preserve space after link text', (WidgetTester tester) async { const String data = '[foo] bar\n\n[foo]: /url'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); final Text textWidget = tester.widget(find.byType(Text)); final TextSpan span = textWidget.textSpan! as TextSpan; expect(span.children!.length, 2); expectLinkTextSpan(span.children![0] as TextSpan, 'foo'); expectLinkTap(linkTapResults, const MarkdownLink('foo', '/url')); expect(span.children![1], isA<TextSpan>()); expect(span.children![1].toPlainText(), ' bar'); expectTextSpanStyle( span.children![1] as TextSpan, null, FontWeight.normal); }, ); testWidgets( // Example 571 from GFM. 'shortcut reference link backslash escape opening bracket to avoid link', (WidgetTester tester) async { const String data = '\\[foo]\n\n[foo]: /url "title"'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); // Link is treated as ordinary text. expectInvalidLink('[foo]'); expect(linkTapResults, isNull); }, ); testWidgets( // Example 572 from GFM. 'shortcut reference link text grouping has precedence over emphasis grouping', (WidgetTester tester) async { const String data = '[foo*]: /url\n\n*[foo*]'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); final Text textWidget = tester.widget(find.byType(Text)); final TextSpan span = textWidget.textSpan! as TextSpan; expect(span.children!.length, 2); expect(span.children![0], isA<TextSpan>()); expect(span.children![0].toPlainText(), '*'); expectTextSpanStyle( span.children![0] as TextSpan, null, FontWeight.normal); expectLinkTextSpan(span.children![1] as TextSpan, 'foo*'); expectLinkTap(linkTapResults, const MarkdownLink('foo*', '/url')); }, ); testWidgets( // Example 573 from GFM. 'full link reference takes precedence over shortcut link reference', (WidgetTester tester) async { const String data = '[foo][bar]\n\n[foo]: /url1\n[bar]: /url2'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('foo'); expectLinkTap(linkTapResults, const MarkdownLink('foo', '/url2')); }, ); testWidgets( // Example 574 from GFM. 'compact link reference takes precedence over shortcut link reference', (WidgetTester tester) async { const String data = '[foo][]\n\n[foo]: /url1'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('foo'); expectLinkTap(linkTapResults, const MarkdownLink('foo', '/url1')); }, ); testWidgets( // Example 575 from GFM. 'inline link reference, no link destination takes precedence over shortcut link reference', (WidgetTester tester) async { const String data = '[foo]()\n\n[foo]: /url1'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); expectValidLink('foo'); expectLinkTap(linkTapResults, const MarkdownLink('foo', '')); }, ); testWidgets( // Example 576 from GFM. 'inline link reference, invalid link destination is a link followed by text', (WidgetTester tester) async { const String data = '[foo](not a link)\n\n[foo]: /url1'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); final Text textWidget = tester.widget(find.byType(Text)); final TextSpan span = textWidget.textSpan! as TextSpan; expect(span.children!.length, 2); expectLinkTextSpan(span.children![0] as TextSpan, 'foo'); expectLinkTap(linkTapResults, const MarkdownLink('foo', '/url1')); expect(span.children![1], isA<TextSpan>()); expect(span.children![1].toPlainText(), '(not a link)'); expectTextSpanStyle( span.children![1] as TextSpan, null, FontWeight.normal); }, ); testWidgets( // Example 577 from GFM. 'three sequential runs of square-bracketed text, normal text and a link reference', (WidgetTester tester) async { const String data = '[foo][bar][baz]\n\n[baz]: /url'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); final Text textWidget = tester.widget(find.byType(Text)); final TextSpan span = textWidget.textSpan! as TextSpan; expect(span.children!.length, 2); expect(span.children![0], isA<TextSpan>()); expect(span.children![0].toPlainText(), '[foo]'); expectTextSpanStyle( span.children![0] as TextSpan, null, FontWeight.normal); expectLinkTextSpan(span.children![1] as TextSpan, 'bar'); expectLinkTap(linkTapResults, const MarkdownLink('bar', '/url')); }, ); testWidgets( // Example 578 from GFM. 'three sequential runs of square-bracketed text, two link references', (WidgetTester tester) async { const String data = '[foo][bar][baz]\n\n[baz]: /url1\n[bar]: /url2'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); final Text textWidget = tester.widget(find.byType(Text)); final TextSpan span = textWidget.textSpan! as TextSpan; expect(span.children!.length, 2); expectLinkTextSpan(span.children![0] as TextSpan, 'foo'); expectLinkTap(linkTapResults, const MarkdownLink('foo', '/url2')); expectLinkTextSpan(span.children![1] as TextSpan, 'baz'); expectLinkTap(linkTapResults, const MarkdownLink('baz', '/url1')); }, ); testWidgets( // Example 579 from GFM. 'full reference link followed by a shortcut reference link', (WidgetTester tester) async { const String data = '[foo][bar][baz]\n\n[baz]: /url1\n[foo]: /url2'; MarkdownLink? linkTapResults; await tester.pumpWidget( boilerplate( MarkdownBody( data: data, onTapLink: (String text, String? href, String title) => linkTapResults = MarkdownLink(text, href, title), ), ), ); final Text textWidget = tester.widget(find.byType(Text)); final TextSpan span = textWidget.textSpan! as TextSpan; expect(span.children!.length, 2); expect(span.children![0], isA<TextSpan>()); expect(span.children![0].toPlainText(), '[foo]'); expectLinkTextSpan(span.children![1] as TextSpan, 'bar'); expectLinkTap(linkTapResults, const MarkdownLink('bar', '/url1')); }, ); }); }
packages/packages/flutter_markdown/test/link_test.dart/0
{ "file_path": "packages/packages/flutter_markdown/test/link_test.dart", "repo_id": "packages", "token_count": 42931 }
959
// 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:process/process.dart'; import '../base/command.dart'; import '../base/file_system.dart'; import '../base/logger.dart'; import '../base/project.dart'; import '../base/terminal.dart'; import '../utils.dart'; /// Abandons the existing migration by deleting the migrate working directory. class MigrateAbandonCommand extends MigrateCommand { MigrateAbandonCommand({ required this.logger, required this.fileSystem, required this.terminal, required ProcessManager processManager, this.standalone = false, }) : migrateUtils = MigrateUtils( logger: logger, fileSystem: fileSystem, processManager: processManager, ) { argParser.addOption( 'staging-directory', help: 'Specifies the custom migration working directory used to stage ' 'and edit proposed changes. This path can be absolute or relative ' 'to the flutter project root. This defaults to ' '`$kDefaultMigrateStagingDirectoryName`', valueHelp: 'path', ); argParser.addOption( 'project-directory', help: 'The root directory of the flutter project. This defaults to the ' 'current working directory if omitted.', valueHelp: 'path', ); argParser.addFlag( 'force', abbr: 'f', help: 'Delete the migrate working directory without asking for confirmation.', ); argParser.addFlag( 'flutter-subcommand', help: 'Enable when using the flutter tool as a subcommand. This changes the ' 'wording of log messages to indicate the correct suggested commands to use.', ); } final Logger logger; final FileSystem fileSystem; final Terminal terminal; final MigrateUtils migrateUtils; final bool standalone; @override final String name = 'abandon'; @override final String description = 'Deletes the current active migration working directory.'; @override Future<CommandResult> runCommand() async { final String? projectDirectory = stringArg('project-directory'); final FlutterProjectFactory flutterProjectFactory = FlutterProjectFactory(); final FlutterProject project = projectDirectory == null ? FlutterProject.current(fileSystem) : flutterProjectFactory .fromDirectory(fileSystem.directory(projectDirectory)); final bool isSubcommand = boolArg('flutter-subcommand') ?? !standalone; if (!validateWorkingDirectory(project, logger)) { return const CommandResult(ExitStatus.fail); } Directory stagingDirectory = project.directory.childDirectory(kDefaultMigrateStagingDirectoryName); final String? customStagingDirectoryPath = stringArg('staging-directory'); if (customStagingDirectoryPath != null) { if (fileSystem.path.isAbsolute(customStagingDirectoryPath)) { stagingDirectory = fileSystem.directory(customStagingDirectoryPath); } else { stagingDirectory = project.directory.childDirectory(customStagingDirectoryPath); } if (!stagingDirectory.existsSync()) { logger.printError( 'Provided staging directory `$customStagingDirectoryPath` ' 'does not exist or is not valid.'); return const CommandResult(ExitStatus.fail); } } if (!stagingDirectory.existsSync()) { logger .printStatus('No migration in progress. Start a new migration with:'); printCommandText('start', logger, standalone: !isSubcommand); return const CommandResult(ExitStatus.fail); } logger.printStatus('\nAbandoning the existing migration will delete the ' 'migration staging directory at ${stagingDirectory.path}'); final bool force = boolArg('force') ?? false; if (!force) { String selection = 'y'; terminal.usesTerminalUi = true; try { selection = await terminal.promptForCharInput( <String>['y', 'n'], logger: logger, prompt: 'Are you sure you wish to continue with abandoning? (y)es, (N)o', defaultChoiceIndex: 1, ); } on StateError catch (e) { logger.printError( e.message, indent: 0, ); } if (selection != 'y') { return const CommandResult(ExitStatus.success); } } try { stagingDirectory.deleteSync(recursive: true); } on FileSystemException catch (e) { logger.printError('Deletion failed with: $e'); logger.printError( 'Please manually delete the staging directory at `${stagingDirectory.path}`'); } logger.printStatus('\nAbandon complete. Start a new migration with:'); printCommandText('start', logger, standalone: !isSubcommand); return const CommandResult(ExitStatus.success); } }
packages/packages/flutter_migrate/lib/src/commands/abandon.dart/0
{ "file_path": "packages/packages/flutter_migrate/lib/src/commands/abandon.dart", "repo_id": "packages", "token_count": 1782 }
960
// 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:args/command_runner.dart'; import 'package:flutter_migrate/src/base/command.dart'; export 'package:test/test.dart' hide isInstanceOf, test; CommandRunner<void> createTestCommandRunner([MigrateCommand? command]) { final CommandRunner<void> runner = TestCommandRunner(); if (command != null) { runner.addCommand(command); } return runner; } class TestCommandRunner extends CommandRunner<void> { TestCommandRunner() : super( 'flutter', 'Manage your Flutter app development.\n' '\n' 'Common commands:\n' '\n' ' flutter create <output directory>\n' ' Create a new Flutter project in the specified directory.\n' '\n' ' flutter run [options]\n' ' Run your Flutter application on an attached device or in an emulator.', ); }
packages/packages/flutter_migrate/test/src/test_flutter_command_runner.dart/0
{ "file_path": "packages/packages/flutter_migrate/test/src/test_flutter_command_runner.dart", "repo_id": "packages", "token_count": 424 }
961
When a deep link is received from the platform, GoRouter will display the configured screen based on the URL path. To configure your Android or iOS app for deep linking, see the [Deep linking](https://docs.flutter.dev/development/ui/navigation/deep-linking) documentation at flutter.dev.
packages/packages/go_router/doc/deep-linking.md/0
{ "file_path": "packages/packages/go_router/doc/deep-linking.md", "repo_id": "packages", "token_count": 76 }
962
// 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'; import '../data.dart'; import '../widgets/author_list.dart'; /// A screen that displays a list of authors. class AuthorsScreen extends StatelessWidget { /// Creates an [AuthorsScreen]. const AuthorsScreen({super.key}); /// The title of the screen. static const String title = 'Authors'; @override Widget build(BuildContext context) => Scaffold( appBar: AppBar( title: const Text(title), ), body: AuthorList( authors: libraryInstance.allAuthors, onTap: (Author author) { context.go('/author/${author.id}'); }, ), ); }
packages/packages/go_router/example/lib/books/src/screens/authors.dart/0
{ "file_path": "packages/packages/go_router/example/lib/books/src/screens/authors.dart", "repo_id": "packages", "token_count": 323 }
963
// 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'; void main() => runApp(App()); /// The main app. class App extends StatelessWidget { /// Creates an [App]. App({super.key}); /// The title of the app. static const String title = 'GoRouter Example: Initial Location'; @override Widget build(BuildContext context) => MaterialApp.router( routerConfig: _router, title: title, ); final GoRouter _router = GoRouter( initialLocation: '/page3', routes: <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, GoRouterState state) => const Page1Screen(), ), GoRoute( path: '/page2', builder: (BuildContext context, GoRouterState state) => const Page2Screen(), ), GoRoute( path: '/page3', builder: (BuildContext context, GoRouterState state) => const Page3Screen(), ), ], ); } /// The screen of the first page. class Page1Screen extends StatelessWidget { /// Creates a [Page1Screen]. const Page1Screen({super.key}); @override Widget build(BuildContext context) => Scaffold( appBar: AppBar(title: const Text(App.title)), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ElevatedButton( onPressed: () => context.go('/page2'), child: const Text('Go to page 2'), ), ], ), ), ); } /// The screen of the second page. class Page2Screen extends StatelessWidget { /// Creates a [Page2Screen]. const Page2Screen({super.key}); @override Widget build(BuildContext context) => Scaffold( appBar: AppBar(title: const Text(App.title)), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ElevatedButton( onPressed: () => context.go('/'), child: const Text('Go to home page'), ), ], ), ), ); } /// The screen of the third page. class Page3Screen extends StatelessWidget { /// Creates a [Page3Screen]. const Page3Screen({super.key}); @override Widget build(BuildContext context) => Scaffold( appBar: AppBar(title: const Text(App.title)), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ ElevatedButton( onPressed: () => context.go('/page2'), child: const Text('Go to page 2'), ), ], ), ), ); }
packages/packages/go_router/example/lib/others/init_loc.dart/0
{ "file_path": "packages/packages/go_router/example/lib/others/init_loc.dart", "repo_id": "packages", "token_count": 1300 }
964
// 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/go_router.dart'; import 'package:go_router_examples/push_with_shell_route.dart' as example; void main() { testWidgets('example works', (WidgetTester tester) async { await tester.pumpWidget(example.PushWithShellRouteExampleApp()); expect(find.text('shell1'), findsOneWidget); await tester.tap(find.text('push the same shell route /shell1')); await tester.pumpAndSettle(); expect(find.text('shell1'), findsOneWidget); expect(find.text('shell1 body'), findsOneWidget); find.text('shell1 body').evaluate().first.pop(); await tester.pumpAndSettle(); expect(find.text('shell1'), findsOneWidget); expect(find.text('shell1 body'), findsNothing); await tester.tap(find.text('push the different shell route /shell2')); await tester.pumpAndSettle(); expect(find.text('shell1'), findsNothing); expect(find.text('shell2'), findsOneWidget); expect(find.text('shell2 body'), findsOneWidget); find.text('shell2 body').evaluate().first.pop(); await tester.pumpAndSettle(); expect(find.text('shell1'), findsOneWidget); expect(find.text('shell2'), findsNothing); await tester.tap(find.text('push the regular route /regular-route')); await tester.pumpAndSettle(); expect(find.text('shell1'), findsNothing); expect(find.text('regular route'), findsOneWidget); find.text('regular route').evaluate().first.pop(); await tester.pumpAndSettle(); expect(find.text('shell1'), findsOneWidget); expect(find.text('regular route'), findsNothing); }); }
packages/packages/go_router/example/test/push_with_shell_route_test.dart/0
{ "file_path": "packages/packages/go_router/example/test/push_with_shell_route_test.dart", "repo_id": "packages", "token_count": 601 }
965
// 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:developer' as developer; import 'package:flutter/foundation.dart'; import 'package:logging/logging.dart'; /// The logger for this package. @visibleForTesting final Logger logger = Logger('GoRouter'); /// Whether or not the logging is enabled. bool _enabled = false; /// Logs the message if logging is enabled. void log(String message, {Level level = Level.INFO}) { if (_enabled) { logger.log(level, message); } } StreamSubscription<LogRecord>? _subscription; /// Forwards diagnostic messages to the dart:developer log() API. void setLogging({bool enabled = false}) { _subscription?.cancel(); _enabled = enabled; if (!enabled) { return; } _subscription = logger.onRecord.listen((LogRecord e) { // use `dumpErrorToConsole` for severe messages to ensure that severe // exceptions are formatted consistently with other Flutter examples and // avoids printing duplicate exceptions if (e.level >= Level.SEVERE) { final Object? error = e.error; FlutterError.dumpErrorToConsole( FlutterErrorDetails( exception: error is Exception ? error : Exception(error), stack: e.stackTrace, library: e.loggerName, context: ErrorDescription(e.message), ), ); } else { developer.log( e.message, time: e.time, sequenceNumber: e.sequenceNumber, level: e.level.value, name: e.loggerName, zone: e.zone, error: e.error, stackTrace: e.stackTrace, ); } }); }
packages/packages/go_router/lib/src/logging.dart/0
{ "file_path": "packages/packages/go_router/lib/src/logging.dart", "repo_id": "packages", "token_count": 633 }
966
# This custom rule set only exists to allow very targeted changes # relative to the default repo settings, for specific use cases. # Please do NOT add more changes here without consulting with # #hackers-ecosystem on Discord. include: ../../../analysis_options.yaml linter: rules: # Matches flutter/flutter, which disables this rule due to false positives # from navigator APIs. unawaited_futures: false
packages/packages/go_router/test/analysis_options.yaml/0
{ "file_path": "packages/packages/go_router/test/analysis_options.yaml", "repo_id": "packages", "token_count": 118 }
967
// 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:go_router/go_router.dart'; import 'test_helpers.dart'; void main() { group('updateShouldNotify', () { test('does not update when goRouter does not change', () { final GoRouter goRouter = GoRouter( routes: <GoRoute>[ GoRoute( path: '/', builder: (_, __) => const Page1(), ), ], ); final bool shouldNotify = setupInheritedGoRouterChange( oldGoRouter: goRouter, newGoRouter: goRouter, ); expect(shouldNotify, false); }); test('does not update even when goRouter changes', () { final GoRouter oldGoRouter = GoRouter( routes: <GoRoute>[ GoRoute( path: '/', builder: (_, __) => const Page1(), ), ], ); final GoRouter newGoRouter = GoRouter( routes: <GoRoute>[ GoRoute( path: '/', builder: (_, __) => const Page2(), ), ], ); final bool shouldNotify = setupInheritedGoRouterChange( oldGoRouter: oldGoRouter, newGoRouter: newGoRouter, ); expect(shouldNotify, false); }); }); test('adds [goRouter] as a diagnostics property', () { final GoRouter goRouter = GoRouter( routes: <GoRoute>[ GoRoute( path: '/', builder: (_, __) => const Page1(), ), ], ); final InheritedGoRouter inheritedGoRouter = InheritedGoRouter( goRouter: goRouter, child: Container(), ); final DiagnosticPropertiesBuilder properties = DiagnosticPropertiesBuilder(); inheritedGoRouter.debugFillProperties(properties); expect(properties.properties.length, 1); expect(properties.properties.first, isA<DiagnosticsProperty<GoRouter>>()); expect(properties.properties.first.value, goRouter); }); testWidgets("mediates Widget's access to GoRouter.", (WidgetTester tester) async { final MockGoRouter router = MockGoRouter(); await tester.pumpWidget(MaterialApp( home: InheritedGoRouter(goRouter: router, child: const _MyWidget()))); await tester.tap(find.text('My Page')); expect(router.latestPushedName, 'my_page'); }); testWidgets('builder can access GoRouter', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/110512. late final GoRouter buildContextRouter; final GoRouter router = GoRouter( initialLocation: '/', routes: <GoRoute>[ GoRoute( path: '/', builder: (BuildContext context, __) { buildContextRouter = GoRouter.of(context); return const DummyScreen(); }, ) ], ); addTearDown(router.dispose); await tester.pumpWidget( MaterialApp.router( routeInformationProvider: router.routeInformationProvider, routeInformationParser: router.routeInformationParser, routerDelegate: router.routerDelegate), ); expect(buildContextRouter, isNotNull); expect(buildContextRouter, equals(router)); }); } bool setupInheritedGoRouterChange({ required GoRouter oldGoRouter, required GoRouter newGoRouter, }) { final InheritedGoRouter oldInheritedGoRouter = InheritedGoRouter( goRouter: oldGoRouter, child: Container(), ); final InheritedGoRouter newInheritedGoRouter = InheritedGoRouter( goRouter: newGoRouter, child: Container(), ); return newInheritedGoRouter.updateShouldNotify( oldInheritedGoRouter, ); } class Page1 extends StatelessWidget { const Page1({super.key}); @override Widget build(BuildContext context) => Container(); } class Page2 extends StatelessWidget { const Page2({super.key}); @override Widget build(BuildContext context) => Container(); } class _MyWidget extends StatelessWidget { const _MyWidget(); @override Widget build(BuildContext context) { return ElevatedButton( onPressed: () => context.pushNamed('my_page'), child: const Text('My Page')); } } class MockGoRouter extends GoRouter { MockGoRouter() : super.routingConfig( routingConfig: const ConstantRoutingConfig( RoutingConfig(routes: <RouteBase>[]))); late String latestPushedName; @override Future<T?> pushNamed<T extends Object?>(String name, {Map<String, String> pathParameters = const <String, String>{}, Map<String, dynamic> queryParameters = const <String, dynamic>{}, Object? extra}) { latestPushedName = name; return Future<T?>.value(); } @override BackButtonDispatcher get backButtonDispatcher => RootBackButtonDispatcher(); }
packages/packages/go_router/test/inherited_test.dart/0
{ "file_path": "packages/packages/go_router/test/inherited_test.dart", "repo_id": "packages", "token_count": 1994 }
968
// 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, unreachable_from_main import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; part 'extra_example.g.dart'; void main() => runApp(const App()); final GoRouter _router = GoRouter( routes: $appRoutes, initialLocation: '/splash', ); class App extends StatelessWidget { const App({super.key}); @override Widget build(BuildContext context) { return MaterialApp.router( routerConfig: _router, ); } } class Extra { const Extra(this.value); final int value; } @TypedGoRoute<RequiredExtraRoute>(path: '/requiredExtra') class RequiredExtraRoute extends GoRouteData { const RequiredExtraRoute({required this.$extra}); final Extra $extra; @override Widget build(BuildContext context, GoRouterState state) => RequiredExtraScreen(extra: $extra); } class RequiredExtraScreen extends StatelessWidget { const RequiredExtraScreen({super.key, required this.extra}); final Extra extra; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Required Extra')), body: Center(child: Text('Extra: ${extra.value}')), ); } } @TypedGoRoute<OptionalExtraRoute>(path: '/optionalExtra') class OptionalExtraRoute extends GoRouteData { const OptionalExtraRoute({this.$extra}); final Extra? $extra; @override Widget build(BuildContext context, GoRouterState state) => OptionalExtraScreen(extra: $extra); } class OptionalExtraScreen extends StatelessWidget { const OptionalExtraScreen({super.key, this.extra}); final Extra? extra; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Optional Extra')), body: Center(child: Text('Extra: ${extra?.value}')), ); } } @TypedGoRoute<SplashRoute>(path: '/splash') class SplashRoute extends GoRouteData { const SplashRoute(); @override Widget build(BuildContext context, GoRouterState state) => const Splash(); } class Splash extends StatelessWidget { const Splash({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('Splash')), body: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ const Placeholder(), ElevatedButton( onPressed: () => const RequiredExtraRoute($extra: Extra(1)).go(context), child: const Text('Required Extra'), ), ElevatedButton( onPressed: () => const OptionalExtraRoute($extra: Extra(2)).go(context), child: const Text('Optional Extra'), ), ElevatedButton( onPressed: () => const OptionalExtraRoute().go(context), child: const Text('Optional Extra (null)'), ), ], ), ); } }
packages/packages/go_router_builder/example/lib/extra_example.dart/0
{ "file_path": "packages/packages/go_router_builder/example/lib/extra_example.dart", "repo_id": "packages", "token_count": 1115 }
969
// GENERATED CODE - DO NOT MODIFY BY HAND // ignore_for_file: always_specify_types, public_member_api_docs part of 'stateful_shell_route_initial_location_example.dart'; // ************************************************************************** // GoRouterGenerator // ************************************************************************** List<RouteBase> get $appRoutes => [ $mainShellRouteData, ]; RouteBase get $mainShellRouteData => StatefulShellRouteData.$route( factory: $MainShellRouteDataExtension._fromState, branches: [ StatefulShellBranchData.$branch( routes: [ GoRouteData.$route( path: '/home', factory: $HomeRouteDataExtension._fromState, ), ], ), StatefulShellBranchData.$branch( initialLocation: NotificationsShellBranchData.$initialLocation, routes: [ GoRouteData.$route( path: '/notifications/:section', factory: $NotificationsRouteDataExtension._fromState, ), ], ), StatefulShellBranchData.$branch( routes: [ GoRouteData.$route( path: '/orders', factory: $OrdersRouteDataExtension._fromState, ), ], ), ], ); extension $MainShellRouteDataExtension on MainShellRouteData { static MainShellRouteData _fromState(GoRouterState state) => const MainShellRouteData(); } extension $HomeRouteDataExtension on HomeRouteData { static HomeRouteData _fromState(GoRouterState state) => const HomeRouteData(); String get location => GoRouteData.$location( '/home', ); 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 $NotificationsRouteDataExtension on NotificationsRouteData { static NotificationsRouteData _fromState(GoRouterState state) => NotificationsRouteData( section: _$NotificationsPageSectionEnumMap ._$fromName(state.pathParameters['section']!), ); String get location => GoRouteData.$location( '/notifications/${Uri.encodeComponent(_$NotificationsPageSectionEnumMap[section]!)}', ); 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 _$NotificationsPageSectionEnumMap = { NotificationsPageSection.latest: 'latest', NotificationsPageSection.old: 'old', NotificationsPageSection.archive: 'archive', }; extension $OrdersRouteDataExtension on OrdersRouteData { static OrdersRouteData _fromState(GoRouterState state) => const OrdersRouteData(); String get location => GoRouteData.$location( '/orders', ); 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<T extends Enum> on Map<T, String> { T _$fromName(String value) => entries.singleWhere((element) => element.value == value).key; }
packages/packages/go_router_builder/example/lib/stateful_shell_route_initial_location_example.g.dart/0
{ "file_path": "packages/packages/go_router_builder/example/lib/stateful_shell_route_initial_location_example.g.dart", "repo_id": "packages", "token_count": 1278 }
970
// 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:go_router_builder/src/path_utils.dart'; import 'package:test/test.dart'; void main() { group('pathParametersFromPattern', () { test('It should return the parameters of the path', () { expect(pathParametersFromPattern('/'), const <String>{}); expect(pathParametersFromPattern('/user'), const <String>{}); expect(pathParametersFromPattern('/user/:id'), const <String>{'id'}); expect(pathParametersFromPattern('/user/:id/book'), const <String>{'id'}); expect( pathParametersFromPattern('/user/:id/book/:bookId'), const <String>{'id', 'bookId'}, ); }); }); group('patternToPath', () { test('It should replace the path parameters with their values', () { expect(patternToPath('/', const <String, String>{}), '/'); expect(patternToPath('/user', const <String, String>{}), '/user'); expect( patternToPath('/user/:id', const <String, String>{'id': 'user-id'}), '/user/user-id'); expect( patternToPath( '/user/:id/book', const <String, String>{'id': 'user-id'}), '/user/user-id/book'); expect( patternToPath('/user/:id/book/:bookId', const <String, String>{'id': 'user-id', 'bookId': 'book-id'}), '/user/user-id/book/book-id', ); }); }); }
packages/packages/go_router_builder/test/path_utils_test.dart/0
{ "file_path": "packages/packages/go_router_builder/test/path_utils_test.dart", "repo_id": "packages", "token_count": 609 }
971
RouteBase get $namedEscapedRoute => GoRouteData.$route( path: '/named-route', name: r'named$Route', factory: $NamedEscapedRouteExtension._fromState, ); extension $NamedEscapedRouteExtension on NamedEscapedRoute { static NamedEscapedRoute _fromState(GoRouterState state) => NamedEscapedRoute(); String get location => GoRouteData.$location( '/named-route', ); 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/test_inputs/named_escaped_route.dart.expect/0
{ "file_path": "packages/packages/go_router_builder/test_inputs/named_escaped_route.dart.expect", "repo_id": "packages", "token_count": 231 }
972
RouteBase get $shellRouteNoConstConstructor => ShellRouteData.$route( factory: $ShellRouteNoConstConstructorExtension._fromState, ); extension $ShellRouteNoConstConstructorExtension on ShellRouteNoConstConstructor { static ShellRouteNoConstConstructor _fromState(GoRouterState state) => ShellRouteNoConstConstructor(); } RouteBase get $shellRouteWithConstConstructor => ShellRouteData.$route( factory: $ShellRouteWithConstConstructorExtension._fromState, ); extension $ShellRouteWithConstConstructorExtension on ShellRouteWithConstConstructor { static ShellRouteWithConstConstructor _fromState(GoRouterState state) => const ShellRouteWithConstConstructor(); }
packages/packages/go_router_builder/test_inputs/shell_route_data.dart.expect/0
{ "file_path": "packages/packages/go_router_builder/test_inputs/shell_route_data.dart.expect", "repo_id": "packages", "token_count": 210 }
973
# 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: 822f6e3595d63f864ae2027ea37fd645b313b71b channel: master project_type: app # Tracks metadata for the flutter migrate command migration: platforms: - platform: root create_revision: 822f6e3595d63f864ae2027ea37fd645b313b71b base_revision: 822f6e3595d63f864ae2027ea37fd645b313b71b - platform: android create_revision: 822f6e3595d63f864ae2027ea37fd645b313b71b base_revision: 822f6e3595d63f864ae2027ea37fd645b313b71b - platform: ios create_revision: 822f6e3595d63f864ae2027ea37fd645b313b71b base_revision: 822f6e3595d63f864ae2027ea37fd645b313b71b - platform: linux create_revision: 822f6e3595d63f864ae2027ea37fd645b313b71b base_revision: 822f6e3595d63f864ae2027ea37fd645b313b71b - platform: macos create_revision: 822f6e3595d63f864ae2027ea37fd645b313b71b base_revision: 822f6e3595d63f864ae2027ea37fd645b313b71b - platform: web create_revision: 822f6e3595d63f864ae2027ea37fd645b313b71b base_revision: 822f6e3595d63f864ae2027ea37fd645b313b71b - platform: windows create_revision: 822f6e3595d63f864ae2027ea37fd645b313b71b base_revision: 822f6e3595d63f864ae2027ea37fd645b313b71b # 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/google_identity_services_web/example/.metadata/0
{ "file_path": "packages/packages/google_identity_services_web/example/.metadata", "repo_id": "packages", "token_count": 728 }
974
<!DOCTYPE html> <!-- 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. --> <html> <head> <base href="$FLUTTER_BASE_HREF"> <meta charset="UTF-8"> <meta content="IE=Edge" http-equiv="X-UA-Compatible"> <meta name="description" content="A new Flutter project."> <!-- iOS meta tags & icons --> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="black"> <meta name="apple-mobile-web-app-title" content="example"> <link rel="apple-touch-icon" href="icons/Icon-192.png"> <!-- Favicon --> <link rel="icon" type="image/png" href="favicon.png"/> <title>Authentication Example</title> <link rel="manifest" href="manifest.json"> <script> // The value below is injected by flutter build, do not touch. var serviceWorkerVersion = null; </script> <!-- Trusted Types API config (disabled) --> <!-- <meta http-equiv="Content-Security-Policy" content="trusted-types;"> --> <!-- Load the GSI SDK --> <!-- <script src="https://accounts.google.com/gsi/client" async defer></script> --> <!-- This script adds the flutter initialization JS code --> <script src="flutter.js" defer></script> </head> <body> <script> window.addEventListener('load', function(ev) { // Download main.dart.js _flutter.loader.loadEntrypoint({ serviceWorker: { serviceWorkerVersion: serviceWorkerVersion, }, onEntrypointLoaded: function(engineInitializer) { engineInitializer.autoStart(); } }); }); </script> </body> </html>
packages/packages/google_identity_services_web/example/web/index.html/0
{ "file_path": "packages/packages/google_identity_services_web/example/web/index.html", "repo_id": "packages", "token_count": 592 }
975
// 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. @TestOn('browser') // Uses package:web library; import 'package:google_identity_services_web/loader.dart'; import 'package:test/test.dart'; import 'package:web/web.dart' as web; import 'tools.dart'; // NOTE: This file needs to be separated from the others because Content // Security Policies can never be *relaxed* once set. // // In order to not introduce a dependency in the order of the tests, we split // them in different files, depending on the strictness of their CSP: // // * js_loader_test.dart : default TT configuration (not enforced) // * js_loader_tt_custom_test.dart : TT are customized, but allowed // * js_loader_tt_forbidden_test.dart: TT are completely disallowed void main() { group('loadWebSdk (TrustedTypes configured)', () { final web.HTMLDivElement target = web.document.createElement('div') as web.HTMLDivElement; injectMetaTag(<String, String>{ 'http-equiv': 'Content-Security-Policy', 'content': "trusted-types my-custom-policy-name 'allow-duplicates';", }); test('Wrong policy name: Fail with TrustedTypesException', () { expect(() { loadWebSdk(target: target); }, throwsA(isA<TrustedTypesException>())); }); test('Correct policy name: Completes', () { final Future<void> done = loadWebSdk( target: target, trustedTypePolicyName: 'my-custom-policy-name', ); expect(done, isA<Future<void>>()); }); }); }
packages/packages/google_identity_services_web/test/js_loader_tt_custom_test.dart/0
{ "file_path": "packages/packages/google_identity_services_web/test/js_loader_tt_custom_test.dart", "repo_id": "packages", "token_count": 547 }
976
// 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'; Widget _mapWithPolylines(Set<Polyline> polylines) { return Directionality( textDirection: TextDirection.ltr, child: GoogleMap( initialCameraPosition: const CameraPosition(target: LatLng(10.0, 15.0)), polylines: polylines, ), ); } void main() { late FakeGoogleMapsFlutterPlatform platform; setUp(() { platform = FakeGoogleMapsFlutterPlatform(); GoogleMapsFlutterPlatform.instance = platform; }); testWidgets('Initializing a polyline', (WidgetTester tester) async { const Polyline p1 = Polyline(polylineId: PolylineId('polyline_1')); await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1})); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.polylineUpdates.last.polylinesToAdd.length, 1); final Polyline initializedPolyline = map.polylineUpdates.last.polylinesToAdd.first; expect(initializedPolyline, equals(p1)); expect(map.polylineUpdates.last.polylineIdsToRemove.isEmpty, true); expect(map.polylineUpdates.last.polylinesToChange.isEmpty, true); }); testWidgets('Adding a polyline', (WidgetTester tester) async { const Polyline p1 = Polyline(polylineId: PolylineId('polyline_1')); const Polyline p2 = Polyline(polylineId: PolylineId('polyline_2')); await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1})); await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1, p2})); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.polylineUpdates.last.polylinesToAdd.length, 1); final Polyline addedPolyline = map.polylineUpdates.last.polylinesToAdd.first; expect(addedPolyline, equals(p2)); expect(map.polylineUpdates.last.polylineIdsToRemove.isEmpty, true); expect(map.polylineUpdates.last.polylinesToChange.isEmpty, true); }); testWidgets('Removing a polyline', (WidgetTester tester) async { const Polyline p1 = Polyline(polylineId: PolylineId('polyline_1')); await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1})); await tester.pumpWidget(_mapWithPolylines(<Polyline>{})); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.polylineUpdates.last.polylineIdsToRemove.length, 1); expect(map.polylineUpdates.last.polylineIdsToRemove.first, equals(p1.polylineId)); expect(map.polylineUpdates.last.polylinesToChange.isEmpty, true); expect(map.polylineUpdates.last.polylinesToAdd.isEmpty, true); }); testWidgets('Updating a polyline', (WidgetTester tester) async { const Polyline p1 = Polyline(polylineId: PolylineId('polyline_1')); const Polyline p2 = Polyline(polylineId: PolylineId('polyline_1'), geodesic: true); await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1})); await tester.pumpWidget(_mapWithPolylines(<Polyline>{p2})); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.polylineUpdates.last.polylinesToChange.length, 1); expect(map.polylineUpdates.last.polylinesToChange.first, equals(p2)); expect(map.polylineUpdates.last.polylineIdsToRemove.isEmpty, true); expect(map.polylineUpdates.last.polylinesToAdd.isEmpty, true); }); testWidgets('Updating a polyline', (WidgetTester tester) async { const Polyline p1 = Polyline(polylineId: PolylineId('polyline_1')); const Polyline p2 = Polyline(polylineId: PolylineId('polyline_1'), geodesic: true); await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1})); await tester.pumpWidget(_mapWithPolylines(<Polyline>{p2})); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.polylineUpdates.last.polylinesToChange.length, 1); final Polyline update = map.polylineUpdates.last.polylinesToChange.first; expect(update, equals(p2)); expect(update.geodesic, true); }); testWidgets('Mutate a polyline', (WidgetTester tester) async { final List<LatLng> points = <LatLng>[const LatLng(0.0, 0.0)]; final Polyline p1 = Polyline( polylineId: const PolylineId('polyline_1'), points: points, ); await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1})); p1.points.add(const LatLng(1.0, 1.0)); await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1})); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.polylineUpdates.last.polylinesToChange.length, 1); expect(map.polylineUpdates.last.polylinesToChange.first, equals(p1)); expect(map.polylineUpdates.last.polylineIdsToRemove.isEmpty, true); expect(map.polylineUpdates.last.polylinesToAdd.isEmpty, true); }); testWidgets('Multi Update', (WidgetTester tester) async { Polyline p1 = const Polyline(polylineId: PolylineId('polyline_1')); Polyline p2 = const Polyline(polylineId: PolylineId('polyline_2')); final Set<Polyline> prev = <Polyline>{p1, p2}; p1 = const Polyline(polylineId: PolylineId('polyline_1'), visible: false); p2 = const Polyline(polylineId: PolylineId('polyline_2'), geodesic: true); final Set<Polyline> cur = <Polyline>{p1, p2}; await tester.pumpWidget(_mapWithPolylines(prev)); await tester.pumpWidget(_mapWithPolylines(cur)); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.polylineUpdates.last.polylinesToChange, cur); expect(map.polylineUpdates.last.polylineIdsToRemove.isEmpty, true); expect(map.polylineUpdates.last.polylinesToAdd.isEmpty, true); }); testWidgets('Multi Update', (WidgetTester tester) async { Polyline p2 = const Polyline(polylineId: PolylineId('polyline_2')); const Polyline p3 = Polyline(polylineId: PolylineId('polyline_3')); final Set<Polyline> prev = <Polyline>{p2, p3}; // p1 is added, p2 is updated, p3 is removed. const Polyline p1 = Polyline(polylineId: PolylineId('polyline_1')); p2 = const Polyline(polylineId: PolylineId('polyline_2'), geodesic: true); final Set<Polyline> cur = <Polyline>{p1, p2}; await tester.pumpWidget(_mapWithPolylines(prev)); await tester.pumpWidget(_mapWithPolylines(cur)); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.polylineUpdates.last.polylinesToChange.length, 1); expect(map.polylineUpdates.last.polylinesToAdd.length, 1); expect(map.polylineUpdates.last.polylineIdsToRemove.length, 1); expect(map.polylineUpdates.last.polylinesToChange.first, equals(p2)); expect(map.polylineUpdates.last.polylinesToAdd.first, equals(p1)); expect(map.polylineUpdates.last.polylineIdsToRemove.first, equals(p3.polylineId)); }); testWidgets('Partial Update', (WidgetTester tester) async { const Polyline p1 = Polyline(polylineId: PolylineId('polyline_1')); const Polyline p2 = Polyline(polylineId: PolylineId('polyline_2')); Polyline p3 = const Polyline(polylineId: PolylineId('polyline_3')); final Set<Polyline> prev = <Polyline>{p1, p2, p3}; p3 = const Polyline(polylineId: PolylineId('polyline_3'), geodesic: true); final Set<Polyline> cur = <Polyline>{p1, p2, p3}; await tester.pumpWidget(_mapWithPolylines(prev)); await tester.pumpWidget(_mapWithPolylines(cur)); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.polylineUpdates.last.polylinesToChange, <Polyline>{p3}); expect(map.polylineUpdates.last.polylineIdsToRemove.isEmpty, true); expect(map.polylineUpdates.last.polylinesToAdd.isEmpty, true); }); testWidgets('Update non platform related attr', (WidgetTester tester) async { Polyline p1 = const Polyline(polylineId: PolylineId('polyline_1')); final Set<Polyline> prev = <Polyline>{p1}; p1 = Polyline(polylineId: const PolylineId('polyline_1'), onTap: () {}); final Set<Polyline> cur = <Polyline>{p1}; await tester.pumpWidget(_mapWithPolylines(prev)); await tester.pumpWidget(_mapWithPolylines(cur)); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.polylineUpdates.last.polylinesToChange.isEmpty, true); expect(map.polylineUpdates.last.polylineIdsToRemove.isEmpty, true); expect(map.polylineUpdates.last.polylinesToAdd.isEmpty, true); }); testWidgets('multi-update with delays', (WidgetTester tester) async { platform.simulatePlatformDelay = true; const Polyline p1 = Polyline(polylineId: PolylineId('polyline_1')); const Polyline p2 = Polyline(polylineId: PolylineId('polyline_2')); const Polyline p3 = Polyline(polylineId: PolylineId('polyline_3'), width: 1); const Polyline p3updated = Polyline(polylineId: PolylineId('polyline_3'), width: 2); // First remove one and add another, then update the new one. await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1, p2})); await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1, p3})); await tester.pumpWidget(_mapWithPolylines(<Polyline>{p1, p3updated})); final PlatformMapStateRecorder map = platform.lastCreatedMap; expect(map.polylineUpdates.length, 3); expect(map.polylineUpdates[0].polylinesToChange.isEmpty, true); expect(map.polylineUpdates[0].polylinesToAdd, <Polyline>{p1, p2}); expect(map.polylineUpdates[0].polylineIdsToRemove.isEmpty, true); expect(map.polylineUpdates[1].polylinesToChange.isEmpty, true); expect(map.polylineUpdates[1].polylinesToAdd, <Polyline>{p3}); expect(map.polylineUpdates[1].polylineIdsToRemove, <PolylineId>{p2.polylineId}); expect(map.polylineUpdates[2].polylinesToChange, <Polyline>{p3updated}); expect(map.polylineUpdates[2].polylinesToAdd.isEmpty, true); expect(map.polylineUpdates[2].polylineIdsToRemove.isEmpty, true); await tester.pumpAndSettle(); }); }
packages/packages/google_maps_flutter/google_maps_flutter/test/polyline_updates_test.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter/test/polyline_updates_test.dart", "repo_id": "packages", "token_count": 3736 }
977
// 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 android.content.Context; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.android.gms.maps.model.CameraPosition; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.StandardMessageCodec; import io.flutter.plugin.platform.PlatformView; import io.flutter.plugin.platform.PlatformViewFactory; import java.util.List; import java.util.Map; public class GoogleMapFactory extends PlatformViewFactory { private final BinaryMessenger binaryMessenger; private final LifecycleProvider lifecycleProvider; private final GoogleMapInitializer googleMapInitializer; GoogleMapFactory( BinaryMessenger binaryMessenger, Context context, LifecycleProvider lifecycleProvider) { super(StandardMessageCodec.INSTANCE); this.binaryMessenger = binaryMessenger; this.lifecycleProvider = lifecycleProvider; this.googleMapInitializer = new GoogleMapInitializer(context, binaryMessenger); } @SuppressWarnings("unchecked") @Override @NonNull public PlatformView create(@NonNull Context context, int id, @Nullable Object args) { Map<String, Object> params = (Map<String, Object>) args; final GoogleMapBuilder builder = new GoogleMapBuilder(); final Object options = params.get("options"); Convert.interpretGoogleMapOptions(options, builder); if (params.containsKey("initialCameraPosition")) { CameraPosition position = Convert.toCameraPosition(params.get("initialCameraPosition")); builder.setInitialCameraPosition(position); } if (params.containsKey("markersToAdd")) { builder.setInitialMarkers(params.get("markersToAdd")); } if (params.containsKey("polygonsToAdd")) { builder.setInitialPolygons(params.get("polygonsToAdd")); } if (params.containsKey("polylinesToAdd")) { builder.setInitialPolylines(params.get("polylinesToAdd")); } if (params.containsKey("circlesToAdd")) { builder.setInitialCircles(params.get("circlesToAdd")); } if (params.containsKey("tileOverlaysToAdd")) { builder.setInitialTileOverlays((List<Map<String, ?>>) params.get("tileOverlaysToAdd")); } final Object cloudMapId = ((Map<?, ?>) options).get("cloudMapId"); if (cloudMapId != null) { builder.setMapId((String) cloudMapId); } return builder.build(id, context, binaryMessenger, lifecycleProvider); } }
packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/GoogleMapFactory.java/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/GoogleMapFactory.java", "repo_id": "packages", "token_count": 833 }
978
// 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.Cap; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.PatternItem; import java.util.List; /** Receiver of Polyline configuration options. */ interface PolylineOptionsSink { void setConsumeTapEvents(boolean consumetapEvents); void setColor(int color); void setEndCap(Cap endCap); void setGeodesic(boolean geodesic); void setJointType(int jointType); void setPattern(List<PatternItem> pattern); void setPoints(List<LatLng> points); void setStartCap(Cap startCap); void setVisible(boolean visible); void setWidth(float width); void setZIndex(float zIndex); }
packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/PolylineOptionsSink.java/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/android/src/main/java/io/flutter/plugins/googlemaps/PolylineOptionsSink.java", "repo_id": "packages", "token_count": 269 }
979
// 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'; // #docregion DisplayMode import 'package:google_maps_flutter_android/google_maps_flutter_android.dart'; import 'package:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart'; void main() { // Require Hybrid Composition mode on Android. final GoogleMapsFlutterPlatform mapsImplementation = GoogleMapsFlutterPlatform.instance; if (mapsImplementation is GoogleMapsFlutterAndroid) { // Force Hybrid Composition mode. mapsImplementation.useAndroidViewSurface = true; } // #enddocregion DisplayMode runApp(const MyApp()); // #docregion DisplayMode } // #enddocregion DisplayMode class MyApp extends StatefulWidget { const MyApp({super.key}); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { // #docregion MapRenderer AndroidMapRenderer mapRenderer = AndroidMapRenderer.platformDefault; // #enddocregion MapRenderer @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('README snippet app'), ), body: const Text('See example in main.dart'), ), ); } Future<void> initializeLatestMapRenderer() async { // #docregion MapRenderer final GoogleMapsFlutterPlatform mapsImplementation = GoogleMapsFlutterPlatform.instance; if (mapsImplementation is GoogleMapsFlutterAndroid) { WidgetsFlutterBinding.ensureInitialized(); mapRenderer = await mapsImplementation .initializeWithRenderer(AndroidMapRenderer.latest); } // #enddocregion MapRenderer } }
packages/packages/google_maps_flutter/google_maps_flutter_android/example/lib/readme_excerpts.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_android/example/lib/readme_excerpts.dart", "repo_id": "packages", "token_count": 628 }
980
// 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 google_maps_flutter_ios; @import google_maps_flutter_ios.Test; @import XCTest; @import GoogleMaps; #import <OCMock/OCMock.h> #import "PartiallyMockedMapView.h" @interface FLTGoogleMapFactory (Test) @property(strong, nonatomic, readonly) id<NSObject> sharedMapServices; @end @interface GoogleMapsTests : XCTestCase @end @implementation GoogleMapsTests - (void)testPlugin { FLTGoogleMapsPlugin *plugin = [[FLTGoogleMapsPlugin alloc] init]; XCTAssertNotNil(plugin); } - (void)testFrameObserver { id registrar = OCMProtocolMock(@protocol(FlutterPluginRegistrar)); CGRect frame = CGRectMake(0, 0, 100, 100); #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" // TODO(stuartmorgan): Switch to initWithOptions: once we can guarantee we will be using SDK 8.3+. // That API was only added in 8.3, and Cocoapod caches on some machines may not be up-to-date // enough to resolve to that yet even when targeting iOS 14+. PartiallyMockedMapView *mapView = [[PartiallyMockedMapView alloc] initWithFrame:frame camera:[[GMSCameraPosition alloc] initWithLatitude:0 longitude:0 zoom:0]]; #pragma clang diagnostic pop FLTGoogleMapController *controller = [[FLTGoogleMapController alloc] initWithMapView:mapView viewIdentifier:0 arguments:nil registrar:registrar]; for (NSInteger i = 0; i < 10; ++i) { [controller view]; } XCTAssertEqual(mapView.frameObserverCount, 1); mapView.frame = frame; XCTAssertEqual(mapView.frameObserverCount, 0); } - (void)testMapsServiceSync { id registrar = OCMProtocolMock(@protocol(FlutterPluginRegistrar)); FLTGoogleMapFactory *factory1 = [[FLTGoogleMapFactory alloc] initWithRegistrar:registrar]; XCTAssertNotNil(factory1.sharedMapServices); FLTGoogleMapFactory *factory2 = [[FLTGoogleMapFactory alloc] initWithRegistrar:registrar]; // Test pointer equality, should be same retained singleton +[GMSServices sharedServices] object. // Retaining the opaque object should be enough to avoid multiple internal initializations, // but don't test the internals of the GoogleMaps API. Assume that it does what is documented. // https://developers.google.com/maps/documentation/ios-sdk/reference/interface_g_m_s_services#a436e03c32b1c0be74e072310a7158831 XCTAssertEqual(factory1.sharedMapServices, factory2.sharedMapServices); } @end
packages/packages/google_maps_flutter/google_maps_flutter_ios/example/ios14/ios/RunnerTests/GoogleMapsTests.m/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_ios/example/ios14/ios/RunnerTests/GoogleMapsTests.m", "repo_id": "packages", "token_count": 1055 }
981
// 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 immutable, objectRuntimeType, setEquals; import 'maps_object.dart'; import 'utils/maps_object.dart'; /// Update specification for a set of objects. @immutable class MapsObjectUpdates<T extends MapsObject<T>> { /// Computes updates given previous and current object sets. /// /// [objectName] is the prefix to use when serializing the updates into a JSON /// dictionary. E.g., 'circle' will give 'circlesToAdd', 'circlesToUpdate', /// 'circleIdsToRemove'. MapsObjectUpdates.from( Set<T> previous, Set<T> current, { required this.objectName, }) { final Map<MapsObjectId<T>, T> previousObjects = keyByMapsObjectId(previous); final Map<MapsObjectId<T>, T> currentObjects = keyByMapsObjectId(current); final Set<MapsObjectId<T>> previousObjectIds = previousObjects.keys.toSet(); final Set<MapsObjectId<T>> currentObjectIds = currentObjects.keys.toSet(); /// Maps an ID back to a [T] in [currentObjects]. /// /// It is a programming error to call this with an ID that is not guaranteed /// to be in [currentObjects]. T idToCurrentObject(MapsObjectId<T> id) { return currentObjects[id]!; } _objectIdsToRemove = previousObjectIds.difference(currentObjectIds); _objectsToAdd = currentObjectIds .difference(previousObjectIds) .map(idToCurrentObject) .toSet(); // Returns `true` if [current] is not equals to previous one with the // same id. bool hasChanged(T current) { final T? previous = previousObjects[current.mapsId]; return current != previous; } _objectsToChange = currentObjectIds .intersection(previousObjectIds) .map(idToCurrentObject) .where(hasChanged) .toSet(); } /// The name of the objects being updated, for use in serialization. final String objectName; /// Set of objects to be added in this update. Set<T> get objectsToAdd { return _objectsToAdd; } late final Set<T> _objectsToAdd; /// Set of objects to be removed in this update. Set<MapsObjectId<T>> get objectIdsToRemove { return _objectIdsToRemove; } late final Set<MapsObjectId<T>> _objectIdsToRemove; /// Set of objects to be changed in this update. Set<T> get objectsToChange { return _objectsToChange; } late final Set<T> _objectsToChange; /// Converts this object to JSON. Object toJson() { final Map<String, Object> updateMap = <String, Object>{}; void addIfNonNull(String fieldName, Object? value) { if (value != null) { updateMap[fieldName] = value; } } addIfNonNull('${objectName}sToAdd', serializeMapsObjectSet(_objectsToAdd)); addIfNonNull( '${objectName}sToChange', serializeMapsObjectSet(_objectsToChange)); addIfNonNull( '${objectName}IdsToRemove', _objectIdsToRemove .map<String>((MapsObjectId<T> m) => m.value) .toList()); return updateMap; } @override bool operator ==(Object other) { if (other.runtimeType != runtimeType) { return false; } return other is MapsObjectUpdates && setEquals(_objectsToAdd, other._objectsToAdd) && setEquals(_objectIdsToRemove, other._objectIdsToRemove) && setEquals(_objectsToChange, other._objectsToChange); } @override int get hashCode => Object.hash(Object.hashAll(_objectsToAdd), Object.hashAll(_objectIdsToRemove), Object.hashAll(_objectsToChange)); @override String toString() { return '${objectRuntimeType(this, 'MapsObjectUpdates')}(add: $objectsToAdd, ' 'remove: $objectIdsToRemove, ' 'change: $objectsToChange)'; } }
packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/maps_object_updates.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/maps_object_updates.dart", "repo_id": "packages", "token_count": 1397 }
982
// 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'; import 'maps_object.dart'; /// Converts an [Iterable] of Cluster Managers in a Map of ClusterManagerId -> Cluster. Map<ClusterManagerId, ClusterManager> keyByClusterManagerId( Iterable<ClusterManager> clusterManagers) { return keyByMapsObjectId<ClusterManager>(clusterManagers) .cast<ClusterManagerId, ClusterManager>(); }
packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/utils/cluster_manager.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/lib/src/types/utils/cluster_manager.dart", "repo_id": "packages", "token_count": 157 }
983
// 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:google_maps_flutter_platform_interface/google_maps_flutter_platform_interface.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('LanLng constructor', () { test('Maintains longitude precision if within acceptable range', () async { const double lat = -34.509981; const double lng = 150.792384; const LatLng latLng = LatLng(lat, lng); expect(latLng.latitude, equals(lat)); expect(latLng.longitude, equals(lng)); }); test('Normalizes longitude that is below lower limit', () async { const double lat = -34.509981; const double lng = -270.0; const LatLng latLng = LatLng(lat, lng); expect(latLng.latitude, equals(lat)); expect(latLng.longitude, equals(90.0)); }); test('Normalizes longitude that is above upper limit', () async { const double lat = -34.509981; const double lng = 270.0; const LatLng latLng = LatLng(lat, lng); expect(latLng.latitude, equals(lat)); expect(latLng.longitude, equals(-90.0)); }); test('Includes longitude set to lower limit', () async { const double lat = -34.509981; const double lng = -180.0; const LatLng latLng = LatLng(lat, lng); expect(latLng.latitude, equals(lat)); expect(latLng.longitude, equals(-180.0)); }); test('Normalizes longitude set to upper limit', () async { const double lat = -34.509981; const double lng = 180.0; const LatLng latLng = LatLng(lat, lng); expect(latLng.latitude, equals(lat)); expect(latLng.longitude, equals(-180.0)); }); }); }
packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/location_test.dart/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_platform_interface/test/types/location_test.dart", "repo_id": "packages", "token_count": 724 }
984
name: google_maps_flutter_web_integration_tests publish_to: none # Tests require flutter beta or greater to run. environment: sdk: ^3.3.0 flutter: ">=3.19.0" dependencies: flutter: sdk: flutter google_maps_flutter_platform_interface: ^2.5.0 google_maps_flutter_web: path: ../ web: ^0.5.0 dev_dependencies: build_runner: ^2.1.1 flutter_test: sdk: flutter google_maps: ^7.1.0 google_maps_flutter: ^2.2.0 # Needed for projection_test.dart http: ">=0.13.0 <2.0.0" integration_test: sdk: flutter mockito: 5.4.4 dependency_overrides: # Override the google_maps_flutter dependency on google_maps_flutter_web. # TODO(ditman): Unwind the circular dependency. This will create problems # if we need to make a breaking change to google_maps_flutter_web. google_maps_flutter_web: path: ../
packages/packages/google_maps_flutter/google_maps_flutter_web/example/pubspec.yaml/0
{ "file_path": "packages/packages/google_maps_flutter/google_maps_flutter_web/example/pubspec.yaml", "repo_id": "packages", "token_count": 338 }
985
buildFlags: _pluginToolsConfigGlobalKey: - "--no-tree-shake-icons" - "--dart-define=buildmode=testing"
packages/packages/google_sign_in/google_sign_in/example/.pluginToolsConfig.yaml/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in/example/.pluginToolsConfig.yaml", "repo_id": "packages", "token_count": 45 }
986
name: google_sign_in_android description: Android implementation of the google_sign_in plugin. repository: https://github.com/flutter/packages/tree/main/packages/google_sign_in/google_sign_in_android issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+google_sign_in%22 version: 6.1.22 environment: sdk: ^3.1.0 flutter: ">=3.13.0" flutter: plugin: implements: google_sign_in platforms: android: dartPluginClass: GoogleSignInAndroid package: io.flutter.plugins.googlesignin pluginClass: GoogleSignInPlugin dependencies: flutter: sdk: flutter google_sign_in_platform_interface: ^2.2.0 dev_dependencies: build_runner: ^2.3.0 flutter_test: sdk: flutter integration_test: sdk: flutter mockito: 5.4.4 pigeon: ^10.1.0 topics: - authentication - google-sign-in # The example deliberately includes limited-use secrets. false_secrets: - /example/android/app/google-services.json - /example/lib/main.dart
packages/packages/google_sign_in/google_sign_in_android/pubspec.yaml/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_android/pubspec.yaml", "repo_id": "packages", "token_count": 404 }
987
<?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>CFBundleDevelopmentRegion</key> <string>$(DEVELOPMENT_LANGUAGE)</string> <key>CFBundleExecutable</key> <string>$(EXECUTABLE_NAME)</string> <key>CFBundleIconFile</key> <string></string> <key>CFBundleIdentifier</key> <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>$(PRODUCT_NAME)</string> <key>CFBundlePackageType</key> <string>APPL</string> <key>CFBundleShortVersionString</key> <string>$(FLUTTER_BUILD_NAME)</string> <key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleTypeRole</key> <string>Editor</string> <key>CFBundleURLSchemes</key> <array> <string>com.googleusercontent.apps.479882132969-9i9aqik3jfjd7qhci1nqf0bm2g71rm1u</string> </array> </dict> </array> <key>CFBundleVersion</key> <string>$(FLUTTER_BUILD_NUMBER)</string> <key>GIDClientID</key> <string>479882132969-9i9aqik3jfjd7qhci1nqf0bm2g71rm1u.apps.googleusercontent.com</string> <key>GIDServerClientID</key> <string>YOUR_SERVER_CLIENT_ID</string> <key>LSMinimumSystemVersion</key> <string>$(MACOSX_DEPLOYMENT_TARGET)</string> <key>NSHumanReadableCopyright</key> <string>$(PRODUCT_COPYRIGHT)</string> <key>NSMainNibFile</key> <string>MainMenu</string> <key>NSPrincipalClass</key> <string>NSApplication</string> </dict> </plist>
packages/packages/google_sign_in/google_sign_in_ios/example/macos/Runner/Info.plist/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_ios/example/macos/Runner/Info.plist", "repo_id": "packages", "token_count": 682 }
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:async'; import 'package:flutter/foundation.dart' show visibleForTesting; import 'package:plugin_platform_interface/plugin_platform_interface.dart'; import 'src/method_channel_google_sign_in.dart'; import 'src/types.dart'; export 'src/method_channel_google_sign_in.dart'; export 'src/types.dart'; /// The interface that implementations of google_sign_in must implement. /// /// Platform implementations that live in a separate package should extend this /// class rather than implement it as `google_sign_in` does not consider newly /// added methods to be breaking changes. Extending this class (using `extends`) /// ensures that the subclass will get the default implementation, while /// platform implementations that `implements` this interface will be broken by /// newly added [GoogleSignInPlatform] methods. abstract class GoogleSignInPlatform extends PlatformInterface { /// Constructs a GoogleSignInPlatform. GoogleSignInPlatform() : super(token: _token); static final Object _token = Object(); /// Only mock implementations should set this to `true`. /// /// Mockito mocks implement this class with `implements` which is forbidden /// (see class docs). This property provides a backdoor for mocks to skip the /// verification that the class isn't implemented with `implements`. @visibleForTesting @Deprecated('Use MockPlatformInterfaceMixin instead') bool get isMock => false; /// The default instance of [GoogleSignInPlatform] to use. /// /// Platform-specific plugins should override this with their own /// platform-specific class that extends [GoogleSignInPlatform] when they /// register themselves. /// /// Defaults to [MethodChannelGoogleSignIn]. static GoogleSignInPlatform get instance => _instance; static GoogleSignInPlatform _instance = MethodChannelGoogleSignIn(); // TODO(amirh): Extract common platform interface logic. // https://github.com/flutter/flutter/issues/43368 static set instance(GoogleSignInPlatform instance) { if (!instance.isMock) { PlatformInterface.verify(instance, _token); } _instance = instance; } /// Initializes the plugin. Deprecated: call [initWithParams] instead. /// /// The [hostedDomain] argument specifies a hosted domain restriction. By /// setting this, sign in will be restricted to accounts of the user in the /// specified domain. By default, the list of accounts will not be restricted. /// /// The list of [scopes] are OAuth scope codes to request when signing in. /// These scope codes will determine the level of data access that is granted /// to your application by the user. The full list of available scopes can be /// found here: <https://developers.google.com/identity/protocols/googlescopes> /// /// The [signInOption] determines the user experience. [SigninOption.games] is /// only supported on Android. /// /// See: /// https://developers.google.com/identity/sign-in/web/reference#gapiauth2initparams Future<void> init({ List<String> scopes = const <String>[], SignInOption signInOption = SignInOption.standard, String? hostedDomain, String? clientId, }) async { throw UnimplementedError('init() has not been implemented.'); } /// Initializes the plugin with specified [params]. You must call this method /// before calling other methods. /// /// See: /// /// * [SignInInitParameters] Future<void> initWithParams(SignInInitParameters params) async { await init( scopes: params.scopes, signInOption: params.signInOption, hostedDomain: params.hostedDomain, clientId: params.clientId, ); } /// Attempts to reuse pre-existing credentials to sign in again, without user interaction. Future<GoogleSignInUserData?> signInSilently() async { throw UnimplementedError('signInSilently() has not been implemented.'); } /// Signs in the user with the options specified to [init]. Future<GoogleSignInUserData?> signIn() async { throw UnimplementedError('signIn() has not been implemented.'); } /// Returns the Tokens used to authenticate other API calls. Future<GoogleSignInTokenData> getTokens( {required String email, bool? shouldRecoverAuth}) async { throw UnimplementedError('getTokens() has not been implemented.'); } /// Signs out the current account from the application. Future<void> signOut() async { throw UnimplementedError('signOut() has not been implemented.'); } /// Revokes all of the scopes that the user granted. Future<void> disconnect() async { throw UnimplementedError('disconnect() has not been implemented.'); } /// Returns whether the current user is currently signed in. Future<bool> isSignedIn() async { throw UnimplementedError('isSignedIn() has not been implemented.'); } /// Clears any cached information that the plugin may be holding on to. Future<void> clearAuthCache({required String token}) async { throw UnimplementedError('clearAuthCache() has not been implemented.'); } /// Requests the user grants additional Oauth [scopes]. /// /// Scopes should come from the full list /// [here](https://developers.google.com/identity/protocols/googlescopes). Future<bool> requestScopes(List<String> scopes) async { throw UnimplementedError('requestScopes() has not been implemented.'); } /// Checks if the current user has granted access to all the specified [scopes]. /// /// Optionally, an [accessToken] can be passed for applications where a /// long-lived token may be cached (like the web). Future<bool> canAccessScopes( List<String> scopes, { String? accessToken, }) async { throw UnimplementedError('canAccessScopes() has not been implemented.'); } /// Returns a stream of [GoogleSignInUserData] authentication events. /// /// These will normally come from asynchronous flows, like the Google Sign-In /// Button Widget from the Web implementation, and will be funneled directly /// to the `onCurrentUserChanged` Stream of the plugin. Stream<GoogleSignInUserData?>? get userDataEvents => null; }
packages/packages/google_sign_in/google_sign_in_platform_interface/lib/google_sign_in_platform_interface.dart/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_platform_interface/lib/google_sign_in_platform_interface.dart", "repo_id": "packages", "token_count": 1759 }
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 'dart:async'; import 'dart:convert'; import 'package:flutter_test/flutter_test.dart'; import 'package:google_identity_services_web/oauth2.dart'; import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart'; import 'package:google_sign_in_web/src/people.dart'; import 'package:http/http.dart' as http; import 'package:http/testing.dart' as http_test; import 'package:integration_test/integration_test.dart'; import 'src/jsify_as.dart'; import 'src/person.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); group('requestUserData', () { const String expectedAccessToken = '3xp3c73d_4cc355_70k3n'; final TokenResponse fakeToken = jsifyAs(<String, Object?>{ 'token_type': 'Bearer', 'access_token': expectedAccessToken, }); testWidgets('happy case', (_) async { final Completer<String> accessTokenCompleter = Completer<String>(); final http.Client mockClient = http_test.MockClient( (http.Request request) async { accessTokenCompleter.complete(request.headers['Authorization']); return http.Response( jsonEncode(person), 200, headers: <String, String>{'content-type': 'application/json'}, ); }, ); final GoogleSignInUserData? user = await requestUserData( fakeToken, overrideClient: mockClient, ); expect(user, isNotNull); expect(user!.email, expectedPersonEmail); expect(user.id, expectedPersonId); expect(user.displayName, expectedPersonName); expect(user.photoUrl, expectedPersonPhoto); expect(user.idToken, isNull); expect( accessTokenCompleter.future, completion('Bearer $expectedAccessToken'), ); }); testWidgets('Unauthorized request - throws exception', (_) async { final http.Client mockClient = http_test.MockClient( (http.Request request) async { return http.Response( 'Unauthorized', 403, ); }, ); expect(() async { await requestUserData( fakeToken, overrideClient: mockClient, ); }, throwsA(isA<http.ClientException>())); }); }); group('extractUserData', () { testWidgets('happy case', (_) async { final GoogleSignInUserData? user = extractUserData(person); expect(user, isNotNull); expect(user!.email, expectedPersonEmail); expect(user.id, expectedPersonId); expect(user.displayName, expectedPersonName); expect(user.photoUrl, expectedPersonPhoto); expect(user.idToken, isNull); }); testWidgets('no name/photo - keeps going', (_) async { final Map<String, Object?> personWithoutSomeData = mapWithoutKeys(person, <String>{ 'names', 'photos', }); final GoogleSignInUserData? user = extractUserData(personWithoutSomeData); expect(user, isNotNull); expect(user!.email, expectedPersonEmail); expect(user.id, expectedPersonId); expect(user.displayName, isNull); expect(user.photoUrl, isNull); expect(user.idToken, isNull); }); testWidgets('no userId - throws assertion error', (_) async { final Map<String, Object?> personWithoutId = mapWithoutKeys(person, <String>{ 'resourceName', }); expect(() { extractUserData(personWithoutId); }, throwsAssertionError); }); testWidgets('no email - throws assertion error', (_) async { final Map<String, Object?> personWithoutEmail = mapWithoutKeys(person, <String>{ 'emailAddresses', }); expect(() { extractUserData(personWithoutEmail); }, throwsAssertionError); }); }); }
packages/packages/google_sign_in/google_sign_in_web/example/integration_test/people_test.dart/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_web/example/integration_test/people_test.dart", "repo_id": "packages", "token_count": 1581 }
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:js_interop'; // TODO(dit): Split `id` and `oauth2` "services" for mocking. https://github.com/flutter/flutter/issues/120657 import 'package:google_identity_services_web/id.dart'; import 'package:google_identity_services_web/oauth2.dart'; import 'package:google_sign_in_platform_interface/google_sign_in_platform_interface.dart'; import 'package:web/web.dart' as web; import 'button_configuration.dart' show GSIButtonConfiguration, convertButtonConfiguration; import 'people.dart' as people; import 'utils.dart' as utils; /// A client to hide (most) of the interaction with the GIS SDK from the plugin. /// /// (Overridable for testing) class GisSdkClient { /// Create a GisSdkClient object. GisSdkClient({ required List<String> initialScopes, required String clientId, required StreamController<GoogleSignInUserData?> userDataController, bool loggingEnabled = false, String? hostedDomain, }) : _initialScopes = initialScopes, _loggingEnabled = loggingEnabled, _userDataEventsController = userDataController { if (_loggingEnabled) { id.setLogLevel('debug'); } // Configure the Stream objects that are going to be used by the clients. _configureStreams(); // Initialize the SDK clients we need. _initializeIdClient( clientId, onResponse: _onCredentialResponse, hostedDomain: hostedDomain, useFedCM: true, ); _tokenClient = _initializeTokenClient( clientId, hostedDomain: hostedDomain, onResponse: _onTokenResponse, onError: _onTokenError, ); if (initialScopes.isNotEmpty) { _codeClient = _initializeCodeClient( clientId, hostedDomain: hostedDomain, onResponse: _onCodeResponse, onError: _onCodeError, scopes: initialScopes, ); } } void _logIfEnabled(String message, [List<Object?>? more]) { if (_loggingEnabled) { final String log = <Object?>['[google_sign_in_web]', message, ...?more].join(' '); web.console.info(log.toJS); } } // Configure the credential (authentication) and token (authorization) response streams. void _configureStreams() { _tokenResponses = StreamController<TokenResponse>.broadcast(); _credentialResponses = StreamController<CredentialResponse>.broadcast(); _codeResponses = StreamController<CodeResponse>.broadcast(); _tokenResponses.stream.listen((TokenResponse response) { _lastTokenResponse = response; _lastTokenResponseExpiration = DateTime.now().add(Duration(seconds: response.expires_in!)); }, onError: (Object error) { _logIfEnabled('Error on TokenResponse:', <Object>[error.toString()]); _lastTokenResponse = null; }); _codeResponses.stream.listen((CodeResponse response) { _lastCodeResponse = response; }, onError: (Object error) { _logIfEnabled('Error on CodeResponse:', <Object>[error.toString()]); _lastCodeResponse = null; }); _credentialResponses.stream.listen((CredentialResponse response) { _lastCredentialResponse = response; }, onError: (Object error) { _logIfEnabled('Error on CredentialResponse:', <Object>[error.toString()]); _lastCredentialResponse = null; }); // In the future, the userDataEvents could propagate null userDataEvents too. _credentialResponses.stream .map(utils.gisResponsesToUserData) .handleError(_cleanCredentialResponsesStreamErrors) .forEach(_userDataEventsController.add); } // This function handles the errors that on the _credentialResponses Stream. // // Most of the time, these errors are part of the flow (like when One Tap UX // cannot be rendered), and the stream of userDataEvents doesn't care about // them. // // (This has been separated to a function so the _configureStreams formatting // looks a little bit better) void _cleanCredentialResponsesStreamErrors(Object error) { _logIfEnabled( 'Removing error from `userDataEvents`:', <Object>[error.toString()], ); } // Initializes the `id` SDK for the silent-sign in (authentication) client. void _initializeIdClient( String clientId, { required CallbackFn onResponse, String? hostedDomain, bool? useFedCM, }) { // Initialize `id` for the silent-sign in code. final IdConfiguration idConfig = IdConfiguration( client_id: clientId, callback: onResponse, cancel_on_tap_outside: false, auto_select: true, // Attempt to sign-in silently. hd: hostedDomain, use_fedcm_for_prompt: useFedCM, // Use the native browser prompt, when available. ); id.initialize(idConfig); } // Handle a "normal" credential (authentication) response. // // (Normal doesn't mean successful, this might contain `error` information.) void _onCredentialResponse(CredentialResponse response) { if (response.error != null) { _credentialResponses.addError(response.error!); } else { _credentialResponses.add(response); } } // Creates a `oauth2.TokenClient` used for authorization (scope) requests. TokenClient _initializeTokenClient( String clientId, { String? hostedDomain, required TokenClientCallbackFn onResponse, required ErrorCallbackFn onError, }) { // Create a Token Client for authorization calls. final TokenClientConfig tokenConfig = TokenClientConfig( client_id: clientId, hd: hostedDomain, callback: _onTokenResponse, error_callback: _onTokenError, // This is here only to satisfy the initialization of the JS TokenClient. // In reality, `scope` is always overridden when calling `requestScopes` // (or the deprecated `signIn`) through an [OverridableTokenClientConfig] // object. scope: <String>[' '], // Fake (but non-empty) list of scopes. ); return oauth2.initTokenClient(tokenConfig); } // Handle a "normal" token (authorization) response. // // (Normal doesn't mean successful, this might contain `error` information.) void _onTokenResponse(TokenResponse response) { if (response.error != null) { _tokenResponses.addError(response.error!); } else { _tokenResponses.add(response); } } // Handle a "not-directly-related-to-authorization" error. // // Token clients have an additional `error_callback` for miscellaneous // errors, like "popup couldn't open" or "popup closed by user". void _onTokenError(Object? error) { if (error != null) { _tokenResponses.addError((error as GoogleIdentityServicesError).type); } } // Creates a `oauth2.CodeClient` used for authorization (scope) requests. CodeClient _initializeCodeClient( String clientId, { String? hostedDomain, required List<String> scopes, required CodeClientCallbackFn onResponse, required ErrorCallbackFn onError, }) { // Create a Token Client for authorization calls. final CodeClientConfig codeConfig = CodeClientConfig( client_id: clientId, hd: hostedDomain, callback: _onCodeResponse, error_callback: _onCodeError, scope: scopes, select_account: true, ux_mode: UxMode.popup, ); return oauth2.initCodeClient(codeConfig); } void _onCodeResponse(CodeResponse response) { if (response.error != null) { _codeResponses.addError(response.error!); } else { _codeResponses.add(response); } } void _onCodeError(Object? error) { if (error != null) { _codeResponses.addError((error as GoogleIdentityServicesError).type); } } /// Attempts to sign-in the user using the OneTap UX flow. /// /// If the user consents, to OneTap, the [GoogleSignInUserData] will be /// generated from a proper [CredentialResponse], which contains `idToken`. /// Else, it'll be synthesized by a request to the People API later, and the /// `idToken` will be null. Future<GoogleSignInUserData?> signInSilently() async { final Completer<GoogleSignInUserData?> userDataCompleter = Completer<GoogleSignInUserData?>(); // Ask the SDK to render the OneClick sign-in. // // And also handle its "moments". id.prompt((PromptMomentNotification moment) { _onPromptMoment(moment, userDataCompleter); }); return userDataCompleter.future; } // Handles "prompt moments" of the OneClick card UI. // // See: https://developers.google.com/identity/gsi/web/guides/receive-notifications-prompt-ui-status Future<void> _onPromptMoment( PromptMomentNotification moment, Completer<GoogleSignInUserData?> completer, ) async { if (completer.isCompleted) { return; // Skip once the moment has been handled. } if (moment.isDismissedMoment() && moment.getDismissedReason() == MomentDismissedReason.credential_returned) { // Kick this part of the handler to the bottom of the JS event queue, so // the _credentialResponses stream has time to propagate its last value, // and we can use _lastCredentialResponse. return Future<void>.delayed(Duration.zero, () { completer .complete(utils.gisResponsesToUserData(_lastCredentialResponse)); }); } // In any other 'failed' moments, return null and add an error to the stream. if (moment.isNotDisplayed() || moment.isSkippedMoment() || moment.isDismissedMoment()) { final String reason = moment.getNotDisplayedReason()?.toString() ?? moment.getSkippedReason()?.toString() ?? moment.getDismissedReason()?.toString() ?? 'unknown_error'; _credentialResponses.addError(reason); completer.complete(null); } } /// Calls `id.renderButton` on [parent] with the given [options]. Future<void> renderButton( Object parent, GSIButtonConfiguration options, ) async { return id.renderButton(parent, convertButtonConfiguration(options)); } /// Requests a server auth code per: /// https://developers.google.com/identity/oauth2/web/guides/use-code-model#initialize_a_code_client Future<String?> requestServerAuthCode() async { // TODO(dit): Enable granular authorization, https://github.com/flutter/flutter/issues/139406 assert(_codeClient != null, 'CodeClient not initialized correctly. Ensure the `scopes` list passed to `init()` or `initWithParams()` is not empty!'); if (_codeClient == null) { return null; } _codeClient!.requestCode(); final CodeResponse response = await _codeResponses.stream.first; return response.code; } // TODO(dit): Clean this up. https://github.com/flutter/flutter/issues/137727 // /// Starts an oauth2 "implicit" flow to authorize requests. /// /// The new GIS SDK does not return user authentication from this flow, so: /// * If [_lastCredentialResponse] is **not** null (the user has successfully /// `signInSilently`), we return that after this method completes. /// * If [_lastCredentialResponse] is null, we add [people.scopes] to the /// [_initialScopes], so we can retrieve User Profile information back /// from the People API (without idToken). See [people.requestUserData]. @Deprecated( 'Use `renderButton` instead. See: https://pub.dev/packages/google_sign_in_web#migrating-to-v011-and-v012-google-identity-services') Future<GoogleSignInUserData?> signIn() async { // Warn users that this method will be removed. web.console.warn( 'The google_sign_in plugin `signIn` method is deprecated on the web, and will be removed in Q2 2024. Please use `renderButton` instead. See: ' 'https://pub.dev/packages/google_sign_in_web#migrating-to-v011-and-v012-google-identity-services' .toJS); // If we already know the user, use their `email` as a `hint`, so they don't // have to pick their user again in the Authorization popup. final GoogleSignInUserData? knownUser = utils.gisResponsesToUserData(_lastCredentialResponse); // This toggles a popup, so `signIn` *must* be called with // user activation. _tokenClient.requestAccessToken(OverridableTokenClientConfig( prompt: knownUser == null ? 'select_account' : '', login_hint: knownUser?.email, scope: <String>[ ..._initialScopes, // If the user hasn't gone through the auth process, // the plugin will attempt to `requestUserData` after, // so we need extra scopes to retrieve that info. if (_lastCredentialResponse == null) ...people.scopes, ], )); await _tokenResponses.stream.first; return _computeUserDataForLastToken(); } // This function returns the currently signed-in [GoogleSignInUserData]. // // It'll do a request to the People API (if needed). // // TODO(dit): Clean this up. https://github.com/flutter/flutter/issues/137727 Future<GoogleSignInUserData?> _computeUserDataForLastToken() async { // If the user hasn't authenticated, request their basic profile info // from the People API. // // This synthetic response will *not* contain an `idToken` field. if (_lastCredentialResponse == null && _requestedUserData == null) { assert(_lastTokenResponse != null); _requestedUserData = await people.requestUserData(_lastTokenResponse!); } // Complete user data either with the _lastCredentialResponse seen, // or the synthetic _requestedUserData from above. return utils.gisResponsesToUserData(_lastCredentialResponse) ?? _requestedUserData; } /// Returns a [GoogleSignInTokenData] from the latest seen responses. GoogleSignInTokenData getTokens() { return utils.gisResponsesToTokenData( _lastCredentialResponse, _lastTokenResponse, _lastCodeResponse, ); } /// Revokes the current authentication. Future<void> signOut() async { await clearAuthCache(); id.disableAutoSelect(); } /// Revokes the current authorization and authentication. Future<void> disconnect() async { if (_lastTokenResponse != null) { oauth2.revoke(_lastTokenResponse!.access_token!); } await signOut(); } /// Returns true if the client has recognized this user before, and the last-seen /// credential is not expired. Future<bool> isSignedIn() async { bool isSignedIn = false; if (_lastCredentialResponse != null) { final DateTime? expiration = utils .getCredentialResponseExpirationTimestamp(_lastCredentialResponse); // All Google ID Tokens provide an "exp" date. If the method above cannot // extract `expiration`, it's because `_lastCredentialResponse`'s contents // are unexpected (or wrong) in any way. // // Users are considered to be signedIn when the last CredentialResponse // exists and has an expiration date in the future. // // Users are not signed in in any other case. // // See: https://developers.google.com/identity/openid-connect/openid-connect#an-id-tokens-payload isSignedIn = expiration?.isAfter(DateTime.now()) ?? false; } return isSignedIn || _requestedUserData != null; } /// Clears all the cached results from authentication and authorization. Future<void> clearAuthCache() async { _lastCredentialResponse = null; _lastTokenResponse = null; _requestedUserData = null; _lastCodeResponse = null; } /// Requests the list of [scopes] passed in to the client. /// /// Keeps the previously granted scopes. Future<bool> requestScopes(List<String> scopes) async { // If we already know the user, use their `email` as a `hint`, so they don't // have to pick their user again in the Authorization popup. final GoogleSignInUserData? knownUser = utils.gisResponsesToUserData(_lastCredentialResponse); _tokenClient.requestAccessToken(OverridableTokenClientConfig( prompt: knownUser == null ? 'select_account' : '', login_hint: knownUser?.email, scope: scopes, include_granted_scopes: true, )); await _tokenResponses.stream.first; return oauth2.hasGrantedAllScopes(_lastTokenResponse!, scopes); } /// Checks if the passed-in `accessToken` can access all `scopes`. /// /// This validates that the `accessToken` is the same as the last seen /// token response, that the token is not expired, then uses that response to /// check if permissions are still granted. Future<bool> canAccessScopes(List<String> scopes, String? accessToken) async { if (accessToken != null && _lastTokenResponse != null) { if (accessToken == _lastTokenResponse!.access_token) { final bool isTokenValid = _lastTokenResponseExpiration?.isAfter(DateTime.now()) ?? false; return isTokenValid && oauth2.hasGrantedAllScopes(_lastTokenResponse!, scopes); } } return false; } final bool _loggingEnabled; // The scopes initially requested by the developer. // // We store this because we might need to add more at `signIn`. If the user // doesn't `silentSignIn`, we expand this list to consult the People API to // return some basic Authentication information. final List<String> _initialScopes; // The Google Identity Services client for oauth requests. late TokenClient _tokenClient; // CodeClient will not be created if `initialScopes` is empty. CodeClient? _codeClient; // Streams of credential and token responses. late StreamController<CredentialResponse> _credentialResponses; late StreamController<TokenResponse> _tokenResponses; late StreamController<CodeResponse> _codeResponses; // The last-seen credential and token responses CredentialResponse? _lastCredentialResponse; TokenResponse? _lastTokenResponse; // Expiration timestamp for the lastTokenResponse, which only has an `expires_in` field. DateTime? _lastTokenResponseExpiration; CodeResponse? _lastCodeResponse; /// The StreamController onto which the GIS Client propagates user authentication events. /// /// This is provided by the implementation of the plugin. final StreamController<GoogleSignInUserData?> _userDataEventsController; // If the user *authenticates* (signs in) through oauth2, the SDK doesn't return // identity information anymore, so we synthesize it by calling the PeopleAPI // (if needed) // // (This is a synthetic _lastCredentialResponse) // // TODO(dit): Clean this up. https://github.com/flutter/flutter/issues/137727 GoogleSignInUserData? _requestedUserData; }
packages/packages/google_sign_in/google_sign_in_web/lib/src/gis_client.dart/0
{ "file_path": "packages/packages/google_sign_in/google_sign_in_web/lib/src/gis_client.dart", "repo_id": "packages", "token_count": 6431 }
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 'package:flutter/foundation.dart'; import 'package:image_picker_platform_interface/image_picker_platform_interface.dart'; export 'package:image_picker_platform_interface/image_picker_platform_interface.dart' show CameraDevice, ImageSource, LostData, LostDataResponse, PickedFile, RetrieveType, XFile, kTypeImage, kTypeVideo; /// Provides an easy way to pick an image/video from the image library, /// or to take a picture/video with the camera. class ImagePicker { /// The platform interface that drives this plugin @visibleForTesting static ImagePickerPlatform get platform => ImagePickerPlatform.instance; /// Returns an [XFile] object wrapping the image that was picked. /// /// The returned [XFile] is intended to be used within a single app session. /// Do not save the file path and use it across sessions. /// /// The `source` argument controls where the image comes from. This can /// be either [ImageSource.camera] or [ImageSource.gallery]. /// /// Where iOS supports HEIC images, Android 8 and below doesn't. Android 9 and /// above only support HEIC images if used in addition to a size modification, /// of which the usage is explained below. /// /// If specified, the image will be at most `maxWidth` wide and /// `maxHeight` tall. Otherwise the image will be returned at it's /// original width and height. /// The `imageQuality` argument modifies the quality of the image, ranging from 0-100 /// where 100 is the original/max quality. If `imageQuality` is null, the image with /// the original quality will be returned. Compression is only supported for certain /// image types such as JPEG and on Android PNG and WebP, too. If compression is not /// supported for the image that is picked, a warning message will be logged. /// /// Use `preferredCameraDevice` to specify the camera to use when the `source` is /// [ImageSource.camera]. /// The `preferredCameraDevice` is ignored when `source` is [ImageSource.gallery]. /// It is also ignored if the chosen camera is not supported on the device. /// Defaults to [CameraDevice.rear]. Note that Android has no documented parameter /// for an intent to specify if the front or rear camera should be opened, this /// function is not guaranteed to work on an Android device. /// /// Use `requestFullMetadata` (defaults to `true`) to control how much additional /// information the plugin tries to get. /// If `requestFullMetadata` is set to `true`, the plugin tries to get the full /// image metadata which may require extra permission requests on some platforms, /// such as `Photo Library Usage` permission on iOS. /// /// In Android, the MainActivity can be destroyed for various reasons. If that happens, the result will be lost /// in this call. You can then call [retrieveLostData] when your app relaunches to retrieve the lost data. /// /// See also [pickMultiImage] to allow users to select multiple images at once. /// /// The method could throw [PlatformException] if the app does not have permission to access /// the camera or photos gallery, no camera is available, plugin is already in use, /// temporary file could not be created (iOS only), plugin activity could not /// be allocated (Android only) or due to an unknown error. Future<XFile?> pickImage({ required ImageSource source, double? maxWidth, double? maxHeight, int? imageQuality, CameraDevice preferredCameraDevice = CameraDevice.rear, bool requestFullMetadata = true, }) { final ImagePickerOptions imagePickerOptions = ImagePickerOptions.createAndValidate( maxWidth: maxWidth, maxHeight: maxHeight, imageQuality: imageQuality, preferredCameraDevice: preferredCameraDevice, requestFullMetadata: requestFullMetadata, ); return platform.getImageFromSource( source: source, options: imagePickerOptions, ); } /// Returns a [List<XFile>] object wrapping the images that were picked. /// /// The returned [List<XFile>] is intended to be used within a single app session. /// Do not save the file path and use it across sessions. /// /// Where iOS supports HEIC images, Android 8 and below doesn't. Android 9 and above only support HEIC images if used /// in addition to a size modification, of which the usage is explained below. /// /// This method is not supported in iOS versions lower than 14. /// /// If specified, the images will be at most `maxWidth` wide and /// `maxHeight` tall. Otherwise the images will be returned at it's /// original width and height. /// /// The `imageQuality` argument modifies the quality of the images, ranging from 0-100 /// where 100 is the original/max quality. If `imageQuality` is null, the images with /// the original quality will be returned. Compression is only supported for certain /// image types such as JPEG and on Android PNG and WebP, too. If compression is not /// supported for the image that is picked, a warning message will be logged. /// /// Use `requestFullMetadata` (defaults to `true`) to control how much additional /// information the plugin tries to get. /// If `requestFullMetadata` is set to `true`, the plugin tries to get the full /// image metadata which may require extra permission requests on some platforms, /// such as `Photo Library Usage` permission on iOS. /// /// The method could throw [PlatformException] if the app does not have permission to access /// the camera or photos gallery, no camera is available, plugin is already in use, /// temporary file could not be created (iOS only), plugin activity could not /// be allocated (Android only) or due to an unknown error. /// /// See also [pickImage] to allow users to only pick a single image. Future<List<XFile>> pickMultiImage({ double? maxWidth, double? maxHeight, int? imageQuality, bool requestFullMetadata = true, }) { final ImageOptions imageOptions = ImageOptions.createAndValidate( maxWidth: maxWidth, maxHeight: maxHeight, imageQuality: imageQuality, requestFullMetadata: requestFullMetadata, ); return platform.getMultiImageWithOptions( options: MultiImagePickerOptions( imageOptions: imageOptions, ), ); } /// Returns an [XFile] of the image or video that was picked. /// /// The image or video can only come from the gallery. /// /// The returned [XFile] is intended to be used within a single app session. /// Do not save the file path and use it across sessions. /// /// Where iOS supports HEIC images, Android 8 and below doesn't. Android 9 and /// above only support HEIC images if used in addition to a size modification, /// of which the usage is explained below. /// /// This method is not supported in iOS versions lower than 14. /// /// If specified, the image will be at most `maxWidth` wide and /// `maxHeight` tall. Otherwise the image will be returned at it's /// original width and height. /// /// The `imageQuality` argument modifies the quality of the image, ranging from 0-100 /// where 100 is the original/max quality. If `imageQuality` is null, the image with /// the original quality will be returned. Compression is only supported for certain /// image types such as JPEG and on Android PNG and WebP, too. If compression is not /// supported for the image that is picked, a warning message will be logged. /// /// Use `requestFullMetadata` (defaults to `true`) to control how much additional /// information the plugin tries to get. /// If `requestFullMetadata` is set to `true`, the plugin tries to get the full /// image metadata which may require extra permission requests on some platforms, /// such as `Photo Library Usage` permission on iOS. /// /// The method could throw [PlatformException] if the app does not have permission to access /// the photos gallery, plugin is already in use, temporary file could not be /// created (iOS only), plugin activity could not be allocated (Android only) /// or due to an unknown error. /// /// If no image or video was picked, the return value is null. Future<XFile?> pickMedia({ double? maxWidth, double? maxHeight, int? imageQuality, bool requestFullMetadata = true, }) async { final List<XFile> listMedia = await platform.getMedia( options: MediaOptions( imageOptions: ImageOptions.createAndValidate( maxHeight: maxHeight, maxWidth: maxWidth, imageQuality: imageQuality, requestFullMetadata: requestFullMetadata, ), allowMultiple: false, ), ); return listMedia.isNotEmpty ? listMedia.first : null; } /// Returns a [List<XFile>] with the images and/or videos that were picked. /// /// The images and videos come from the gallery. /// /// The returned [List<XFile>] is intended to be used within a single app session. /// Do not save the file paths and use them across sessions. /// /// Where iOS supports HEIC images, Android 8 and below doesn't. Android 9 and /// above only support HEIC images if used in addition to a size modification, /// of which the usage is explained below. /// /// This method is not supported in iOS versions lower than 14. /// /// If specified, the images will be at most `maxWidth` wide and /// `maxHeight` tall. Otherwise the images will be returned at their /// original width and height. /// /// The `imageQuality` argument modifies the quality of the images, ranging from 0-100 /// where 100 is the original/max quality. If `imageQuality` is null, the images with /// the original quality will be returned. Compression is only supported for certain /// image types such as JPEG and on Android PNG and WebP, too. If compression is not /// supported for the image that is picked, a warning message will be logged. /// /// Use `requestFullMetadata` (defaults to `true`) to control how much additional /// information the plugin tries to get. /// If `requestFullMetadata` is set to `true`, the plugin tries to get the full /// image metadata which may require extra permission requests on some platforms, /// such as `Photo Library Usage` permission on iOS. /// /// The method could throw [PlatformException] if the app does not have permission to access /// the photos gallery, plugin is already in use, temporary file could not be /// created (iOS only), plugin activity could not be allocated (Android only) /// or due to an unknown error. /// /// If no images or videos were picked, the return value is an empty list. Future<List<XFile>> pickMultipleMedia({ double? maxWidth, double? maxHeight, int? imageQuality, bool requestFullMetadata = true, }) { return platform.getMedia( options: MediaOptions( allowMultiple: true, imageOptions: ImageOptions.createAndValidate( maxHeight: maxHeight, maxWidth: maxWidth, imageQuality: imageQuality, requestFullMetadata: requestFullMetadata, ), ), ); } /// Returns an [XFile] object wrapping the video that was picked. /// /// The returned [XFile] is intended to be used within a single app session. Do not save the file path and use it across sessions. /// /// The [source] argument controls where the video comes from. This can /// be either [ImageSource.camera] or [ImageSource.gallery]. /// /// The [maxDuration] argument specifies the maximum duration of the captured video. If no [maxDuration] is specified, /// the maximum duration will be infinite. /// /// Use `preferredCameraDevice` to specify the camera to use when the `source` is [ImageSource.camera]. /// The `preferredCameraDevice` is ignored when `source` is [ImageSource.gallery]. It is also ignored if the chosen camera is not supported on the device. /// Defaults to [CameraDevice.rear]. /// /// In Android, the MainActivity can be destroyed for various reasons. If that happens, the result will be lost /// in this call. You can then call [retrieveLostData] when your app relaunches to retrieve the lost data. /// /// The method could throw [PlatformException] if the app does not have permission to access /// the camera or photos gallery, no camera is available, plugin is already in use, /// temporary file could not be created and video could not be cached (iOS only), /// plugin activity could not be allocated (Android only) or due to an unknown error. /// Future<XFile?> pickVideo({ required ImageSource source, CameraDevice preferredCameraDevice = CameraDevice.rear, Duration? maxDuration, }) { return platform.getVideo( source: source, preferredCameraDevice: preferredCameraDevice, maxDuration: maxDuration, ); } /// Retrieve the lost [XFile] when [pickImage], [pickMultiImage] or [pickVideo] failed because the MainActivity /// is destroyed. (Android only) /// /// Image or video can be lost if the MainActivity is destroyed. And there is no guarantee that the MainActivity is always alive. /// Call this method to retrieve the lost data and process the data according to your app's business logic. /// /// Returns a [LostDataResponse] object if successfully retrieved the lost data. The [LostDataResponse] object can \ /// represent either a successful image/video selection, or a failure. /// /// Calling this on a non-Android platform will throw [UnimplementedError] exception. /// /// See also: /// * [LostDataResponse], for what's included in the response. /// * [Android Activity Lifecycle](https://developer.android.com/reference/android/app/Activity.html), for more information on MainActivity destruction. Future<LostDataResponse> retrieveLostData() { return platform.getLostData(); } /// Returns true if the current platform implementation supports [source]. /// /// Calling a `pick*` method with a source for which this method /// returns `false` will throw an error. bool supportsImageSource(ImageSource source) { return platform.supportsImageSource(source); } }
packages/packages/image_picker/image_picker/lib/image_picker.dart/0
{ "file_path": "packages/packages/image_picker/image_picker/lib/image_picker.dart", "repo_id": "packages", "token_count": 4007 }
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. package io.flutter.plugins.imagepicker; import android.Manifest; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.ClipData; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.hardware.camera2.CameraCharacteristics; import android.media.MediaScannerConnection; import android.net.Uri; import android.os.Build; import android.provider.MediaStore; import androidx.activity.result.PickVisualMediaRequest; import androidx.activity.result.contract.ActivityResultContracts; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import androidx.core.app.ActivityCompat; import androidx.core.content.FileProvider; import io.flutter.plugin.common.PluginRegistry; import io.flutter.plugins.imagepicker.Messages.FlutterError; import io.flutter.plugins.imagepicker.Messages.ImageSelectionOptions; import io.flutter.plugins.imagepicker.Messages.VideoSelectionOptions; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * A delegate class doing the heavy lifting for the plugin. * * <p>When invoked, both the {@link #chooseImageFromGallery} and {@link #takeImageWithCamera} * methods go through the same steps: * * <p>1. Check for an existing {@link #pendingCallState}. If a previous pendingCallState exists, * this means that the chooseImageFromGallery() or takeImageWithCamera() method was called at least * twice. In this case, stop executing and finish with an error. * * <p>2. Check that a required runtime permission has been granted. The takeImageWithCamera() method * checks that {@link Manifest.permission#CAMERA} has been granted. * * <p>The permission check can end up in two different outcomes: * * <p>A) If the permission has already been granted, continue with picking the image from gallery or * camera. * * <p>B) If the permission hasn't already been granted, ask for the permission from the user. If the * user grants the permission, proceed with step #3. If the user denies the permission, stop doing * anything else and finish with a null result. * * <p>3. Launch the gallery or camera for picking the image, depending on whether * chooseImageFromGallery() or takeImageWithCamera() was called. * * <p>This can end up in three different outcomes: * * <p>A) User picks an image. No maxWidth or maxHeight was specified when calling {@code * pickImage()} method in the Dart side of this plugin. Finish with full path for the picked image * as the result. * * <p>B) User picks an image. A maxWidth and/or maxHeight was provided when calling {@code * pickImage()} method in the Dart side of this plugin. A scaled copy of the image is created. * Finish with full path for the scaled image as the result. * * <p>C) User cancels picking an image. Finish with null result. */ public class ImagePickerDelegate implements PluginRegistry.ActivityResultListener, PluginRegistry.RequestPermissionsResultListener { @VisibleForTesting static final int REQUEST_CODE_CHOOSE_IMAGE_FROM_GALLERY = 2342; @VisibleForTesting static final int REQUEST_CODE_TAKE_IMAGE_WITH_CAMERA = 2343; @VisibleForTesting static final int REQUEST_CAMERA_IMAGE_PERMISSION = 2345; @VisibleForTesting static final int REQUEST_CODE_CHOOSE_MULTI_IMAGE_FROM_GALLERY = 2346; @VisibleForTesting static final int REQUEST_CODE_CHOOSE_MEDIA_FROM_GALLERY = 2347; @VisibleForTesting static final int REQUEST_CODE_CHOOSE_VIDEO_FROM_GALLERY = 2352; @VisibleForTesting static final int REQUEST_CODE_TAKE_VIDEO_WITH_CAMERA = 2353; @VisibleForTesting static final int REQUEST_CAMERA_VIDEO_PERMISSION = 2355; public enum CameraDevice { REAR, FRONT } /** Holds call state during intent handling. */ private static class PendingCallState { public final @Nullable ImageSelectionOptions imageOptions; public final @Nullable VideoSelectionOptions videoOptions; public final @NonNull Messages.Result<List<String>> result; PendingCallState( @Nullable ImageSelectionOptions imageOptions, @Nullable VideoSelectionOptions videoOptions, @NonNull Messages.Result<List<String>> result) { this.imageOptions = imageOptions; this.videoOptions = videoOptions; this.result = result; } } @VisibleForTesting final String fileProviderName; private final @NonNull Activity activity; private final @NonNull ImageResizer imageResizer; private final @NonNull ImagePickerCache cache; private final PermissionManager permissionManager; private final FileUriResolver fileUriResolver; private final FileUtils fileUtils; private final ExecutorService executor; private CameraDevice cameraDevice; interface PermissionManager { boolean isPermissionGranted(String permissionName); void askForPermission(String permissionName, int requestCode); boolean needRequestCameraPermission(); } interface FileUriResolver { Uri resolveFileProviderUriForFile(String fileProviderName, File imageFile); void getFullImagePath(Uri imageUri, OnPathReadyListener listener); } interface OnPathReadyListener { void onPathReady(String path); } private Uri pendingCameraMediaUri; private @Nullable PendingCallState pendingCallState; private final Object pendingCallStateLock = new Object(); public ImagePickerDelegate( final @NonNull Activity activity, final @NonNull ImageResizer imageResizer, final @NonNull ImagePickerCache cache) { this( activity, imageResizer, null, null, null, cache, new PermissionManager() { @Override public boolean isPermissionGranted(String permissionName) { return ActivityCompat.checkSelfPermission(activity, permissionName) == PackageManager.PERMISSION_GRANTED; } @Override public void askForPermission(String permissionName, int requestCode) { ActivityCompat.requestPermissions(activity, new String[] {permissionName}, requestCode); } @Override public boolean needRequestCameraPermission() { return ImagePickerUtils.needRequestCameraPermission(activity); } }, new FileUriResolver() { @Override public Uri resolveFileProviderUriForFile(String fileProviderName, File file) { return FileProvider.getUriForFile(activity, fileProviderName, file); } @Override public void getFullImagePath(final Uri imageUri, final OnPathReadyListener listener) { MediaScannerConnection.scanFile( activity, new String[] {(imageUri != null) ? imageUri.getPath() : ""}, null, (path, uri) -> listener.onPathReady(path)); } }, new FileUtils(), Executors.newSingleThreadExecutor()); } /** * This constructor is used exclusively for testing; it can be used to provide mocks to final * fields of this class. Otherwise those fields would have to be mutable and visible. */ @VisibleForTesting ImagePickerDelegate( final @NonNull Activity activity, final @NonNull ImageResizer imageResizer, final @Nullable ImageSelectionOptions pendingImageOptions, final @Nullable VideoSelectionOptions pendingVideoOptions, final @Nullable Messages.Result<List<String>> result, final @NonNull ImagePickerCache cache, final PermissionManager permissionManager, final FileUriResolver fileUriResolver, final FileUtils fileUtils, final ExecutorService executor) { this.activity = activity; this.imageResizer = imageResizer; this.fileProviderName = activity.getPackageName() + ".flutter.image_provider"; if (result != null) { this.pendingCallState = new PendingCallState(pendingImageOptions, pendingVideoOptions, result); } this.permissionManager = permissionManager; this.fileUriResolver = fileUriResolver; this.fileUtils = fileUtils; this.cache = cache; this.executor = executor; } void setCameraDevice(CameraDevice device) { cameraDevice = device; } // Save the state of the image picker so it can be retrieved with `retrieveLostImage`. void saveStateBeforeResult() { ImageSelectionOptions localImageOptions; synchronized (pendingCallStateLock) { if (pendingCallState == null) { return; } localImageOptions = pendingCallState.imageOptions; } cache.saveType( localImageOptions != null ? ImagePickerCache.CacheType.IMAGE : ImagePickerCache.CacheType.VIDEO); if (localImageOptions != null) { cache.saveDimensionWithOutputOptions(localImageOptions); } final Uri localPendingCameraMediaUri = pendingCameraMediaUri; if (localPendingCameraMediaUri != null) { cache.savePendingCameraMediaUriPath(localPendingCameraMediaUri); } } @Nullable Messages.CacheRetrievalResult retrieveLostImage() { Map<String, Object> cacheMap = cache.getCacheMap(); if (cacheMap.isEmpty()) { return null; } Messages.CacheRetrievalResult.Builder result = new Messages.CacheRetrievalResult.Builder(); Messages.CacheRetrievalType type = (Messages.CacheRetrievalType) cacheMap.get(ImagePickerCache.MAP_KEY_TYPE); if (type != null) { result.setType(type); } result.setError((Messages.CacheRetrievalError) cacheMap.get(ImagePickerCache.MAP_KEY_ERROR)); @SuppressWarnings("unchecked") ArrayList<String> pathList = (ArrayList<String>) cacheMap.get(ImagePickerCache.MAP_KEY_PATH_LIST); if (pathList != null) { ArrayList<String> newPathList = new ArrayList<>(); for (String path : pathList) { Double maxWidth = (Double) cacheMap.get(ImagePickerCache.MAP_KEY_MAX_WIDTH); Double maxHeight = (Double) cacheMap.get(ImagePickerCache.MAP_KEY_MAX_HEIGHT); Integer boxedImageQuality = (Integer) cacheMap.get(ImagePickerCache.MAP_KEY_IMAGE_QUALITY); int imageQuality = boxedImageQuality == null ? 100 : boxedImageQuality; newPathList.add(imageResizer.resizeImageIfNeeded(path, maxWidth, maxHeight, imageQuality)); } result.setPaths(newPathList); } cache.clear(); return result.build(); } public void chooseMediaFromGallery( @NonNull Messages.MediaSelectionOptions options, @NonNull Messages.GeneralOptions generalOptions, @NonNull Messages.Result<List<String>> result) { if (!setPendingOptionsAndResult(options.getImageSelectionOptions(), null, result)) { finishWithAlreadyActiveError(result); return; } launchPickMediaFromGalleryIntent(generalOptions); } private void launchPickMediaFromGalleryIntent(Messages.GeneralOptions generalOptions) { Intent pickMediaIntent; if (generalOptions.getUsePhotoPicker() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { if (generalOptions.getAllowMultiple()) { pickMediaIntent = new ActivityResultContracts.PickMultipleVisualMedia() .createIntent( activity, new PickVisualMediaRequest.Builder() .setMediaType( ActivityResultContracts.PickVisualMedia.ImageAndVideo.INSTANCE) .build()); } else { pickMediaIntent = new ActivityResultContracts.PickVisualMedia() .createIntent( activity, new PickVisualMediaRequest.Builder() .setMediaType( ActivityResultContracts.PickVisualMedia.ImageAndVideo.INSTANCE) .build()); } } else { pickMediaIntent = new Intent(Intent.ACTION_GET_CONTENT); pickMediaIntent.setType("*/*"); String[] mimeTypes = {"video/*", "image/*"}; pickMediaIntent.putExtra("CONTENT_TYPE", mimeTypes); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { pickMediaIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, generalOptions.getAllowMultiple()); } } activity.startActivityForResult(pickMediaIntent, REQUEST_CODE_CHOOSE_MEDIA_FROM_GALLERY); } public void chooseVideoFromGallery( @NonNull VideoSelectionOptions options, boolean usePhotoPicker, @NonNull Messages.Result<List<String>> result) { if (!setPendingOptionsAndResult(null, options, result)) { finishWithAlreadyActiveError(result); return; } launchPickVideoFromGalleryIntent(usePhotoPicker); } private void launchPickVideoFromGalleryIntent(Boolean usePhotoPicker) { Intent pickVideoIntent; if (usePhotoPicker && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { pickVideoIntent = new ActivityResultContracts.PickVisualMedia() .createIntent( activity, new PickVisualMediaRequest.Builder() .setMediaType(ActivityResultContracts.PickVisualMedia.VideoOnly.INSTANCE) .build()); } else { pickVideoIntent = new Intent(Intent.ACTION_GET_CONTENT); pickVideoIntent.setType("video/*"); } activity.startActivityForResult(pickVideoIntent, REQUEST_CODE_CHOOSE_VIDEO_FROM_GALLERY); } public void takeVideoWithCamera( @NonNull VideoSelectionOptions options, @NonNull Messages.Result<List<String>> result) { if (!setPendingOptionsAndResult(null, options, result)) { finishWithAlreadyActiveError(result); return; } if (needRequestCameraPermission() && !permissionManager.isPermissionGranted(Manifest.permission.CAMERA)) { permissionManager.askForPermission( Manifest.permission.CAMERA, REQUEST_CAMERA_VIDEO_PERMISSION); return; } launchTakeVideoWithCameraIntent(); } private void launchTakeVideoWithCameraIntent() { Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE); VideoSelectionOptions localVideoOptions = null; synchronized (pendingCallStateLock) { if (pendingCallState != null) { localVideoOptions = pendingCallState.videoOptions; } } if (localVideoOptions != null && localVideoOptions.getMaxDurationSeconds() != null) { int maxSeconds = localVideoOptions.getMaxDurationSeconds().intValue(); intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, maxSeconds); } if (cameraDevice == CameraDevice.FRONT) { useFrontCamera(intent); } File videoFile = createTemporaryWritableVideoFile(); pendingCameraMediaUri = Uri.parse("file:" + videoFile.getAbsolutePath()); Uri videoUri = fileUriResolver.resolveFileProviderUriForFile(fileProviderName, videoFile); intent.putExtra(MediaStore.EXTRA_OUTPUT, videoUri); grantUriPermissions(intent, videoUri); try { activity.startActivityForResult(intent, REQUEST_CODE_TAKE_VIDEO_WITH_CAMERA); } catch (ActivityNotFoundException e) { try { // If we can't delete the file again here, there's not really anything we can do about it. //noinspection ResultOfMethodCallIgnored videoFile.delete(); } catch (SecurityException exception) { exception.printStackTrace(); } finishWithError("no_available_camera", "No cameras available for taking pictures."); } } public void chooseImageFromGallery( @NonNull ImageSelectionOptions options, boolean usePhotoPicker, @NonNull Messages.Result<List<String>> result) { if (!setPendingOptionsAndResult(options, null, result)) { finishWithAlreadyActiveError(result); return; } launchPickImageFromGalleryIntent(usePhotoPicker); } public void chooseMultiImageFromGallery( @NonNull ImageSelectionOptions options, boolean usePhotoPicker, @NonNull Messages.Result<List<String>> result) { if (!setPendingOptionsAndResult(options, null, result)) { finishWithAlreadyActiveError(result); return; } launchMultiPickImageFromGalleryIntent(usePhotoPicker); } private void launchPickImageFromGalleryIntent(Boolean usePhotoPicker) { Intent pickImageIntent; if (usePhotoPicker && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { pickImageIntent = new ActivityResultContracts.PickVisualMedia() .createIntent( activity, new PickVisualMediaRequest.Builder() .setMediaType(ActivityResultContracts.PickVisualMedia.ImageOnly.INSTANCE) .build()); } else { pickImageIntent = new Intent(Intent.ACTION_GET_CONTENT); pickImageIntent.setType("image/*"); } activity.startActivityForResult(pickImageIntent, REQUEST_CODE_CHOOSE_IMAGE_FROM_GALLERY); } private void launchMultiPickImageFromGalleryIntent(Boolean usePhotoPicker) { Intent pickMultiImageIntent; if (usePhotoPicker && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { pickMultiImageIntent = new ActivityResultContracts.PickMultipleVisualMedia() .createIntent( activity, new PickVisualMediaRequest.Builder() .setMediaType(ActivityResultContracts.PickVisualMedia.ImageOnly.INSTANCE) .build()); } else { pickMultiImageIntent = new Intent(Intent.ACTION_GET_CONTENT); pickMultiImageIntent.setType("image/*"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { pickMultiImageIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); } } activity.startActivityForResult( pickMultiImageIntent, REQUEST_CODE_CHOOSE_MULTI_IMAGE_FROM_GALLERY); } public void takeImageWithCamera( @NonNull ImageSelectionOptions options, @NonNull Messages.Result<List<String>> result) { if (!setPendingOptionsAndResult(options, null, result)) { finishWithAlreadyActiveError(result); return; } if (needRequestCameraPermission() && !permissionManager.isPermissionGranted(Manifest.permission.CAMERA)) { permissionManager.askForPermission( Manifest.permission.CAMERA, REQUEST_CAMERA_IMAGE_PERMISSION); return; } launchTakeImageWithCameraIntent(); } private boolean needRequestCameraPermission() { if (permissionManager == null) { return false; } return permissionManager.needRequestCameraPermission(); } private void launchTakeImageWithCameraIntent() { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (cameraDevice == CameraDevice.FRONT) { useFrontCamera(intent); } File imageFile = createTemporaryWritableImageFile(); pendingCameraMediaUri = Uri.parse("file:" + imageFile.getAbsolutePath()); Uri imageUri = fileUriResolver.resolveFileProviderUriForFile(fileProviderName, imageFile); intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); grantUriPermissions(intent, imageUri); try { activity.startActivityForResult(intent, REQUEST_CODE_TAKE_IMAGE_WITH_CAMERA); } catch (ActivityNotFoundException e) { try { // If we can't delete the file again here, there's not really anything we can do about it. //noinspection ResultOfMethodCallIgnored imageFile.delete(); } catch (SecurityException exception) { exception.printStackTrace(); } finishWithError("no_available_camera", "No cameras available for taking pictures."); } } private File createTemporaryWritableImageFile() { return createTemporaryWritableFile(".jpg"); } private File createTemporaryWritableVideoFile() { return createTemporaryWritableFile(".mp4"); } private File createTemporaryWritableFile(String suffix) { String filename = UUID.randomUUID().toString(); File image; File externalFilesDirectory = activity.getCacheDir(); try { externalFilesDirectory.mkdirs(); image = File.createTempFile(filename, suffix, externalFilesDirectory); } catch (IOException e) { throw new RuntimeException(e); } return image; } private void grantUriPermissions(Intent intent, Uri imageUri) { PackageManager packageManager = activity.getPackageManager(); List<ResolveInfo> compatibleActivities; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { compatibleActivities = packageManager.queryIntentActivities( intent, PackageManager.ResolveInfoFlags.of(PackageManager.MATCH_DEFAULT_ONLY)); } else { compatibleActivities = queryIntentActivitiesPreApi33(packageManager, intent); } for (ResolveInfo info : compatibleActivities) { activity.grantUriPermission( info.activityInfo.packageName, imageUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); } } @SuppressWarnings("deprecation") private static List<ResolveInfo> queryIntentActivitiesPreApi33( PackageManager packageManager, Intent intent) { return packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); } @Override public boolean onRequestPermissionsResult( int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { boolean permissionGranted = grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED; switch (requestCode) { case REQUEST_CAMERA_IMAGE_PERMISSION: if (permissionGranted) { launchTakeImageWithCameraIntent(); } break; case REQUEST_CAMERA_VIDEO_PERMISSION: if (permissionGranted) { launchTakeVideoWithCameraIntent(); } break; default: return false; } if (!permissionGranted) { switch (requestCode) { case REQUEST_CAMERA_IMAGE_PERMISSION: case REQUEST_CAMERA_VIDEO_PERMISSION: finishWithError("camera_access_denied", "The user did not allow camera access."); break; } } return true; } @Override public boolean onActivityResult( final int requestCode, final int resultCode, final @Nullable Intent data) { Runnable handlerRunnable; switch (requestCode) { case REQUEST_CODE_CHOOSE_IMAGE_FROM_GALLERY: handlerRunnable = () -> handleChooseImageResult(resultCode, data); break; case REQUEST_CODE_CHOOSE_MULTI_IMAGE_FROM_GALLERY: handlerRunnable = () -> handleChooseMultiImageResult(resultCode, data); break; case REQUEST_CODE_TAKE_IMAGE_WITH_CAMERA: handlerRunnable = () -> handleCaptureImageResult(resultCode); break; case REQUEST_CODE_CHOOSE_MEDIA_FROM_GALLERY: handlerRunnable = () -> handleChooseMediaResult(resultCode, data); break; case REQUEST_CODE_CHOOSE_VIDEO_FROM_GALLERY: handlerRunnable = () -> handleChooseVideoResult(resultCode, data); break; case REQUEST_CODE_TAKE_VIDEO_WITH_CAMERA: handlerRunnable = () -> handleCaptureVideoResult(resultCode); break; default: return false; } executor.execute(handlerRunnable); return true; } private void handleChooseImageResult(int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK && data != null) { Uri uri = data.getData(); // On several pre-Android 13 devices using Android Photo Picker, the Uri from getData() could be null. if (uri == null) { ClipData clipData = data.getClipData(); if (clipData != null && clipData.getItemCount() == 1) { uri = clipData.getItemAt(0).getUri(); } } // If there's no valid Uri, return an error if (uri == null) { finishWithError("no_valid_image_uri", "Cannot find the selected image."); return; } String path = fileUtils.getPathFromUri(activity, uri); handleImageResult(path, false); return; } // User cancelled choosing a picture. finishWithSuccess(null); } public class MediaPath { public MediaPath(@NonNull String path, @Nullable String mimeType) { this.path = path; this.mimeType = mimeType; } final String path; final String mimeType; public @NonNull String getPath() { return path; } public @Nullable String getMimeType() { return mimeType; } } private void handleChooseMediaResult(int resultCode, Intent intent) { if (resultCode == Activity.RESULT_OK && intent != null) { ArrayList<MediaPath> paths = new ArrayList<>(); if (intent.getClipData() != null) { for (int i = 0; i < intent.getClipData().getItemCount(); i++) { Uri uri = intent.getClipData().getItemAt(i).getUri(); String path = fileUtils.getPathFromUri(activity, uri); String mimeType = activity.getContentResolver().getType(uri); paths.add(new MediaPath(path, mimeType)); } } else { paths.add(new MediaPath(fileUtils.getPathFromUri(activity, intent.getData()), null)); } handleMediaResult(paths); return; } // User cancelled choosing a picture. finishWithSuccess(null); } private void handleChooseMultiImageResult(int resultCode, Intent intent) { if (resultCode == Activity.RESULT_OK && intent != null) { ArrayList<MediaPath> paths = new ArrayList<>(); if (intent.getClipData() != null) { for (int i = 0; i < intent.getClipData().getItemCount(); i++) { paths.add( new MediaPath( fileUtils.getPathFromUri(activity, intent.getClipData().getItemAt(i).getUri()), null)); } } else { paths.add(new MediaPath(fileUtils.getPathFromUri(activity, intent.getData()), null)); } handleMediaResult(paths); return; } // User cancelled choosing a picture. finishWithSuccess(null); } private void handleChooseVideoResult(int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK && data != null) { Uri uri = data.getData(); // On several pre-Android 13 devices using Android Photo Picker, the Uri from getData() could be null. if (uri == null) { ClipData clipData = data.getClipData(); if (clipData != null && clipData.getItemCount() == 1) { uri = clipData.getItemAt(0).getUri(); } } // If there's no valid Uri, return an error if (uri == null) { finishWithError("no_valid_video_uri", "Cannot find the selected video."); return; } String path = fileUtils.getPathFromUri(activity, uri); handleVideoResult(path); return; } // User cancelled choosing a picture. finishWithSuccess(null); } private void handleCaptureImageResult(int resultCode) { if (resultCode == Activity.RESULT_OK) { final Uri localPendingCameraMediaUri = pendingCameraMediaUri; fileUriResolver.getFullImagePath( localPendingCameraMediaUri != null ? localPendingCameraMediaUri : Uri.parse(cache.retrievePendingCameraMediaUriPath()), path -> handleImageResult(path, true)); return; } // User cancelled taking a picture. finishWithSuccess(null); } private void handleCaptureVideoResult(int resultCode) { if (resultCode == Activity.RESULT_OK) { final Uri localPendingCameraMediaUrl = pendingCameraMediaUri; fileUriResolver.getFullImagePath( localPendingCameraMediaUrl != null ? localPendingCameraMediaUrl : Uri.parse(cache.retrievePendingCameraMediaUriPath()), this::handleVideoResult); return; } // User cancelled taking a picture. finishWithSuccess(null); } void handleImageResult(String path, boolean shouldDeleteOriginalIfScaled) { ImageSelectionOptions localImageOptions = null; synchronized (pendingCallStateLock) { if (pendingCallState != null) { localImageOptions = pendingCallState.imageOptions; } } if (localImageOptions != null) { String finalImagePath = getResizedImagePath(path, localImageOptions); // Delete original file if scaled. if (finalImagePath != null && !finalImagePath.equals(path) && shouldDeleteOriginalIfScaled) { new File(path).delete(); } finishWithSuccess(finalImagePath); } else { finishWithSuccess(path); } } private String getResizedImagePath(String path, @NonNull ImageSelectionOptions outputOptions) { return imageResizer.resizeImageIfNeeded( path, outputOptions.getMaxWidth(), outputOptions.getMaxHeight(), outputOptions.getQuality().intValue()); } private void handleMediaResult(@NonNull ArrayList<MediaPath> paths) { ImageSelectionOptions localImageOptions = null; synchronized (pendingCallStateLock) { if (pendingCallState != null) { localImageOptions = pendingCallState.imageOptions; } } ArrayList<String> finalPaths = new ArrayList<>(); if (localImageOptions != null) { for (int i = 0; i < paths.size(); i++) { MediaPath path = paths.get(i); String finalPath = path.path; if (path.mimeType == null || !path.mimeType.startsWith("video/")) { finalPath = getResizedImagePath(path.path, localImageOptions); } finalPaths.add(finalPath); } finishWithListSuccess(finalPaths); } else { for (int i = 0; i < paths.size(); i++) { finalPaths.add(paths.get(i).path); } finishWithListSuccess(finalPaths); } } private void handleVideoResult(String path) { finishWithSuccess(path); } private boolean setPendingOptionsAndResult( @Nullable ImageSelectionOptions imageOptions, @Nullable VideoSelectionOptions videoOptions, @NonNull Messages.Result<List<String>> result) { synchronized (pendingCallStateLock) { if (pendingCallState != null) { return false; } pendingCallState = new PendingCallState(imageOptions, videoOptions, result); } // Clean up cache if a new image picker is launched. cache.clear(); return true; } // Handles completion of selection with a single result. // // A null imagePath indicates that the image picker was cancelled without // selection. private void finishWithSuccess(@Nullable String imagePath) { ArrayList<String> pathList = new ArrayList<>(); if (imagePath != null) { pathList.add(imagePath); } Messages.Result<List<String>> localResult = null; synchronized (pendingCallStateLock) { if (pendingCallState != null) { localResult = pendingCallState.result; } pendingCallState = null; } if (localResult == null) { // Only save data for later retrieval if something was actually selected. if (!pathList.isEmpty()) { cache.saveResult(pathList, null, null); } } else { localResult.success(pathList); } } private void finishWithListSuccess(ArrayList<String> imagePaths) { Messages.Result<List<String>> localResult = null; synchronized (pendingCallStateLock) { if (pendingCallState != null) { localResult = pendingCallState.result; } pendingCallState = null; } if (localResult == null) { cache.saveResult(imagePaths, null, null); } else { localResult.success(imagePaths); } } private void finishWithAlreadyActiveError(Messages.Result<List<String>> result) { result.error(new FlutterError("already_active", "Image picker is already active", null)); } private void finishWithError(String errorCode, String errorMessage) { Messages.Result<List<String>> localResult = null; synchronized (pendingCallStateLock) { if (pendingCallState != null) { localResult = pendingCallState.result; } pendingCallState = null; } if (localResult == null) { cache.saveResult(null, errorCode, errorMessage); } else { localResult.error(new FlutterError(errorCode, errorMessage, null)); } } private void useFrontCamera(Intent intent) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { intent.putExtra( "android.intent.extras.CAMERA_FACING", CameraCharacteristics.LENS_FACING_FRONT); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { intent.putExtra("android.intent.extra.USE_FRONT_CAMERA", true); } } else { intent.putExtra("android.intent.extras.CAMERA_FACING", 1); } } }
packages/packages/image_picker/image_picker_android/android/src/main/java/io/flutter/plugins/imagepicker/ImagePickerDelegate.java/0
{ "file_path": "packages/packages/image_picker/image_picker_android/android/src/main/java/io/flutter/plugins/imagepicker/ImagePickerDelegate.java", "repo_id": "packages", "token_count": 12352 }
993
mock-maker-inline
packages/packages/image_picker/image_picker_android/android/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker/0
{ "file_path": "packages/packages/image_picker/image_picker_android/android/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker", "repo_id": "packages", "token_count": 6 }
994
// 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:flutter/foundation.dart' show visibleForTesting; import 'package:flutter_web_plugins/flutter_web_plugins.dart'; import 'package:image_picker_platform_interface/image_picker_platform_interface.dart'; import 'package:mime/mime.dart' as mime; import 'package:web/web.dart' as web; import 'src/image_resizer.dart'; import 'src/pkg_web_tweaks.dart'; const String _kImagePickerInputsDomId = '__image_picker_web-file-input'; const String _kAcceptImageMimeType = 'image/*'; const String _kAcceptVideoMimeType = 'video/3gpp,video/x-m4v,video/mp4,video/*'; /// The web implementation of [ImagePickerPlatform]. /// /// This class implements the `package:image_picker` functionality for the web. class ImagePickerPlugin extends ImagePickerPlatform { /// A constructor that allows tests to override the function that creates file inputs. ImagePickerPlugin({ @visibleForTesting ImagePickerPluginTestOverrides? overrides, @visibleForTesting ImageResizer? imageResizer, }) : _overrides = overrides { _imageResizer = imageResizer ?? ImageResizer(); _target = _ensureInitialized(_kImagePickerInputsDomId); } final ImagePickerPluginTestOverrides? _overrides; bool get _hasOverrides => _overrides != null; late web.Element _target; late ImageResizer _imageResizer; /// Registers this class as the default instance of [ImagePickerPlatform]. static void registerWith(Registrar registrar) { ImagePickerPlatform.instance = ImagePickerPlugin(); } /// Returns an [XFile] with the image that was picked, or `null` if no images were picked. @override Future<XFile?> getImageFromSource({ required ImageSource source, ImagePickerOptions options = const ImagePickerOptions(), }) async { final String? capture = computeCaptureAttribute(source, options.preferredCameraDevice); final List<XFile> files = await getFiles( accept: _kAcceptImageMimeType, capture: capture, ); return files.isEmpty ? null : _imageResizer.resizeImageIfNeeded( files.first, options.maxWidth, options.maxHeight, options.imageQuality, ); } /// Returns a [List<XFile>] with the images that were picked, if any. @override Future<List<XFile>> getMultiImageWithOptions({ MultiImagePickerOptions options = const MultiImagePickerOptions(), }) async { final List<XFile> images = await getFiles( accept: _kAcceptImageMimeType, multiple: true, ); final Iterable<Future<XFile>> resized = images.map( (XFile image) => _imageResizer.resizeImageIfNeeded( image, options.imageOptions.maxWidth, options.imageOptions.maxHeight, options.imageOptions.imageQuality, ), ); return Future.wait<XFile>(resized); } /// Returns an [XFile] containing the video that was picked. /// /// The [source] argument controls where the video comes from. This can /// be either [ImageSource.camera] or [ImageSource.gallery]. /// /// Note that the `maxDuration` argument is not supported on the web. If the argument is supplied, it'll be silently ignored by the web version of the plugin. /// /// Use `preferredCameraDevice` to specify the camera to use when the `source` is [ImageSource.camera]. /// The `preferredCameraDevice` is ignored when `source` is [ImageSource.gallery]. It is also ignored if the chosen camera is not supported on the device. /// Defaults to [CameraDevice.rear]. /// /// If no images were picked, the return value is null. @override Future<XFile?> getVideo({ required ImageSource source, CameraDevice preferredCameraDevice = CameraDevice.rear, Duration? maxDuration, }) async { final String? capture = computeCaptureAttribute(source, preferredCameraDevice); final List<XFile> files = await getFiles( accept: _kAcceptVideoMimeType, capture: capture, ); return files.isEmpty ? null : files.first; } /// Injects a file input, and returns a list of XFile media that the user selected locally. @override Future<List<XFile>> getMedia({ required MediaOptions options, }) async { final List<XFile> images = await getFiles( accept: '$_kAcceptImageMimeType,$_kAcceptVideoMimeType', multiple: options.allowMultiple, ); final Iterable<Future<XFile>> resized = images.map((XFile media) { if (mime.lookupMimeType(media.path)?.startsWith('image/') ?? false) { return _imageResizer.resizeImageIfNeeded( media, options.imageOptions.maxWidth, options.imageOptions.maxHeight, options.imageOptions.imageQuality, ); } return Future<XFile>.value(media); }); return Future.wait<XFile>(resized); } /// Injects a file input with the specified accept+capture attributes, and /// returns a list of XFile that the user selected locally. /// /// `capture` is only supported in mobile browsers. /// /// `multiple` can be passed to allow for multiple selection of files. Defaults /// to false. /// /// See https://caniuse.com/#feat=html-media-capture @visibleForTesting Future<List<XFile>> getFiles({ String? accept, String? capture, bool multiple = false, }) { final web.HTMLInputElement input = createInputElement( accept, capture, multiple: multiple, ); _injectAndActivate(input); return _getSelectedXFiles(input).whenComplete(() { input.remove(); }); } // Deprecated methods follow... /// Returns an [XFile] with the image that was picked. /// /// The `source` argument controls where the image comes from. This can /// be either [ImageSource.camera] or [ImageSource.gallery]. /// /// Note that the `maxWidth`, `maxHeight` and `imageQuality` arguments are not supported on the web. If any of these arguments is supplied, it'll be silently ignored by the web version of the plugin. /// /// Use `preferredCameraDevice` to specify the camera to use when the `source` is [ImageSource.camera]. /// The `preferredCameraDevice` is ignored when `source` is [ImageSource.gallery]. It is also ignored if the chosen camera is not supported on the device. /// Defaults to [CameraDevice.rear]. /// /// If no images were picked, the return value is null. @override @Deprecated('Use getImageFromSource instead.') Future<XFile?> getImage({ required ImageSource source, double? maxWidth, double? maxHeight, int? imageQuality, CameraDevice preferredCameraDevice = CameraDevice.rear, }) async { return getImageFromSource( source: source, options: ImagePickerOptions( maxWidth: maxWidth, maxHeight: maxHeight, imageQuality: imageQuality, preferredCameraDevice: preferredCameraDevice, )); } /// Injects a file input, and returns a list of XFile images that the user selected locally. @override @Deprecated('Use getMultiImageWithOptions instead.') Future<List<XFile>> getMultiImage({ double? maxWidth, double? maxHeight, int? imageQuality, }) async { return getMultiImageWithOptions( options: MultiImagePickerOptions( imageOptions: ImageOptions( maxWidth: maxWidth, maxHeight: maxHeight, imageQuality: imageQuality, ), ), ); } // DOM methods /// Converts plugin configuration into a proper value for the `capture` attribute. /// /// See: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#capture @visibleForTesting String? computeCaptureAttribute(ImageSource source, CameraDevice device) { if (source == ImageSource.camera) { return (device == CameraDevice.front) ? 'user' : 'environment'; } return null; } List<web.File>? _getFilesFromInput(web.HTMLInputElement input) { if (_hasOverrides) { return _overrides!.getMultipleFilesFromInput(input); } return input.files?.toList; } /// Handles the OnChange event from a FileUploadInputElement object /// Returns a list of selected files. List<web.File>? _handleOnChangeEvent(web.Event event) { final web.HTMLInputElement? input = event.target as web.HTMLInputElement?; return input == null ? null : _getFilesFromInput(input); } /// Monitors an <input type="file"> and returns the selected file(s). Future<List<XFile>> _getSelectedXFiles(web.HTMLInputElement input) { final Completer<List<XFile>> completer = Completer<List<XFile>>(); // TODO(dit): Migrate all this to Streams (onChange, onError, onCancel) when onCancel is available. // See: https://github.com/dart-lang/web/issues/199 // Observe the input until we can return something input.onchange = (web.Event event) { final List<web.File>? files = _handleOnChangeEvent(event); if (!completer.isCompleted && files != null) { completer.complete(files.map((web.File file) { return XFile( web.URL.createObjectURL(file), name: file.name, length: file.size, lastModified: DateTime.fromMillisecondsSinceEpoch( file.lastModified, ), mimeType: file.type, ); }).toList()); } }.toJS; input.oncancel = (web.Event _) { completer.complete(<XFile>[]); }.toJS; input.onerror = (web.Event event) { if (!completer.isCompleted) { completer.completeError(event); } }.toJS; // Note that we don't bother detaching from these streams, since the // "input" gets re-created in the DOM every time the user needs to // pick a file. return completer.future; } /// Initializes a DOM container where we can host input elements. web.Element _ensureInitialized(String id) { web.Element? target = web.document.querySelector('#$id'); if (target == null) { final web.Element targetElement = web.document.createElement('flt-image-picker-inputs')..id = id; // TODO(ditman): Append inside the `view` of the running app. web.document.body!.append(targetElement); target = targetElement; } return target; } /// Creates an input element that accepts certain file types, and /// allows to `capture` from the device's cameras (where supported) @visibleForTesting web.HTMLInputElement createInputElement( String? accept, String? capture, { bool multiple = false, }) { if (_hasOverrides) { return _overrides!.createInputElement(accept, capture); } final web.HTMLInputElement element = web.HTMLInputElement() ..type = 'file' ..multiple = multiple; if (accept != null) { element.accept = accept; } if (capture != null) { element.setAttribute('capture', capture); } return element; } /// Injects the file input element, and clicks on it void _injectAndActivate(web.HTMLElement element) { _target.replaceChildren(<JSAny>[].toJS); _target.append(element); // TODO(dit): Reimplement this with the showPicker() API, https://github.com/flutter/flutter/issues/130365 element.click(); } } // Some tools to override behavior for unit-testing /// A function that creates a file input with the passed in `accept` and `capture` attributes. @visibleForTesting typedef OverrideCreateInputFunction = web.HTMLInputElement Function( String? accept, String? capture, ); /// A function that extracts list of files from the file `input` passed in. @visibleForTesting typedef OverrideExtractMultipleFilesFromInputFunction = List<web.File> Function( web.HTMLInputElement? input); /// Overrides for some of the functionality above. @visibleForTesting class ImagePickerPluginTestOverrides { /// Override the creation of the input element. late OverrideCreateInputFunction createInputElement; /// Override the extraction of the selected files from an input element. late OverrideExtractMultipleFilesFromInputFunction getMultipleFilesFromInput; }
packages/packages/image_picker/image_picker_for_web/lib/image_picker_for_web.dart/0
{ "file_path": "packages/packages/image_picker/image_picker_for_web/lib/image_picker_for_web.dart", "repo_id": "packages", "token_count": 4193 }
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 "FLTImagePickerPhotoAssetUtil.h" #import "FLTImagePickerImageUtil.h" #import "FLTImagePickerMetaDataUtil.h" #import <MobileCoreServices/MobileCoreServices.h> @implementation FLTImagePickerPhotoAssetUtil + (PHAsset *)getAssetFromImagePickerInfo:(NSDictionary *)info { return info[UIImagePickerControllerPHAsset]; } + (PHAsset *)getAssetFromPHPickerResult:(PHPickerResult *)result API_AVAILABLE(ios(14)) { PHFetchResult *fetchResult = [PHAsset fetchAssetsWithLocalIdentifiers:@[ result.assetIdentifier ] options:nil]; return fetchResult.firstObject; } + (NSURL *)saveVideoFromURL:(NSURL *)videoURL { if (![[NSFileManager defaultManager] isReadableFileAtPath:[videoURL path]]) { return nil; } NSString *fileName = [videoURL lastPathComponent]; NSURL *destination = [NSURL fileURLWithPath:[self temporaryFilePath:fileName]]; NSError *error; [[NSFileManager defaultManager] copyItemAtURL:videoURL toURL:destination error:&error]; if (error) { return nil; } return destination; } + (NSString *)saveImageWithOriginalImageData:(NSData *)originalImageData image:(UIImage *)image maxWidth:(NSNumber *)maxWidth maxHeight:(NSNumber *)maxHeight imageQuality:(NSNumber *)imageQuality { NSString *suffix = kFLTImagePickerDefaultSuffix; FLTImagePickerMIMEType type = kFLTImagePickerMIMETypeDefault; NSDictionary *metaData = nil; // Getting the image type from the original image data if necessary. if (originalImageData) { type = [FLTImagePickerMetaDataUtil getImageMIMETypeFromImageData:originalImageData]; suffix = [FLTImagePickerMetaDataUtil imageTypeSuffixFromType:type] ?: kFLTImagePickerDefaultSuffix; metaData = [FLTImagePickerMetaDataUtil getMetaDataFromImageData:originalImageData]; } if (type == FLTImagePickerMIMETypeGIF) { GIFInfo *gifInfo = [FLTImagePickerImageUtil scaledGIFImage:originalImageData maxWidth:maxWidth maxHeight:maxHeight]; return [self saveImageWithMetaData:metaData gifInfo:gifInfo suffix:suffix]; } else { return [self saveImageWithMetaData:metaData image:image suffix:suffix type:type imageQuality:imageQuality]; } } + (NSString *)saveImageWithPickerInfo:(nullable NSDictionary *)info image:(UIImage *)image imageQuality:(NSNumber *)imageQuality { NSDictionary *metaData = info[UIImagePickerControllerMediaMetadata]; return [self saveImageWithMetaData:metaData image:image suffix:kFLTImagePickerDefaultSuffix type:kFLTImagePickerMIMETypeDefault imageQuality:imageQuality]; } + (NSString *)saveImageWithMetaData:(NSDictionary *)metaData gifInfo:(GIFInfo *)gifInfo suffix:(NSString *)suffix { NSString *path = [self temporaryFilePath:suffix]; return [self saveImageWithMetaData:metaData gifInfo:gifInfo path:path]; } + (NSString *)saveImageWithMetaData:(NSDictionary *)metaData image:(UIImage *)image suffix:(NSString *)suffix type:(FLTImagePickerMIMEType)type imageQuality:(NSNumber *)imageQuality { NSData *data = [FLTImagePickerMetaDataUtil convertImage:image usingType:type quality:imageQuality]; if (metaData) { NSData *updatedData = [FLTImagePickerMetaDataUtil imageFromImage:data withMetaData:metaData]; // If updating the metadata fails, just save the original. if (updatedData) { data = updatedData; } } return [self createFile:data suffix:suffix]; } + (NSString *)saveImageWithMetaData:(NSDictionary *)metaData gifInfo:(GIFInfo *)gifInfo path:(NSString *)path { CGImageDestinationRef destination = CGImageDestinationCreateWithURL( (__bridge CFURLRef)[NSURL fileURLWithPath:path], kUTTypeGIF, gifInfo.images.count, NULL); NSDictionary *frameProperties = @{ (__bridge NSString *)kCGImagePropertyGIFDictionary : @{ (__bridge NSString *)kCGImagePropertyGIFDelayTime : @(gifInfo.interval), }, }; NSMutableDictionary *gifMetaProperties = [NSMutableDictionary dictionaryWithDictionary:metaData]; NSMutableDictionary *gifProperties = (NSMutableDictionary *)gifMetaProperties[(NSString *)kCGImagePropertyGIFDictionary]; if (gifMetaProperties == nil) { gifProperties = [NSMutableDictionary dictionary]; } gifProperties[(__bridge NSString *)kCGImagePropertyGIFLoopCount] = @0; CGImageDestinationSetProperties(destination, (__bridge CFDictionaryRef)gifMetaProperties); for (NSInteger index = 0; index < gifInfo.images.count; index++) { UIImage *image = (UIImage *)[gifInfo.images objectAtIndex:index]; CGImageDestinationAddImage(destination, image.CGImage, (__bridge CFDictionaryRef)frameProperties); } CGImageDestinationFinalize(destination); CFRelease(destination); return path; } + (NSString *)temporaryFilePath:(NSString *)suffix { NSString *fileExtension = [@"image_picker_%@" stringByAppendingString:suffix]; NSString *guid = [[NSProcessInfo processInfo] globallyUniqueString]; NSString *tmpFile = [NSString stringWithFormat:fileExtension, guid]; NSString *tmpDirectory = NSTemporaryDirectory(); NSString *tmpPath = [tmpDirectory stringByAppendingPathComponent:tmpFile]; return tmpPath; } + (NSString *)createFile:(NSData *)data suffix:(NSString *)suffix { NSString *tmpPath = [self temporaryFilePath:suffix]; if ([[NSFileManager defaultManager] createFileAtPath:tmpPath contents:data attributes:nil]) { return tmpPath; } else { nil; } return tmpPath; } @end
packages/packages/image_picker/image_picker_ios/ios/Classes/FLTImagePickerPhotoAssetUtil.m/0
{ "file_path": "packages/packages/image_picker/image_picker_ios/ios/Classes/FLTImagePickerPhotoAssetUtil.m", "repo_id": "packages", "token_count": 2736 }
996
name: image_picker_ios description: iOS implementation of the image_picker plugin. repository: https://github.com/flutter/packages/tree/main/packages/image_picker/image_picker_ios issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+image_picker%22 version: 0.8.9+2 environment: sdk: ^3.2.3 flutter: ">=3.16.6" flutter: plugin: implements: image_picker platforms: ios: dartPluginClass: ImagePickerIOS pluginClass: FLTImagePickerPlugin dependencies: flutter: sdk: flutter image_picker_platform_interface: ^2.8.0 dev_dependencies: flutter_test: sdk: flutter mockito: 5.4.4 pigeon: ^13.0.0 topics: - camera - image-picker - files - file-selection
packages/packages/image_picker/image_picker_ios/pubspec.yaml/0
{ "file_path": "packages/packages/image_picker/image_picker_ios/pubspec.yaml", "repo_id": "packages", "token_count": 318 }
997
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
packages/packages/image_picker/image_picker_macos/example/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "packages/packages/image_picker/image_picker_macos/example/macos/Runner/Configs/Release.xcconfig", "repo_id": "packages", "token_count": 32 }
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. /// The type of the retrieved data in a [LostDataResponse]. enum RetrieveType { /// A static picture. See [ImagePicker.pickImage]. image, /// A video. See [ImagePicker.pickVideo]. video, /// Either a video or a static picture. See [ImagePicker.pickMedia]. media, }
packages/packages/image_picker/image_picker_platform_interface/lib/src/types/retrieve_type.dart/0
{ "file_path": "packages/packages/image_picker/image_picker_platform_interface/lib/src/types/retrieve_type.dart", "repo_id": "packages", "token_count": 128 }
999
name: image_picker_windows description: Windows platform implementation of image_picker repository: https://github.com/flutter/packages/tree/main/packages/image_picker/image_picker_windows issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+image_picker%22 version: 0.2.1+1 environment: sdk: ^3.1.0 flutter: ">=3.13.0" flutter: plugin: implements: image_picker platforms: windows: dartPluginClass: ImagePickerWindows dependencies: file_selector_platform_interface: ^2.2.0 file_selector_windows: ^0.9.0 flutter: sdk: flutter image_picker_platform_interface: ^2.8.0 dev_dependencies: build_runner: ^2.1.5 flutter_test: sdk: flutter mockito: 5.4.4 topics: - image-picker - files - file-selection
packages/packages/image_picker/image_picker_windows/pubspec.yaml/0
{ "file_path": "packages/packages/image_picker/image_picker_windows/pubspec.yaml", "repo_id": "packages", "token_count": 327 }
1,000
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
packages/packages/in_app_purchase/in_app_purchase/example/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase/example/macos/Runner/Configs/Release.xcconfig", "repo_id": "packages", "token_count": 32 }
1,001
rootProject.name = 'in_app_purchase'
packages/packages/in_app_purchase/in_app_purchase_android/android/settings.gradle/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/android/settings.gradle", "repo_id": "packages", "token_count": 14 }
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:json_annotation/json_annotation.dart'; import '../../billing_client_wrappers.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 'billing_config_wrapper.g.dart'; /// The error message shown when the map represents billing config is invalid from method channel. /// /// This usually indicates a serious underlining code issue in the plugin. @visibleForTesting const String kInvalidBillingConfigErrorMessage = 'Invalid billing config map from method channel.'; /// Params containing the response code and the debug message from the Play Billing API response. @JsonSerializable() @BillingResponseConverter() @immutable class BillingConfigWrapper implements HasBillingResponse { /// Constructs the object with [responseCode] and [debugMessage]. const BillingConfigWrapper( {required this.responseCode, this.debugMessage, this.countryCode = ''}); /// Constructs an instance of this from a key value map of data. /// /// The map needs to have named string keys with values matching the names and /// types of all of the members on this class. factory BillingConfigWrapper.fromJson(Map<String, dynamic>? map) { if (map == null || map.isEmpty) { return const BillingConfigWrapper( responseCode: BillingResponse.error, debugMessage: kInvalidBillingConfigErrorMessage, ); } return _$BillingConfigWrapperFromJson(map); } /// Response code returned in the Play Billing API calls. @override final BillingResponse responseCode; /// Debug message returned in the Play Billing API calls. /// /// Defaults to `null`. /// This message uses an en-US locale and should not be shown to users. @JsonKey(defaultValue: '') final String? debugMessage; /// https://developer.android.com/reference/com/android/billingclient/api/BillingConfig#getCountryCode() @JsonKey(defaultValue: '') final String countryCode; @override bool operator ==(Object other) { if (other.runtimeType != runtimeType) { return false; } return other is BillingConfigWrapper && other.responseCode == responseCode && other.debugMessage == debugMessage && other.countryCode == countryCode; } @override int get hashCode => Object.hash(responseCode, debugMessage, countryCode); }
packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/billing_config_wrapper.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/lib/src/billing_client_wrappers/billing_config_wrapper.dart", "repo_id": "packages", "token_count": 776 }
1,003
// 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'; /// Method channel for the plugin's platform<-->Dart calls. const MethodChannel channel = MethodChannel('plugins.flutter.io/in_app_purchase');
packages/packages/in_app_purchase/in_app_purchase_android/lib/src/channel.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/lib/src/channel.dart", "repo_id": "packages", "token_count": 98 }
1,004
// 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:in_app_purchase_android/billing_client_wrappers.dart'; import 'package:test/test.dart'; const ProductWrapper dummyProduct = ProductWrapper( productId: 'id', productType: ProductType.inapp, ); void main() { group('ProductWrapper', () { test('converts product from map', () { const ProductWrapper expected = dummyProduct; final ProductWrapper parsed = productFromJson(expected.toJson()); expect(parsed, equals(expected)); }); }); } ProductWrapper productFromJson(Map<String, dynamic> serialized) { return ProductWrapper( productId: serialized['productId'] as String, productType: const ProductTypeConverter() .fromJson(serialized['productType'] as String), ); }
packages/packages/in_app_purchase/in_app_purchase_android/test/billing_client_wrappers/product_wrapper_test.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_android/test/billing_client_wrappers/product_wrapper_test.dart", "repo_id": "packages", "token_count": 291 }
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. #import "InAppPurchasePlugin.h" #import <StoreKit/StoreKit.h> #import "FIAObjectTranslator.h" #import "FIAPPaymentQueueDelegate.h" #import "FIAPReceiptManager.h" #import "FIAPRequestHandler.h" #import "FIAPaymentQueueHandler.h" #import "InAppPurchasePlugin+TestOnly.h" @interface InAppPurchasePlugin () // After querying the product, the available products will be saved in the map to be used // for purchase. @property(strong, nonatomic, readonly) NSMutableDictionary *productsCache; // Callback channel to dart used for when a function from the payment queue delegate is triggered. @property(strong, nonatomic, readonly) FlutterMethodChannel *paymentQueueDelegateCallbackChannel; @property(strong, nonatomic, readonly) NSObject<FlutterPluginRegistrar> *registrar; @property(strong, nonatomic, readonly) FIAPReceiptManager *receiptManager; @property(strong, nonatomic, readonly) FIAPPaymentQueueDelegate *paymentQueueDelegate API_AVAILABLE(ios(13)) API_UNAVAILABLE(tvos, macos, watchos); @end @implementation InAppPurchasePlugin + (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar { FlutterMethodChannel *channel = [FlutterMethodChannel methodChannelWithName:@"plugins.flutter.io/in_app_purchase" binaryMessenger:[registrar messenger]]; InAppPurchasePlugin *instance = [[InAppPurchasePlugin alloc] initWithRegistrar:registrar]; [registrar addMethodCallDelegate:instance channel:channel]; [registrar addApplicationDelegate:instance]; SetUpInAppPurchaseAPI(registrar.messenger, instance); } - (instancetype)initWithReceiptManager:(FIAPReceiptManager *)receiptManager { self = [super init]; _receiptManager = receiptManager; _requestHandlers = [NSMutableSet new]; _productsCache = [NSMutableDictionary new]; _handlerFactory = ^FIAPRequestHandler *(SKRequest *request) { return [[FIAPRequestHandler alloc] initWithRequest:request]; }; return self; } - (instancetype)initWithReceiptManager:(FIAPReceiptManager *)receiptManager handlerFactory:(FIAPRequestHandler * (^)(SKRequest *))handlerFactory { self = [self initWithReceiptManager:receiptManager]; _handlerFactory = [handlerFactory copy]; return self; } - (instancetype)initWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar { self = [self initWithReceiptManager:[FIAPReceiptManager new]]; _registrar = registrar; __weak typeof(self) weakSelf = self; _paymentQueueHandler = [[FIAPaymentQueueHandler alloc] initWithQueue:[SKPaymentQueue defaultQueue] transactionsUpdated:^(NSArray<SKPaymentTransaction *> *_Nonnull transactions) { [weakSelf handleTransactionsUpdated:transactions]; } transactionRemoved:^(NSArray<SKPaymentTransaction *> *_Nonnull transactions) { [weakSelf handleTransactionsRemoved:transactions]; } restoreTransactionFailed:^(NSError *_Nonnull error) { [weakSelf handleTransactionRestoreFailed:error]; } restoreCompletedTransactionsFinished:^{ [weakSelf restoreCompletedTransactionsFinished]; } shouldAddStorePayment:^BOOL(SKPayment *payment, SKProduct *product) { return [weakSelf shouldAddStorePayment:payment product:product]; } updatedDownloads:^void(NSArray<SKDownload *> *_Nonnull downloads) { [weakSelf updatedDownloads:downloads]; } transactionCache:[[FIATransactionCache alloc] init]]; _transactionObserverCallbackChannel = [FlutterMethodChannel methodChannelWithName:@"plugins.flutter.io/in_app_purchase" binaryMessenger:[registrar messenger]]; return self; } - (nullable NSNumber *)canMakePaymentsWithError: (FlutterError *_Nullable __autoreleasing *_Nonnull)error { return @([SKPaymentQueue canMakePayments]); } - (nullable NSArray<SKPaymentTransactionMessage *> *)transactionsWithError: (FlutterError *_Nullable *_Nonnull)error { NSArray<SKPaymentTransaction *> *transactions = [self.paymentQueueHandler getUnfinishedTransactions]; NSMutableArray *transactionMaps = [[NSMutableArray alloc] init]; for (SKPaymentTransaction *transaction in transactions) { [transactionMaps addObject:[FIAObjectTranslator convertTransactionToPigeon:transaction]]; } return transactionMaps; } - (nullable SKStorefrontMessage *)storefrontWithError:(FlutterError *_Nullable *_Nonnull)error API_AVAILABLE(ios(13.0), macos(10.15)) { SKStorefront *storefront = self.paymentQueueHandler.storefront; if (!storefront) { return nil; } return [FIAObjectTranslator convertStorefrontToPigeon:storefront]; } - (void)startProductRequestProductIdentifiers:(NSArray<NSString *> *)productIdentifiers completion:(void (^)(SKProductsResponseMessage *_Nullable, FlutterError *_Nullable))completion { SKProductsRequest *request = [self getProductRequestWithIdentifiers:[NSSet setWithArray:productIdentifiers]]; FIAPRequestHandler *handler = self.handlerFactory(request); [self.requestHandlers addObject:handler]; __weak typeof(self) weakSelf = self; [handler startProductRequestWithCompletionHandler:^(SKProductsResponse *_Nullable response, NSError *_Nullable startProductRequestError) { FlutterError *error = nil; if (startProductRequestError != nil) { error = [FlutterError errorWithCode:@"storekit_getproductrequest_platform_error" message:startProductRequestError.localizedDescription details:startProductRequestError.description]; completion(nil, error); return; } if (!response) { error = [FlutterError errorWithCode:@"storekit_platform_no_response" message:@"Failed to get SKProductResponse in startRequest " @"call. Error occured on iOS platform" details:productIdentifiers]; completion(nil, error); return; } for (SKProduct *product in response.products) { [self.productsCache setObject:product forKey:product.productIdentifier]; } completion([FIAObjectTranslator convertProductsResponseToPigeon:response], error); [weakSelf.requestHandlers removeObject:handler]; }]; } - (void)addPaymentPaymentMap:(nonnull NSDictionary *)paymentMap error:(FlutterError *_Nullable __autoreleasing *_Nonnull)error { NSString *productID = [paymentMap objectForKey:@"productIdentifier"]; // When a product is already fetched, we create a payment object with // the product to process the payment. SKProduct *product = [self getProduct:productID]; if (!product) { *error = [FlutterError errorWithCode:@"storekit_invalid_payment_object" message: @"You have requested a payment for an invalid product. Either the " @"`productIdentifier` of the payment is not valid or the product has not been " @"fetched before adding the payment to the payment queue." details:paymentMap]; return; } SKMutablePayment *payment = [SKMutablePayment paymentWithProduct:product]; payment.applicationUsername = [paymentMap objectForKey:@"applicationUsername"]; NSNumber *quantity = [paymentMap objectForKey:@"quantity"]; payment.quantity = (quantity != nil) ? quantity.integerValue : 1; NSNumber *simulatesAskToBuyInSandbox = [paymentMap objectForKey:@"simulatesAskToBuyInSandbox"]; payment.simulatesAskToBuyInSandbox = (id)simulatesAskToBuyInSandbox == (id)[NSNull null] ? NO : [simulatesAskToBuyInSandbox boolValue]; if (@available(iOS 12.2, *)) { NSDictionary *paymentDiscountMap = [self getNonNullValueFromDictionary:paymentMap forKey:@"paymentDiscount"]; NSString *errorMsg = nil; SKPaymentDiscount *paymentDiscount = [FIAObjectTranslator getSKPaymentDiscountFromMap:paymentDiscountMap withError:&errorMsg]; if (errorMsg) { *error = [FlutterError errorWithCode:@"storekit_invalid_payment_discount_object" message:[NSString stringWithFormat:@"You have requested a payment and specified a " @"payment discount with invalid properties. %@", errorMsg] details:paymentMap]; return; } payment.paymentDiscount = paymentDiscount; } if (![self.paymentQueueHandler addPayment:payment]) { *error = [FlutterError errorWithCode:@"storekit_duplicate_product_object" message:@"There is a pending transaction for the same product identifier. Please " @"either wait for it to be finished or finish it manually using " @"`completePurchase` to avoid edge cases." details:paymentMap]; return; } } - (void)finishTransactionFinishMap:(nonnull NSDictionary<NSString *, NSString *> *)finishMap error:(FlutterError *_Nullable __autoreleasing *_Nonnull)error { NSString *transactionIdentifier = [finishMap objectForKey:@"transactionIdentifier"]; NSString *productIdentifier = [finishMap objectForKey:@"productIdentifier"]; NSArray<SKPaymentTransaction *> *pendingTransactions = [self.paymentQueueHandler getUnfinishedTransactions]; for (SKPaymentTransaction *transaction in pendingTransactions) { // If the user cancels the purchase dialog we won't have a transactionIdentifier. // So if it is null AND a transaction in the pendingTransactions list has // also a null transactionIdentifier we check for equal product identifiers. if ([transaction.transactionIdentifier isEqualToString:transactionIdentifier] || ([transactionIdentifier isEqual:[NSNull null]] && transaction.transactionIdentifier == nil && [transaction.payment.productIdentifier isEqualToString:productIdentifier])) { @try { [self.paymentQueueHandler finishTransaction:transaction]; } @catch (NSException *e) { *error = [FlutterError errorWithCode:@"storekit_finish_transaction_exception" message:e.name details:e.description]; return; } } } } - (void)restoreTransactionsApplicationUserName:(nullable NSString *)applicationUserName error:(FlutterError *_Nullable __autoreleasing *_Nonnull) error { [self.paymentQueueHandler restoreTransactions:applicationUserName]; } - (void)presentCodeRedemptionSheetWithError: (FlutterError *_Nullable __autoreleasing *_Nonnull)error { #if TARGET_OS_IOS [self.paymentQueueHandler presentCodeRedemptionSheet]; #endif } - (nullable NSString *)retrieveReceiptDataWithError: (FlutterError *_Nullable __autoreleasing *_Nonnull)error { FlutterError *flutterError; NSString *receiptData = [self.receiptManager retrieveReceiptWithError:&flutterError]; if (flutterError) { *error = flutterError; return nil; } return receiptData; } - (void)refreshReceiptReceiptProperties:(nullable NSDictionary *)receiptProperties completion:(nonnull void (^)(FlutterError *_Nullable))completion { SKReceiptRefreshRequest *request; if (receiptProperties) { // if recieptProperties is not null, this call is for testing. NSMutableDictionary *properties = [NSMutableDictionary new]; properties[SKReceiptPropertyIsExpired] = receiptProperties[@"isExpired"]; properties[SKReceiptPropertyIsRevoked] = receiptProperties[@"isRevoked"]; properties[SKReceiptPropertyIsVolumePurchase] = receiptProperties[@"isVolumePurchase"]; request = [self getRefreshReceiptRequest:properties]; } else { request = [self getRefreshReceiptRequest:nil]; } FIAPRequestHandler *handler = self.handlerFactory(request); [self.requestHandlers addObject:handler]; __weak typeof(self) weakSelf = self; [handler startProductRequestWithCompletionHandler:^(SKProductsResponse *_Nullable response, NSError *_Nullable error) { FlutterError *requestError; if (error) { requestError = [FlutterError errorWithCode:@"storekit_refreshreceiptrequest_platform_error" message:error.localizedDescription details:error.description]; completion(requestError); return; } completion(nil); [weakSelf.requestHandlers removeObject:handler]; }]; } - (void)startObservingPaymentQueueWithError: (FlutterError *_Nullable __autoreleasing *_Nonnull)error { [_paymentQueueHandler startObservingPaymentQueue]; } - (void)stopObservingPaymentQueueWithError: (FlutterError *_Nullable __autoreleasing *_Nonnull)error { [_paymentQueueHandler stopObservingPaymentQueue]; } - (void)registerPaymentQueueDelegateWithError: (FlutterError *_Nullable __autoreleasing *_Nonnull)error { #if TARGET_OS_IOS if (@available(iOS 13.0, *)) { _paymentQueueDelegateCallbackChannel = [FlutterMethodChannel methodChannelWithName:@"plugins.flutter.io/in_app_purchase_payment_queue_delegate" binaryMessenger:[_registrar messenger]]; _paymentQueueDelegate = [[FIAPPaymentQueueDelegate alloc] initWithMethodChannel:_paymentQueueDelegateCallbackChannel]; _paymentQueueHandler.delegate = _paymentQueueDelegate; } #endif } - (void)removePaymentQueueDelegateWithError: (FlutterError *_Nullable __autoreleasing *_Nonnull)error { if (@available(iOS 13.0, *)) { _paymentQueueHandler.delegate = nil; } _paymentQueueDelegate = nil; _paymentQueueDelegateCallbackChannel = nil; } - (void)showPriceConsentIfNeededWithError:(FlutterError *_Nullable __autoreleasing *_Nonnull)error { #if TARGET_OS_IOS if (@available(iOS 13.4, *)) { [_paymentQueueHandler showPriceConsentIfNeeded]; } #endif } - (id)getNonNullValueFromDictionary:(NSDictionary *)dictionary forKey:(NSString *)key { id value = dictionary[key]; return [value isKindOfClass:[NSNull class]] ? nil : value; } #pragma mark - transaction observer: - (void)handleTransactionsUpdated:(NSArray<SKPaymentTransaction *> *)transactions { NSMutableArray *maps = [NSMutableArray new]; for (SKPaymentTransaction *transaction in transactions) { [maps addObject:[FIAObjectTranslator getMapFromSKPaymentTransaction:transaction]]; } [self.transactionObserverCallbackChannel invokeMethod:@"updatedTransactions" arguments:maps]; } - (void)handleTransactionsRemoved:(NSArray<SKPaymentTransaction *> *)transactions { NSMutableArray *maps = [NSMutableArray new]; for (SKPaymentTransaction *transaction in transactions) { [maps addObject:[FIAObjectTranslator getMapFromSKPaymentTransaction:transaction]]; } [self.transactionObserverCallbackChannel invokeMethod:@"removedTransactions" arguments:maps]; } - (void)handleTransactionRestoreFailed:(NSError *)error { [self.transactionObserverCallbackChannel invokeMethod:@"restoreCompletedTransactionsFailed" arguments:[FIAObjectTranslator getMapFromNSError:error]]; } - (void)restoreCompletedTransactionsFinished { [self.transactionObserverCallbackChannel invokeMethod:@"paymentQueueRestoreCompletedTransactionsFinished" arguments:nil]; } - (void)updatedDownloads:(NSArray<SKDownload *> *)downloads { NSLog(@"Received an updatedDownloads callback, but downloads are not supported."); } - (BOOL)shouldAddStorePayment:(SKPayment *)payment product:(SKProduct *)product { // We always return NO here. And we send the message to dart to process the payment; and we will // have a interception method that deciding if the payment should be processed (implemented by the // programmer). [self.productsCache setObject:product forKey:product.productIdentifier]; [self.transactionObserverCallbackChannel invokeMethod:@"shouldAddStorePayment" arguments:@{ @"payment" : [FIAObjectTranslator getMapFromSKPayment:payment], @"product" : [FIAObjectTranslator getMapFromSKProduct:product] }]; return NO; } #pragma mark - dependency injection (for unit testing) - (SKProductsRequest *)getProductRequestWithIdentifiers:(NSSet *)identifiers { return [[SKProductsRequest alloc] initWithProductIdentifiers:identifiers]; } - (SKProduct *)getProduct:(NSString *)productID { return [self.productsCache objectForKey:productID]; } - (SKReceiptRefreshRequest *)getRefreshReceiptRequest:(NSDictionary *)properties { return [[SKReceiptRefreshRequest alloc] initWithReceiptProperties:properties]; } @end
packages/packages/in_app_purchase/in_app_purchase_storekit/darwin/Classes/InAppPurchasePlugin.m/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_storekit/darwin/Classes/InAppPurchasePlugin.m", "repo_id": "packages", "token_count": 6363 }
1,006
// 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 (v16.0.4), 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, unnecessary_import, no_leading_underscores_for_local_identifiers // ignore_for_file: avoid_relative_lib_imports 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'; import 'package:flutter_test/flutter_test.dart'; import 'package:in_app_purchase_storekit/src/messages.g.dart'; class _TestInAppPurchaseApiCodec extends StandardMessageCodec { const _TestInAppPurchaseApiCodec(); @override void writeValue(WriteBuffer buffer, Object? value) { if (value is SKErrorMessage) { buffer.putUint8(128); writeValue(buffer, value.encode()); } else if (value is SKPaymentDiscountMessage) { buffer.putUint8(129); writeValue(buffer, value.encode()); } else if (value is SKPaymentMessage) { buffer.putUint8(130); writeValue(buffer, value.encode()); } else if (value is SKPaymentTransactionMessage) { buffer.putUint8(131); writeValue(buffer, value.encode()); } else if (value is SKPriceLocaleMessage) { buffer.putUint8(132); writeValue(buffer, value.encode()); } else if (value is SKProductDiscountMessage) { buffer.putUint8(133); writeValue(buffer, value.encode()); } else if (value is SKProductMessage) { buffer.putUint8(134); writeValue(buffer, value.encode()); } else if (value is SKProductSubscriptionPeriodMessage) { buffer.putUint8(135); writeValue(buffer, value.encode()); } else if (value is SKProductsResponseMessage) { buffer.putUint8(136); writeValue(buffer, value.encode()); } else if (value is SKStorefrontMessage) { buffer.putUint8(137); writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } } @override Object? readValueOfType(int type, ReadBuffer buffer) { switch (type) { case 128: return SKErrorMessage.decode(readValue(buffer)!); case 129: return SKPaymentDiscountMessage.decode(readValue(buffer)!); case 130: return SKPaymentMessage.decode(readValue(buffer)!); case 131: return SKPaymentTransactionMessage.decode(readValue(buffer)!); case 132: return SKPriceLocaleMessage.decode(readValue(buffer)!); case 133: return SKProductDiscountMessage.decode(readValue(buffer)!); case 134: return SKProductMessage.decode(readValue(buffer)!); case 135: return SKProductSubscriptionPeriodMessage.decode(readValue(buffer)!); case 136: return SKProductsResponseMessage.decode(readValue(buffer)!); case 137: return SKStorefrontMessage.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } } } abstract class TestInAppPurchaseApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> pigeonChannelCodec = _TestInAppPurchaseApiCodec(); /// Returns if the current device is able to make payments bool canMakePayments(); List<SKPaymentTransactionMessage?> transactions(); SKStorefrontMessage storefront(); void addPayment(Map<String?, Object?> paymentMap); Future<SKProductsResponseMessage> startProductRequest( List<String?> productIdentifiers); void finishTransaction(Map<String?, String?> finishMap); void restoreTransactions(String? applicationUserName); void presentCodeRedemptionSheet(); String? retrieveReceiptData(); Future<void> refreshReceipt({Map<String?, Object?>? receiptProperties}); void startObservingPaymentQueue(); void stopObservingPaymentQueue(); void registerPaymentQueueDelegate(); void removePaymentQueueDelegate(); void showPriceConsentIfNeeded(); static void setup(TestInAppPurchaseApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.canMakePayments', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(__pigeon_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(__pigeon_channel, (Object? message) async { try { final bool output = api.canMakePayments(); return <Object?>[output]; } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.transactions', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(__pigeon_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(__pigeon_channel, (Object? message) async { try { final List<SKPaymentTransactionMessage?> output = api.transactions(); return <Object?>[output]; } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.storefront', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(__pigeon_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(__pigeon_channel, (Object? message) async { try { final SKStorefrontMessage output = api.storefront(); return <Object?>[output]; } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.addPayment', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(__pigeon_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(__pigeon_channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.addPayment was null.'); final List<Object?> args = (message as List<Object?>?)!; final Map<String?, Object?>? arg_paymentMap = (args[0] as Map<Object?, Object?>?)?.cast<String?, Object?>(); assert(arg_paymentMap != null, 'Argument for dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.addPayment was null, expected non-null Map<String?, Object?>.'); try { api.addPayment(arg_paymentMap!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.startProductRequest', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(__pigeon_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(__pigeon_channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.startProductRequest was null.'); final List<Object?> args = (message as List<Object?>?)!; final List<String?>? arg_productIdentifiers = (args[0] as List<Object?>?)?.cast<String?>(); assert(arg_productIdentifiers != null, 'Argument for dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.startProductRequest was null, expected non-null List<String?>.'); try { final SKProductsResponseMessage output = await api.startProductRequest(arg_productIdentifiers!); return <Object?>[output]; } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.finishTransaction', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(__pigeon_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(__pigeon_channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.finishTransaction was null.'); final List<Object?> args = (message as List<Object?>?)!; final Map<String?, String?>? arg_finishMap = (args[0] as Map<Object?, Object?>?)?.cast<String?, String?>(); assert(arg_finishMap != null, 'Argument for dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.finishTransaction was null, expected non-null Map<String?, String?>.'); try { api.finishTransaction(arg_finishMap!); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.restoreTransactions', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(__pigeon_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(__pigeon_channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.restoreTransactions was null.'); final List<Object?> args = (message as List<Object?>?)!; final String? arg_applicationUserName = (args[0] as String?); try { api.restoreTransactions(arg_applicationUserName); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.presentCodeRedemptionSheet', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(__pigeon_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(__pigeon_channel, (Object? message) async { try { api.presentCodeRedemptionSheet(); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.retrieveReceiptData', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(__pigeon_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(__pigeon_channel, (Object? message) async { try { final String? output = api.retrieveReceiptData(); return <Object?>[output]; } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.refreshReceipt', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(__pigeon_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(__pigeon_channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.refreshReceipt was null.'); final List<Object?> args = (message as List<Object?>?)!; final Map<String?, Object?>? arg_receiptProperties = (args[0] as Map<Object?, Object?>?)?.cast<String?, Object?>(); try { await api.refreshReceipt(receiptProperties: arg_receiptProperties); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.startObservingPaymentQueue', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(__pigeon_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(__pigeon_channel, (Object? message) async { try { api.startObservingPaymentQueue(); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.stopObservingPaymentQueue', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(__pigeon_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(__pigeon_channel, (Object? message) async { try { api.stopObservingPaymentQueue(); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.registerPaymentQueueDelegate', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(__pigeon_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(__pigeon_channel, (Object? message) async { try { api.registerPaymentQueueDelegate(); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.removePaymentQueueDelegate', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(__pigeon_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(__pigeon_channel, (Object? message) async { try { api.removePaymentQueueDelegate(); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.in_app_purchase_storekit.InAppPurchaseAPI.showPriceConsentIfNeeded', pigeonChannelCodec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(__pigeon_channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(__pigeon_channel, (Object? message) async { try { api.showPriceConsentIfNeeded(); return wrapResponse(empty: true); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } } }
packages/packages/in_app_purchase/in_app_purchase_storekit/test/test_api.g.dart/0
{ "file_path": "packages/packages/in_app_purchase/in_app_purchase_storekit/test/test_api.g.dart", "repo_id": "packages", "token_count": 9577 }
1,007
// 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 Foundation public final class IosPlatformImagesPlugin: NSObject, FlutterPlugin, PlatformImagesApi { public static func register(with registrar: FlutterPluginRegistrar) { let instance = IosPlatformImagesPlugin() let messenger = registrar.messenger() PlatformImagesApiSetup.setUp(binaryMessenger: messenger, api: instance) } func loadImage(name: String) -> PlatformImageData? { guard let image = UIImage(named: name), let data = image.pngData() else { return nil } return PlatformImageData( data: FlutterStandardTypedData(bytes: data), scale: Double(image.scale)) } func resolveUrl(resourceName: String, extension: String?) throws -> String? { guard let url = Bundle.main.url( forResource: resourceName, withExtension: `extension`) else { return nil } return url.absoluteString } }
packages/packages/ios_platform_images/ios/Classes/IosPlatformImagesPlugin.swift/0
{ "file_path": "packages/packages/ios_platform_images/ios/Classes/IosPlatformImagesPlugin.swift", "repo_id": "packages", "token_count": 351 }
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. // Autogenerated from Pigeon (v11.0.0), do not edit directly. // See also: https://pub.dev/packages/pigeon package io.flutter.plugins.localauth; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.plugin.common.BasicMessageChannel; import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.MessageCodec; import io.flutter.plugin.common.StandardMessageCodec; import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; /** Generated class from Pigeon. */ @SuppressWarnings({"unused", "unchecked", "CodeBlock2Expr", "RedundantSuppression", "serial"}) public class Messages { /** Error class for passing custom error details to Flutter via a thrown PlatformException. */ public static class FlutterError extends RuntimeException { /** The error code. */ public final String code; /** The error details. Must be a datatype supported by the api codec. */ public final Object details; public FlutterError(@NonNull String code, @Nullable String message, @Nullable Object details) { super(message); this.code = code; this.details = details; } } @NonNull protected static ArrayList<Object> wrapError(@NonNull Throwable exception) { ArrayList<Object> errorList = new ArrayList<Object>(3); if (exception instanceof FlutterError) { FlutterError error = (FlutterError) exception; errorList.add(error.code); errorList.add(error.getMessage()); errorList.add(error.details); } else { errorList.add(exception.toString()); errorList.add(exception.getClass().getSimpleName()); errorList.add( "Cause: " + exception.getCause() + ", Stacktrace: " + Log.getStackTraceString(exception)); } return errorList; } /** Possible outcomes of an authentication attempt. */ public enum AuthResult { /** The user authenticated successfully. */ SUCCESS(0), /** The user failed to successfully authenticate. */ FAILURE(1), /** An authentication was already in progress. */ ERROR_ALREADY_IN_PROGRESS(2), /** There is no foreground activity. */ ERROR_NO_ACTIVITY(3), /** The foreground activity is not a FragmentActivity. */ ERROR_NOT_FRAGMENT_ACTIVITY(4), /** The authentication system was not available. */ ERROR_NOT_AVAILABLE(5), /** No biometrics are enrolled. */ ERROR_NOT_ENROLLED(6), /** The user is locked out temporarily due to too many failed attempts. */ ERROR_LOCKED_OUT_TEMPORARILY(7), /** The user is locked out until they log in another way due to too many failed attempts. */ ERROR_LOCKED_OUT_PERMANENTLY(8); final int index; private AuthResult(final int index) { this.index = index; } } /** Pigeon equivalent of the subset of BiometricType used by Android. */ public enum AuthClassification { WEAK(0), STRONG(1); final int index; private AuthClassification(final int index) { this.index = index; } } /** * Pigeon version of AndroidAuthStrings, plus the authorization reason. * * <p>See auth_messages_android.dart for details. * * <p>Generated class from Pigeon that represents data sent in messages. */ public static final class AuthStrings { private @NonNull String reason; public @NonNull String getReason() { return reason; } public void setReason(@NonNull String setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"reason\" is null."); } this.reason = setterArg; } private @NonNull String biometricHint; public @NonNull String getBiometricHint() { return biometricHint; } public void setBiometricHint(@NonNull String setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"biometricHint\" is null."); } this.biometricHint = setterArg; } private @NonNull String biometricNotRecognized; public @NonNull String getBiometricNotRecognized() { return biometricNotRecognized; } public void setBiometricNotRecognized(@NonNull String setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"biometricNotRecognized\" is null."); } this.biometricNotRecognized = setterArg; } private @NonNull String biometricRequiredTitle; public @NonNull String getBiometricRequiredTitle() { return biometricRequiredTitle; } public void setBiometricRequiredTitle(@NonNull String setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"biometricRequiredTitle\" is null."); } this.biometricRequiredTitle = setterArg; } private @NonNull String cancelButton; public @NonNull String getCancelButton() { return cancelButton; } public void setCancelButton(@NonNull String setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"cancelButton\" is null."); } this.cancelButton = setterArg; } private @NonNull String deviceCredentialsRequiredTitle; public @NonNull String getDeviceCredentialsRequiredTitle() { return deviceCredentialsRequiredTitle; } public void setDeviceCredentialsRequiredTitle(@NonNull String setterArg) { if (setterArg == null) { throw new IllegalStateException( "Nonnull field \"deviceCredentialsRequiredTitle\" is null."); } this.deviceCredentialsRequiredTitle = setterArg; } private @NonNull String deviceCredentialsSetupDescription; public @NonNull String getDeviceCredentialsSetupDescription() { return deviceCredentialsSetupDescription; } public void setDeviceCredentialsSetupDescription(@NonNull String setterArg) { if (setterArg == null) { throw new IllegalStateException( "Nonnull field \"deviceCredentialsSetupDescription\" is null."); } this.deviceCredentialsSetupDescription = setterArg; } private @NonNull String goToSettingsButton; public @NonNull String getGoToSettingsButton() { return goToSettingsButton; } public void setGoToSettingsButton(@NonNull String setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"goToSettingsButton\" is null."); } this.goToSettingsButton = setterArg; } private @NonNull String goToSettingsDescription; public @NonNull String getGoToSettingsDescription() { return goToSettingsDescription; } public void setGoToSettingsDescription(@NonNull String setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"goToSettingsDescription\" is null."); } this.goToSettingsDescription = setterArg; } private @NonNull String signInTitle; public @NonNull String getSignInTitle() { return signInTitle; } public void setSignInTitle(@NonNull String setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"signInTitle\" is null."); } this.signInTitle = setterArg; } /** Constructor is non-public to enforce null safety; use Builder. */ AuthStrings() {} public static final class Builder { private @Nullable String reason; public @NonNull Builder setReason(@NonNull String setterArg) { this.reason = setterArg; return this; } private @Nullable String biometricHint; public @NonNull Builder setBiometricHint(@NonNull String setterArg) { this.biometricHint = setterArg; return this; } private @Nullable String biometricNotRecognized; public @NonNull Builder setBiometricNotRecognized(@NonNull String setterArg) { this.biometricNotRecognized = setterArg; return this; } private @Nullable String biometricRequiredTitle; public @NonNull Builder setBiometricRequiredTitle(@NonNull String setterArg) { this.biometricRequiredTitle = setterArg; return this; } private @Nullable String cancelButton; public @NonNull Builder setCancelButton(@NonNull String setterArg) { this.cancelButton = setterArg; return this; } private @Nullable String deviceCredentialsRequiredTitle; public @NonNull Builder setDeviceCredentialsRequiredTitle(@NonNull String setterArg) { this.deviceCredentialsRequiredTitle = setterArg; return this; } private @Nullable String deviceCredentialsSetupDescription; public @NonNull Builder setDeviceCredentialsSetupDescription(@NonNull String setterArg) { this.deviceCredentialsSetupDescription = setterArg; return this; } private @Nullable String goToSettingsButton; public @NonNull Builder setGoToSettingsButton(@NonNull String setterArg) { this.goToSettingsButton = setterArg; return this; } private @Nullable String goToSettingsDescription; public @NonNull Builder setGoToSettingsDescription(@NonNull String setterArg) { this.goToSettingsDescription = setterArg; return this; } private @Nullable String signInTitle; public @NonNull Builder setSignInTitle(@NonNull String setterArg) { this.signInTitle = setterArg; return this; } public @NonNull AuthStrings build() { AuthStrings pigeonReturn = new AuthStrings(); pigeonReturn.setReason(reason); pigeonReturn.setBiometricHint(biometricHint); pigeonReturn.setBiometricNotRecognized(biometricNotRecognized); pigeonReturn.setBiometricRequiredTitle(biometricRequiredTitle); pigeonReturn.setCancelButton(cancelButton); pigeonReturn.setDeviceCredentialsRequiredTitle(deviceCredentialsRequiredTitle); pigeonReturn.setDeviceCredentialsSetupDescription(deviceCredentialsSetupDescription); pigeonReturn.setGoToSettingsButton(goToSettingsButton); pigeonReturn.setGoToSettingsDescription(goToSettingsDescription); pigeonReturn.setSignInTitle(signInTitle); return pigeonReturn; } } @NonNull ArrayList<Object> toList() { ArrayList<Object> toListResult = new ArrayList<Object>(10); toListResult.add(reason); toListResult.add(biometricHint); toListResult.add(biometricNotRecognized); toListResult.add(biometricRequiredTitle); toListResult.add(cancelButton); toListResult.add(deviceCredentialsRequiredTitle); toListResult.add(deviceCredentialsSetupDescription); toListResult.add(goToSettingsButton); toListResult.add(goToSettingsDescription); toListResult.add(signInTitle); return toListResult; } static @NonNull AuthStrings fromList(@NonNull ArrayList<Object> list) { AuthStrings pigeonResult = new AuthStrings(); Object reason = list.get(0); pigeonResult.setReason((String) reason); Object biometricHint = list.get(1); pigeonResult.setBiometricHint((String) biometricHint); Object biometricNotRecognized = list.get(2); pigeonResult.setBiometricNotRecognized((String) biometricNotRecognized); Object biometricRequiredTitle = list.get(3); pigeonResult.setBiometricRequiredTitle((String) biometricRequiredTitle); Object cancelButton = list.get(4); pigeonResult.setCancelButton((String) cancelButton); Object deviceCredentialsRequiredTitle = list.get(5); pigeonResult.setDeviceCredentialsRequiredTitle((String) deviceCredentialsRequiredTitle); Object deviceCredentialsSetupDescription = list.get(6); pigeonResult.setDeviceCredentialsSetupDescription((String) deviceCredentialsSetupDescription); Object goToSettingsButton = list.get(7); pigeonResult.setGoToSettingsButton((String) goToSettingsButton); Object goToSettingsDescription = list.get(8); pigeonResult.setGoToSettingsDescription((String) goToSettingsDescription); Object signInTitle = list.get(9); pigeonResult.setSignInTitle((String) signInTitle); return pigeonResult; } } /** Generated class from Pigeon that represents data sent in messages. */ public static final class AuthOptions { private @NonNull Boolean biometricOnly; public @NonNull Boolean getBiometricOnly() { return biometricOnly; } public void setBiometricOnly(@NonNull Boolean setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"biometricOnly\" is null."); } this.biometricOnly = setterArg; } private @NonNull Boolean sensitiveTransaction; public @NonNull Boolean getSensitiveTransaction() { return sensitiveTransaction; } public void setSensitiveTransaction(@NonNull Boolean setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"sensitiveTransaction\" is null."); } this.sensitiveTransaction = setterArg; } private @NonNull Boolean sticky; public @NonNull Boolean getSticky() { return sticky; } public void setSticky(@NonNull Boolean setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"sticky\" is null."); } this.sticky = setterArg; } private @NonNull Boolean useErrorDialgs; public @NonNull Boolean getUseErrorDialgs() { return useErrorDialgs; } public void setUseErrorDialgs(@NonNull Boolean setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"useErrorDialgs\" is null."); } this.useErrorDialgs = setterArg; } /** Constructor is non-public to enforce null safety; use Builder. */ AuthOptions() {} public static final class Builder { private @Nullable Boolean biometricOnly; public @NonNull Builder setBiometricOnly(@NonNull Boolean setterArg) { this.biometricOnly = setterArg; return this; } private @Nullable Boolean sensitiveTransaction; public @NonNull Builder setSensitiveTransaction(@NonNull Boolean setterArg) { this.sensitiveTransaction = setterArg; return this; } private @Nullable Boolean sticky; public @NonNull Builder setSticky(@NonNull Boolean setterArg) { this.sticky = setterArg; return this; } private @Nullable Boolean useErrorDialgs; public @NonNull Builder setUseErrorDialgs(@NonNull Boolean setterArg) { this.useErrorDialgs = setterArg; return this; } public @NonNull AuthOptions build() { AuthOptions pigeonReturn = new AuthOptions(); pigeonReturn.setBiometricOnly(biometricOnly); pigeonReturn.setSensitiveTransaction(sensitiveTransaction); pigeonReturn.setSticky(sticky); pigeonReturn.setUseErrorDialgs(useErrorDialgs); return pigeonReturn; } } @NonNull ArrayList<Object> toList() { ArrayList<Object> toListResult = new ArrayList<Object>(4); toListResult.add(biometricOnly); toListResult.add(sensitiveTransaction); toListResult.add(sticky); toListResult.add(useErrorDialgs); return toListResult; } static @NonNull AuthOptions fromList(@NonNull ArrayList<Object> list) { AuthOptions pigeonResult = new AuthOptions(); Object biometricOnly = list.get(0); pigeonResult.setBiometricOnly((Boolean) biometricOnly); Object sensitiveTransaction = list.get(1); pigeonResult.setSensitiveTransaction((Boolean) sensitiveTransaction); Object sticky = list.get(2); pigeonResult.setSticky((Boolean) sticky); Object useErrorDialgs = list.get(3); pigeonResult.setUseErrorDialgs((Boolean) useErrorDialgs); return pigeonResult; } } /** Generated class from Pigeon that represents data sent in messages. */ public static final class AuthClassificationWrapper { private @NonNull AuthClassification value; public @NonNull AuthClassification getValue() { return value; } public void setValue(@NonNull AuthClassification setterArg) { if (setterArg == null) { throw new IllegalStateException("Nonnull field \"value\" is null."); } this.value = setterArg; } /** Constructor is non-public to enforce null safety; use Builder. */ AuthClassificationWrapper() {} public static final class Builder { private @Nullable AuthClassification value; public @NonNull Builder setValue(@NonNull AuthClassification setterArg) { this.value = setterArg; return this; } public @NonNull AuthClassificationWrapper build() { AuthClassificationWrapper pigeonReturn = new AuthClassificationWrapper(); pigeonReturn.setValue(value); return pigeonReturn; } } @NonNull ArrayList<Object> toList() { ArrayList<Object> toListResult = new ArrayList<Object>(1); toListResult.add(value == null ? null : value.index); return toListResult; } static @NonNull AuthClassificationWrapper fromList(@NonNull ArrayList<Object> list) { AuthClassificationWrapper pigeonResult = new AuthClassificationWrapper(); Object value = list.get(0); pigeonResult.setValue(AuthClassification.values()[(int) value]); return pigeonResult; } } public interface Result<T> { @SuppressWarnings("UnknownNullness") void success(T result); void error(@NonNull Throwable error); } private static class LocalAuthApiCodec extends StandardMessageCodec { public static final LocalAuthApiCodec INSTANCE = new LocalAuthApiCodec(); private LocalAuthApiCodec() {} @Override protected Object readValueOfType(byte type, @NonNull ByteBuffer buffer) { switch (type) { case (byte) 128: return AuthClassificationWrapper.fromList((ArrayList<Object>) readValue(buffer)); case (byte) 129: return AuthOptions.fromList((ArrayList<Object>) readValue(buffer)); case (byte) 130: return AuthStrings.fromList((ArrayList<Object>) readValue(buffer)); default: return super.readValueOfType(type, buffer); } } @Override protected void writeValue(@NonNull ByteArrayOutputStream stream, Object value) { if (value instanceof AuthClassificationWrapper) { stream.write(128); writeValue(stream, ((AuthClassificationWrapper) value).toList()); } else if (value instanceof AuthOptions) { stream.write(129); writeValue(stream, ((AuthOptions) value).toList()); } else if (value instanceof AuthStrings) { stream.write(130); writeValue(stream, ((AuthStrings) value).toList()); } else { super.writeValue(stream, value); } } } /** Generated interface from Pigeon that represents a handler of messages from Flutter. */ public interface LocalAuthApi { /** Returns true if this device supports authentication. */ @NonNull Boolean isDeviceSupported(); /** * Returns true if this device can support biometric authentication, whether any biometrics are * enrolled or not. */ @NonNull Boolean deviceCanSupportBiometrics(); /** * Cancels any in-progress authentication. * * <p>Returns true only if authentication was in progress, and was successfully cancelled. */ @NonNull Boolean stopAuthentication(); /** * Returns the biometric types that are enrolled, and can thus be used without additional setup. */ @NonNull List<AuthClassificationWrapper> getEnrolledBiometrics(); /** * Attempts to authenticate the user with the provided [options], and using [strings] for any * UI. */ void authenticate( @NonNull AuthOptions options, @NonNull AuthStrings strings, @NonNull Result<AuthResult> result); /** The codec used by LocalAuthApi. */ static @NonNull MessageCodec<Object> getCodec() { return LocalAuthApiCodec.INSTANCE; } /** Sets up an instance of `LocalAuthApi` to handle messages through the `binaryMessenger`. */ static void setup(@NonNull BinaryMessenger binaryMessenger, @Nullable LocalAuthApi api) { { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.local_auth_android.LocalAuthApi.isDeviceSupported", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); try { Boolean output = api.isDeviceSupported(); wrapped.add(0, output); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.local_auth_android.LocalAuthApi.deviceCanSupportBiometrics", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); try { Boolean output = api.deviceCanSupportBiometrics(); wrapped.add(0, output); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.local_auth_android.LocalAuthApi.stopAuthentication", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); try { Boolean output = api.stopAuthentication(); wrapped.add(0, output); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.local_auth_android.LocalAuthApi.getEnrolledBiometrics", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); try { List<AuthClassificationWrapper> output = api.getEnrolledBiometrics(); wrapped.add(0, output); } catch (Throwable exception) { ArrayList<Object> wrappedError = wrapError(exception); wrapped = wrappedError; } reply.reply(wrapped); }); } else { channel.setMessageHandler(null); } } { BasicMessageChannel<Object> channel = new BasicMessageChannel<>( binaryMessenger, "dev.flutter.pigeon.local_auth_android.LocalAuthApi.authenticate", getCodec()); if (api != null) { channel.setMessageHandler( (message, reply) -> { ArrayList<Object> wrapped = new ArrayList<Object>(); ArrayList<Object> args = (ArrayList<Object>) message; AuthOptions optionsArg = (AuthOptions) args.get(0); AuthStrings stringsArg = (AuthStrings) args.get(1); Result<AuthResult> resultCallback = new Result<AuthResult>() { public void success(AuthResult result) { wrapped.add(0, result.index); reply.reply(wrapped); } public void error(Throwable error) { ArrayList<Object> wrappedError = wrapError(error); reply.reply(wrappedError); } }; api.authenticate(optionsArg, stringsArg, resultCallback); }); } else { channel.setMessageHandler(null); } } } } }
packages/packages/local_auth/local_auth_android/android/src/main/java/io/flutter/plugins/localauth/Messages.java/0
{ "file_path": "packages/packages/local_auth/local_auth_android/android/src/main/java/io/flutter/plugins/localauth/Messages.java", "repo_id": "packages", "token_count": 9844 }
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:pigeon/pigeon.dart'; @ConfigurePigeon(PigeonOptions( dartOut: 'lib/src/messages.g.dart', javaOut: 'android/src/main/java/io/flutter/plugins/localauth/Messages.java', javaOptions: JavaOptions(package: 'io.flutter.plugins.localauth'), copyrightHeader: 'pigeons/copyright.txt', )) /// Pigeon version of AndroidAuthStrings, plus the authorization reason. /// /// See auth_messages_android.dart for details. class AuthStrings { /// Constructs a new instance. const AuthStrings({ required this.reason, required this.biometricHint, required this.biometricNotRecognized, required this.biometricRequiredTitle, required this.cancelButton, required this.deviceCredentialsRequiredTitle, required this.deviceCredentialsSetupDescription, required this.goToSettingsButton, required this.goToSettingsDescription, required this.signInTitle, }); final String reason; final String biometricHint; final String biometricNotRecognized; final String biometricRequiredTitle; final String cancelButton; final String deviceCredentialsRequiredTitle; final String deviceCredentialsSetupDescription; final String goToSettingsButton; final String goToSettingsDescription; final String signInTitle; } /// Possible outcomes of an authentication attempt. enum AuthResult { /// The user authenticated successfully. success, /// The user failed to successfully authenticate. failure, /// An authentication was already in progress. errorAlreadyInProgress, /// There is no foreground activity. errorNoActivity, /// The foreground activity is not a FragmentActivity. errorNotFragmentActivity, /// The authentication system was not available. errorNotAvailable, /// No biometrics are enrolled. errorNotEnrolled, /// The user is locked out temporarily due to too many failed attempts. errorLockedOutTemporarily, /// The user is locked out until they log in another way due to too many /// failed attempts. errorLockedOutPermanently, } class AuthOptions { AuthOptions( {required this.biometricOnly, required this.sensitiveTransaction, required this.sticky, required this.useErrorDialgs}); final bool biometricOnly; final bool sensitiveTransaction; final bool sticky; final bool useErrorDialgs; } /// Pigeon equivalent of the subset of BiometricType used by Android. enum AuthClassification { weak, strong } // TODO(stuartmorgan): Remove this when // https://github.com/flutter/flutter/issues/87307 is implemented. class AuthClassificationWrapper { AuthClassificationWrapper({required this.value}); final AuthClassification value; } @HostApi() abstract class LocalAuthApi { /// Returns true if this device supports authentication. bool isDeviceSupported(); /// Returns true if this device can support biometric authentication, whether /// any biometrics are enrolled or not. bool deviceCanSupportBiometrics(); /// Cancels any in-progress authentication. /// /// Returns true only if authentication was in progress, and was successfully /// cancelled. bool stopAuthentication(); /// Returns the biometric types that are enrolled, and can thus be used /// without additional setup. List<AuthClassificationWrapper> getEnrolledBiometrics(); /// Attempts to authenticate the user with the provided [options], and using /// [strings] for any UI. @async AuthResult authenticate(AuthOptions options, AuthStrings strings); }
packages/packages/local_auth/local_auth_android/pigeons/messages.dart/0
{ "file_path": "packages/packages/local_auth/local_auth_android/pigeons/messages.dart", "repo_id": "packages", "token_count": 1013 }
1,010
# local_auth_platform_interface A common platform interface for the [`local_auth`][1] plugin. This interface allows platform-specific implementations of the `local_auth` plugin, as well as the plugin itself, to ensure they are supporting the same interface. # Usage To implement a new platform-specific implementation of `local_auth`, extend [`LocalAuthPlatform`][2] with an implementation that performs the platform-specific behavior, and when you register your plugin, set the default `LocalAuthPlatform` by calling `LocalAuthPlatform.instance = MyLocalAuthPlatform()`. # 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]: ../local_auth [2]: lib/local_auth_platform_interface.dart
packages/packages/local_auth/local_auth_platform_interface/README.md/0
{ "file_path": "packages/packages/local_auth/local_auth_platform_interface/README.md", "repo_id": "packages", "token_count": 236 }
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. // Autogenerated from Pigeon (v10.1.2), do not edit directly. // See also: https://pub.dev/packages/pigeon #undef _HAS_EXCEPTIONS #include "messages.g.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 local_auth_windows { using flutter::BasicMessageChannel; using flutter::CustomEncodableValue; using flutter::EncodableList; using flutter::EncodableMap; using flutter::EncodableValue; /// The codec used by LocalAuthApi. const flutter::StandardMessageCodec& LocalAuthApi::GetCodec() { return flutter::StandardMessageCodec::GetInstance( &flutter::StandardCodecSerializer::GetInstance()); } // Sets up an instance of `LocalAuthApi` to handle messages through the // `binary_messenger`. void LocalAuthApi::SetUp(flutter::BinaryMessenger* binary_messenger, LocalAuthApi* api) { { auto channel = std::make_unique<BasicMessageChannel<>>( binary_messenger, "dev.flutter.pigeon.LocalAuthApi.isDeviceSupported", &GetCodec()); if (api != nullptr) { channel->SetMessageHandler( [api](const EncodableValue& message, const flutter::MessageReply<EncodableValue>& reply) { try { api->IsDeviceSupported([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); } } { auto channel = std::make_unique<BasicMessageChannel<>>( binary_messenger, "dev.flutter.pigeon.LocalAuthApi.authenticate", &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_localized_reason_arg = args.at(0); if (encodable_localized_reason_arg.IsNull()) { reply(WrapError("localized_reason_arg unexpectedly null.")); return; } const auto& localized_reason_arg = std::get<std::string>(encodable_localized_reason_arg); api->Authenticate( localized_reason_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); } } } EncodableValue LocalAuthApi::WrapError(std::string_view error_message) { return EncodableValue( EncodableList{EncodableValue(std::string(error_message)), EncodableValue("Error"), EncodableValue()}); } EncodableValue LocalAuthApi::WrapError(const FlutterError& error) { return EncodableValue(EncodableList{EncodableValue(error.code()), EncodableValue(error.message()), error.details()}); } } // namespace local_auth_windows
packages/packages/local_auth/local_auth_windows/windows/messages.g.cpp/0
{ "file_path": "packages/packages/local_auth/local_auth_windows/windows/messages.g.cpp", "repo_id": "packages", "token_count": 1935 }
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. // ignore_for_file: avoid_dynamic_calls import 'dart:convert'; import 'package:gcloud/storage.dart'; import 'package:googleapis/storage/v1.dart' show DetailedApiRequestError, StorageApi; import 'package:googleapis_auth/auth_io.dart'; import 'common.dart'; import 'constants.dart'; import 'gcs_lock.dart'; /// A [MetricPoint] modeled after the format that Skia Perf expects. /// /// Skia Perf Format is a JSON file that looks like: /// ```json /// { /// "gitHash": "fe4a4029a080bc955e9588d05a6cd9eb490845d4", /// "key": { /// "arch": "x86", /// "gpu": "GTX660", /// "model": "ShuttleA", /// "os": "Ubuntu12" /// }, /// "results": { /// "ChunkAlloc_PushPop_640_480": { /// "nonrendering": { /// "min_ms": 0.01485466666666667, /// "options": { /// "source_type": "bench" /// } /// } /// }, /// "DeferredSurfaceCopy_discardable_640_480": { /// "565": { /// "min_ms": 2.215988, /// "options": { /// "source_type": "bench" /// } /// } /// } /// } /// } /// } /// ``` class SkiaPerfPoint extends MetricPoint { SkiaPerfPoint._(this.githubRepo, this.gitHash, this.testName, this.subResult, double? value, this._options, this.jsonUrl) : assert(_options[kGithubRepoKey] == null), assert(_options[kGitRevisionKey] == null), assert(_options[kNameKey] == null), super( value, <String, String?>{} ..addAll(_options) ..addAll(<String, String?>{ kGithubRepoKey: githubRepo, kGitRevisionKey: gitHash, kNameKey: testName, kSubResultKey: subResult, }), ) { assert(tags[kGithubRepoKey] != null); assert(tags[kGitRevisionKey] != null); assert(tags[kNameKey] != null); } /// Construct [SkiaPerfPoint] from a well-formed [MetricPoint]. /// /// The [MetricPoint] must have [kGithubRepoKey], [kGitRevisionKey], /// [kNameKey] in its tags for this to be successful. /// /// If the [MetricPoint] has a tag 'date', that tag will be removed so Skia /// perf can plot multiple metrics with different date as a single trace. /// Skia perf will use the git revision's date instead of this date tag in /// the time axis. factory SkiaPerfPoint.fromPoint(MetricPoint p) { final String? githubRepo = p.tags[kGithubRepoKey]; final String? gitHash = p.tags[kGitRevisionKey]; final String? name = p.tags[kNameKey]; if (githubRepo == null || gitHash == null || name == null) { throw StateError( '$kGithubRepoKey, $kGitRevisionKey, $kNameKey must be set in' ' the tags of $p.'); } final String subResult = p.tags[kSubResultKey] ?? kSkiaPerfValueKey; final Map<String, String> options = <String, String>{}..addEntries( p.tags.entries.where( (MapEntry<String, dynamic> entry) => entry.key != kGithubRepoKey && entry.key != kGitRevisionKey && entry.key != kNameKey && entry.key != kSubResultKey && // https://github.com/google/benchmark automatically generates a // 'date' field. If it's included in options, the Skia perf won't // be able to connect different points in a single trace because // the date is always different. entry.key != 'date', ), ); return SkiaPerfPoint._( githubRepo, gitHash, name, subResult, p.value, options, null); } /// In the format of '<owner>/<name>' such as 'flutter/flutter' or /// 'flutter/engine'. final String githubRepo; /// SHA such as 'ad20d368ffa09559754e4b2b5c12951341ca3b2d' final String? gitHash; /// For Flutter devicelab, this is the task name (e.g., /// 'flutter_gallery__transition_perf'); for Google benchmark, this is the /// benchmark name (e.g., 'BM_ShellShutdown'). /// /// In Skia perf web dashboard, this value can be queried and filtered by /// "test". final String testName; /// The name of "subResult" comes from the special treatment of "sub_result" /// in SkiaPerf. If not provided, its value will be set to kSkiaPerfValueKey. /// /// When Google benchmarks are converted to SkiaPerfPoint, this subResult /// could be "cpu_time" or "real_time". /// /// When devicelab benchmarks are converted to SkiaPerfPoint, this subResult /// is often the metric name such as "average_frame_build_time_millis" whereas /// the [testName] is the benchmark or task name such as /// "flutter_gallery__transition_perf". final String subResult; /// The url to the Skia perf json file in the Google Cloud Storage bucket. /// /// This can be null if the point has been stored in the bucket yet. final String? jsonUrl; Map<String, dynamic> _toSubResultJson() { return <String, dynamic>{ subResult: value, kSkiaPerfOptionsKey: _options, }; } /// Convert a list of SkiaPoints with the same git repo and git revision into /// a single json file in the Skia perf format. /// /// The list must be non-empty. static Map<String, dynamic> toSkiaPerfJson(List<SkiaPerfPoint> points) { assert(points.isNotEmpty); assert(() { for (final SkiaPerfPoint p in points) { if (p.githubRepo != points[0].githubRepo || p.gitHash != points[0].gitHash) { return false; } } return true; }(), 'All points must have same githubRepo and gitHash'); final Map<String, dynamic> results = <String, dynamic>{}; for (final SkiaPerfPoint p in points) { final Map<String, dynamic> subResultJson = p._toSubResultJson(); if (results[p.testName] == null) { results[p.testName] = <String, dynamic>{ kSkiaPerfDefaultConfig: subResultJson, }; } else { // Flutter currently doesn't support having the same name but different // options/configurations. If this actually happens in the future, we // probably can use different values of config (currently there's only // one kSkiaPerfDefaultConfig) to resolve the conflict. assert(results[p.testName][kSkiaPerfDefaultConfig][kSkiaPerfOptionsKey] .toString() == subResultJson[kSkiaPerfOptionsKey].toString()); assert( results[p.testName][kSkiaPerfDefaultConfig][p.subResult] == null); results[p.testName][kSkiaPerfDefaultConfig][p.subResult] = p.value; } } return <String, dynamic>{ kSkiaPerfGitHashKey: points[0].gitHash, kSkiaPerfResultsKey: results, }; } // Equivalent to tags without git repo, git hash, and name because those two // are already stored somewhere else. final Map<String, String> _options; } /// Handle writing and updates of Skia perf GCS buckets. class SkiaPerfGcsAdaptor { /// Construct the adaptor given the associated GCS bucket where the data is /// read from and written to. SkiaPerfGcsAdaptor(this._gcsBucket); /// Used by Skia to differentiate json file format versions. static const int version = 1; /// Write a list of SkiaPerfPoint into a GCS file with name `objectName` in /// the proper json format that's understandable by Skia perf services. /// /// The `objectName` must be a properly formatted string returned by /// [computeObjectName]. /// /// The read may retry multiple times if transient network errors with code /// 504 happens. Future<void> writePoints( String objectName, List<SkiaPerfPoint> points) async { final String jsonString = jsonEncode(SkiaPerfPoint.toSkiaPerfJson(points)); final List<int> content = utf8.encode(jsonString); // Retry multiple times as GCS may return 504 timeout. for (int retry = 0; retry < 5; retry += 1) { try { await _gcsBucket.writeBytes(objectName, content); return; } catch (e) { if (e is DetailedApiRequestError && e.status == 504) { continue; } rethrow; } } // Retry one last time and let the exception go through. await _gcsBucket.writeBytes(objectName, content); } /// Read a list of `SkiaPerfPoint` that have been previously written to the /// GCS file with name `objectName`. /// /// The Github repo and revision of those points will be inferred from the /// `objectName`. /// /// Return an empty list if the object does not exist in the GCS bucket. /// /// The read may retry multiple times if transient network errors with code /// 504 happens. Future<List<SkiaPerfPoint>> readPoints(String objectName) async { // Retry multiple times as GCS may return 504 timeout. for (int retry = 0; retry < 5; retry += 1) { try { return await _readPointsWithoutRetry(objectName); } catch (e) { if (e is DetailedApiRequestError && e.status == 504) { continue; } rethrow; } } // Retry one last time and let the exception go through. return _readPointsWithoutRetry(objectName); } Future<List<SkiaPerfPoint>> _readPointsWithoutRetry(String objectName) async { ObjectInfo? info; try { info = await _gcsBucket.info(objectName); } catch (e) { if (e.toString().contains('No such object')) { return <SkiaPerfPoint>[]; } else { rethrow; } } final Stream<List<int>> stream = _gcsBucket.read(objectName); final Stream<int> byteStream = stream.expand((List<int> x) => x); final Map<String, dynamic> decodedJson = jsonDecode(utf8.decode(await byteStream.toList())) as Map<String, dynamic>; final List<SkiaPerfPoint> points = <SkiaPerfPoint>[]; final String firstGcsNameComponent = objectName.split('/')[0]; _populateGcsNameToGithubRepoMapIfNeeded(); final String githubRepo = _gcsNameToGithubRepo[firstGcsNameComponent]!; final String? gitHash = decodedJson[kSkiaPerfGitHashKey] as String?; final Map<String, dynamic> results = decodedJson[kSkiaPerfResultsKey] as Map<String, dynamic>; for (final String name in results.keys) { final Map<String, dynamic> subResultMap = results[name][kSkiaPerfDefaultConfig] as Map<String, dynamic>; for (final String subResult in subResultMap.keys.where((String s) => s != kSkiaPerfOptionsKey)) { points.add(SkiaPerfPoint._( githubRepo, gitHash, name, subResult, subResultMap[subResult] as double?, (subResultMap[kSkiaPerfOptionsKey] as Map<String, dynamic>) .cast<String, String>(), info.downloadLink.toString(), )); } } return points; } /// Compute the GCS file name that's used to store metrics for a given commit /// (git revision). /// /// Skia perf needs all directory names to be well formatted. The final name /// of the json file can be arbitrary, and multiple json files can be put /// in that leaf directory. We are using multiple json files divided by test /// names to scale up the system to avoid too many writes competing for /// the same json file. static Future<String> computeObjectName(String githubRepo, String? revision, DateTime commitTime, String taskName) async { assert(_githubRepoToGcsName[githubRepo] != null); final String? topComponent = _githubRepoToGcsName[githubRepo]; // [commitTime] is not guranteed to be UTC. Ensure it is so all results // pushed to GCS are the same timezone. final DateTime commitUtcTime = commitTime.toUtc(); final String month = commitUtcTime.month.toString().padLeft(2, '0'); final String day = commitUtcTime.day.toString().padLeft(2, '0'); final String hour = commitUtcTime.hour.toString().padLeft(2, '0'); final String dateComponents = '${commitUtcTime.year}/$month/$day/$hour'; return '$topComponent/$dateComponents/$revision/${taskName}_values.json'; } static final Map<String, String> _githubRepoToGcsName = <String, String>{ kFlutterFrameworkRepo: 'flutter-flutter', kFlutterEngineRepo: 'flutter-engine', }; static final Map<String?, String> _gcsNameToGithubRepo = <String?, String>{}; static void _populateGcsNameToGithubRepoMapIfNeeded() { if (_gcsNameToGithubRepo.isEmpty) { for (final String repo in _githubRepoToGcsName.keys) { final String? gcsName = _githubRepoToGcsName[repo]; assert(_gcsNameToGithubRepo[gcsName] == null); _gcsNameToGithubRepo[gcsName] = repo; } } } final Bucket _gcsBucket; } /// A [MetricDestination] that conforms to Skia Perf's protocols. class SkiaPerfDestination extends MetricDestination { /// Creates a new [SkiaPerfDestination]. SkiaPerfDestination(this._gcs, this._lock); /// Create from a full credentials json (of a service account). static Future<SkiaPerfDestination> makeFromGcpCredentials( Map<String, dynamic> credentialsJson, {bool isTesting = false}) async { final AutoRefreshingAuthClient client = await clientViaServiceAccount( ServiceAccountCredentials.fromJson(credentialsJson), Storage.SCOPES); return make( client, credentialsJson[kProjectId] as String, isTesting: isTesting, ); } /// Create from an access token and its project id. static Future<SkiaPerfDestination> makeFromAccessToken( String token, String projectId, {bool isTesting = false}) async { final AuthClient client = authClientFromAccessToken(token, Storage.SCOPES); return make(client, projectId, isTesting: isTesting); } /// Create from an [AuthClient] and a GCP project id. /// /// [AuthClient] can be obtained from functions like `clientViaUserConsent`. static Future<SkiaPerfDestination> make(AuthClient client, String projectId, {bool isTesting = false}) async { final Storage storage = Storage(client, projectId); final String bucketName = isTesting ? kTestBucketName : kBucketName; if (!await storage.bucketExists(bucketName)) { throw StateError('Bucket $bucketName does not exist.'); } final SkiaPerfGcsAdaptor adaptor = SkiaPerfGcsAdaptor(storage.bucket(bucketName)); final GcsLock lock = GcsLock(StorageApi(client), bucketName); return SkiaPerfDestination(adaptor, lock); } @override Future<void> update( List<MetricPoint> points, DateTime commitTime, String taskName) async { // 1st, create a map based on git repo, git revision, and point id. Git repo // and git revision are the top level components of the Skia perf GCS object // name. final Map<String, Map<String?, Map<String, SkiaPerfPoint>>> pointMap = <String, Map<String, Map<String, SkiaPerfPoint>>>{}; for (final SkiaPerfPoint p in points.map((MetricPoint x) => SkiaPerfPoint.fromPoint(x))) { pointMap[p.githubRepo] ??= <String, Map<String, SkiaPerfPoint>>{}; pointMap[p.githubRepo]![p.gitHash] ??= <String, SkiaPerfPoint>{}; pointMap[p.githubRepo]![p.gitHash]![p.id] = p; } // All created locks must be released before returning final List<Future<void>> lockFutures = <Future<void>>[]; // 2nd, read existing points from the gcs object and update with new ones. for (final String repo in pointMap.keys) { for (final String? revision in pointMap[repo]!.keys) { final String objectName = await SkiaPerfGcsAdaptor.computeObjectName( repo, revision, commitTime, taskName); final Map<String, SkiaPerfPoint>? newPoints = pointMap[repo]![revision]; // Too many bots writing the metrics of a git revision into a single json // file will cause high contention on the lock. We use multiple // json files according to task names. Skia perf read all json files in // the directory so one can use arbitrary names for those sharded json // file names. lockFutures.add( _lock!.protectedRun('$objectName.lock', () async { final List<SkiaPerfPoint> oldPoints = await _gcs.readPoints(objectName); for (final SkiaPerfPoint p in oldPoints) { if (newPoints![p.id] == null) { newPoints[p.id] = p; } } await _gcs.writePoints(objectName, newPoints!.values.toList()); }), ); } } await Future.wait(lockFutures); } final SkiaPerfGcsAdaptor _gcs; late final GcsLock? _lock; }
packages/packages/metrics_center/lib/src/skiaperf.dart/0
{ "file_path": "packages/packages/metrics_center/lib/src/skiaperf.dart", "repo_id": "packages", "token_count": 6545 }
1,013
// 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. // Example script to illustrate how to use the mdns package to discover the port // of a Dart observatory over mDNS. // ignore_for_file: avoid_print import 'package:multicast_dns/multicast_dns.dart'; Future<void> main() async { // Parse the command line arguments. const String name = '_dartobservatory._tcp.local'; final MDnsClient client = MDnsClient(); // Start the client with default options. await client.start(); // Get the PTR record for the service. await for (final PtrResourceRecord ptr in client .lookup<PtrResourceRecord>(ResourceRecordQuery.serverPointer(name))) { // Use the domainName from the PTR record to get the SRV record, // which will have the port and local hostname. // Note that duplicate messages may come through, especially if any // other mDNS queries are running elsewhere on the machine. await for (final SrvResourceRecord srv in client.lookup<SrvResourceRecord>( ResourceRecordQuery.service(ptr.domainName))) { // Domain name will be something like "[email protected]._dartobservatory._tcp.local" final String bundleId = ptr.domainName; //.substring(0, ptr.domainName.indexOf('@')); print('Dart observatory instance found at ' '${srv.target}:${srv.port} for "$bundleId".'); } } client.stop(); print('Done.'); }
packages/packages/multicast_dns/example/main.dart/0
{ "file_path": "packages/packages/multicast_dns/example/main.dart", "repo_id": "packages", "token_count": 491 }
1,014
## NEXT * Updates minimum supported SDK version to Flutter 3.13/Dart 3.1. ## 0.3.3+3 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. * Aligns Dart and Flutter SDK constraints. ## 0.3.3+2 * Ignores lint warnings from new changes in Flutter master. * Suppresses deprecation warnings for changes to Flutter master. * Fixes lint warnings. ## 0.3.3+1 * Migrates from `ui.hash*` to `Object.hash*`. ## 0.3.3 * Avoids dynamic calls in equality checks. ## 0.3.2 * Fix typos * Fix `unnecessary_import` lint errors. ## 0.3.1 * Add PaletteGenerator.fromByteData to allow creating palette from image byte data. ## 0.3.0 * Migrated to null safety. ## 0.2.4+1 * Removed a `dart:async` import that isn't required for \>=Dart 2.1. ## 0.2.4 * Fix PaletteGenerator.fromImageProvider region not scaled to fit image size. ## 0.2.3 * Bumped minimum Flutter version to 1.15.21 to pick up Diagnosticable as a mixin and remove DiagnosticableMixin. ## 0.2.2 * Bumped minimum Flutter version to 1.6.7 to pick up DiagnosticableMixin. ## 0.2.1 * PaletteGenerator: performance improvements. ## 0.2.0 * Updated code to be compatible with Flutter breaking change. ## 0.1.1 * Fixed a problem with a listener that wasn't being unregistered properly. ## 0.1.0 * Initial Open Source release.
packages/packages/palette_generator/CHANGELOG.md/0
{ "file_path": "packages/packages/palette_generator/CHANGELOG.md", "repo_id": "packages", "token_count": 466 }
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 'dart:io' show Directory; import 'package:flutter/foundation.dart' show visibleForTesting; import 'package:path_provider_platform_interface/path_provider_platform_interface.dart'; export 'package:path_provider_platform_interface/path_provider_platform_interface.dart' show StorageDirectory; @visibleForTesting @Deprecated('This is no longer necessary, and is now a no-op') set disablePathProviderPlatformOverride(bool override) {} /// An exception thrown when a directory that should always be available on /// the current platform cannot be obtained. class MissingPlatformDirectoryException implements Exception { /// Creates a new exception MissingPlatformDirectoryException(this.message, {this.details}); /// The explanation of the exception. final String message; /// Added details, if any. /// /// E.g., an error object from the platform implementation. final Object? details; @override String toString() { final String detailsAddition = details == null ? '' : ': $details'; return 'MissingPlatformDirectoryException($message)$detailsAddition'; } } PathProviderPlatform get _platform => PathProviderPlatform.instance; /// Path to the temporary directory on the device that is not backed up and is /// suitable for storing caches of downloaded files. /// /// Files in this directory may be cleared at any time. This does *not* return /// a new temporary directory. Instead, the caller is responsible for creating /// (and cleaning up) files or directories within this directory. This /// directory is scoped to the calling application. /// /// Example implementations: /// - `NSCachesDirectory` on iOS and macOS. /// - `Context.getCacheDir` on Android. /// /// Throws a [MissingPlatformDirectoryException] if the system is unable to /// provide the directory. Future<Directory> getTemporaryDirectory() async { final String? path = await _platform.getTemporaryPath(); if (path == null) { throw MissingPlatformDirectoryException( 'Unable to get temporary directory'); } return Directory(path); } /// Path to a directory where the application may place application support /// files. /// /// If this directory does not exist, it is created automatically. /// /// Use this for files you don’t want exposed to the user. Your app should not /// use this directory for user data files. /// /// Example implementations: /// - `NSApplicationSupportDirectory` on iOS and macOS. /// - The Flutter engine's `PathUtils.getFilesDir` API on Android. /// /// Throws a [MissingPlatformDirectoryException] if the system is unable to /// provide the directory. Future<Directory> getApplicationSupportDirectory() async { final String? path = await _platform.getApplicationSupportPath(); if (path == null) { throw MissingPlatformDirectoryException( 'Unable to get application support directory'); } return Directory(path); } /// Path to the directory where application can store files that are persistent, /// backed up, and not visible to the user, such as sqlite.db. /// /// Example implementations: /// - `NSApplicationSupportDirectory` on iOS and macOS. /// /// Throws an [UnsupportedError] if this is not supported on the current /// platform. For example, this is unlikely to ever be supported on Android, /// as no equivalent path exists. /// /// Throws a [MissingPlatformDirectoryException] if the system is unable to /// provide the directory on a supported platform. Future<Directory> getLibraryDirectory() async { final String? path = await _platform.getLibraryPath(); if (path == null) { throw MissingPlatformDirectoryException('Unable to get library directory'); } return Directory(path); } /// Path to a directory where the application may place data that is /// user-generated, or that cannot otherwise be recreated by your application. /// /// Consider using another path, such as [getApplicationSupportDirectory], /// [getApplicationCacheDirectory], or [getExternalStorageDirectory], if the /// data is not user-generated. /// /// Example implementations: /// - `NSDocumentDirectory` on iOS and macOS. /// - The Flutter engine's `PathUtils.getDataDirectory` API on Android. /// /// Throws a [MissingPlatformDirectoryException] if the system is unable to /// provide the directory. Future<Directory> getApplicationDocumentsDirectory() async { final String? path = await _platform.getApplicationDocumentsPath(); if (path == null) { throw MissingPlatformDirectoryException( 'Unable to get application documents directory'); } return Directory(path); } /// Path to a directory where the application may place application-specific /// cache files. /// /// If this directory does not exist, it is created automatically. /// /// Throws a [MissingPlatformDirectoryException] if the system is unable to /// provide the directory. Future<Directory> getApplicationCacheDirectory() async { final String? path = await _platform.getApplicationCachePath(); if (path == null) { throw MissingPlatformDirectoryException( 'Unable to get application cache directory'); } return Directory(path); } /// Path to a directory where the application may access top level storage. /// /// Example implementation: /// - `getExternalFilesDir(null)` on Android. /// /// Throws an [UnsupportedError] if this is not supported on the current /// platform (for example, on iOS where it is not possible to access outside /// the app's sandbox). Future<Directory?> getExternalStorageDirectory() async { final String? path = await _platform.getExternalStoragePath(); if (path == null) { return null; } return Directory(path); } /// Paths to directories where application specific cache data can be stored /// externally. /// /// These paths typically reside on external storage like separate partitions /// or SD cards. Phones may have multiple storage directories available. /// /// Example implementation: /// - Context.getExternalCacheDirs() on Android (or /// Context.getExternalCacheDir() on API levels below 19). /// /// Throws an [UnsupportedError] if this is not supported on the current /// platform. This is unlikely to ever be supported on any platform other than /// Android. Future<List<Directory>?> getExternalCacheDirectories() async { final List<String>? paths = await _platform.getExternalCachePaths(); if (paths == null) { return null; } return paths.map((String path) => Directory(path)).toList(); } /// Paths to directories where application specific data can be stored /// externally. /// /// These paths typically reside on external storage like separate partitions /// or SD cards. Phones may have multiple storage directories available. /// /// Example implementation: /// - Context.getExternalFilesDirs(type) on Android (or /// Context.getExternalFilesDir(type) on API levels below 19). /// /// Throws an [UnsupportedError] if this is not supported on the current /// platform. This is unlikely to ever be supported on any platform other than /// Android. Future<List<Directory>?> getExternalStorageDirectories({ /// Optional parameter. See [StorageDirectory] for more informations on /// how this type translates to Android storage directories. StorageDirectory? type, }) async { final List<String>? paths = await _platform.getExternalStoragePaths(type: type); if (paths == null) { return null; } return paths.map((String path) => Directory(path)).toList(); } /// Path to the directory where downloaded files can be stored. /// /// The returned directory is not guaranteed to exist, so clients should verify /// that it does before using it, and potentially create it if necessary. /// /// Throws an [UnsupportedError] if this is not supported on the current /// platform. Future<Directory?> getDownloadsDirectory() async { final String? path = await _platform.getDownloadsPath(); if (path == null) { return null; } return Directory(path); }
packages/packages/path_provider/path_provider/lib/path_provider.dart/0
{ "file_path": "packages/packages/path_provider/path_provider/lib/path_provider.dart", "repo_id": "packages", "token_count": 2056 }
1,016
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
packages/packages/path_provider/path_provider_foundation/example/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "packages/packages/path_provider/path_provider_foundation/example/macos/Runner/Configs/Debug.xcconfig", "repo_id": "packages", "token_count": 32 }
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 'dart:io'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/annotations.dart'; import 'package:mockito/mockito.dart'; import 'package:path/path.dart' as p; import 'package:path_provider_foundation/messages.g.dart'; import 'package:path_provider_foundation/path_provider_foundation.dart'; import 'messages_test.g.dart'; import 'path_provider_foundation_test.mocks.dart'; @GenerateMocks(<Type>[TestPathProviderApi]) void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('PathProviderFoundation', () { late MockTestPathProviderApi mockApi; // These unit tests use the actual filesystem, since an injectable // filesystem would add a runtime dependency to the package, so everything // is contained to a temporary directory. late Directory testRoot; setUp(() async { testRoot = Directory.systemTemp.createTempSync(); mockApi = MockTestPathProviderApi(); TestPathProviderApi.setup(mockApi); }); tearDown(() { testRoot.deleteSync(recursive: true); }); test('getTemporaryPath', () async { final PathProviderFoundation pathProvider = PathProviderFoundation(); final String temporaryPath = p.join(testRoot.path, 'temporary', 'path'); when(mockApi.getDirectoryPath(DirectoryType.temp)) .thenReturn(temporaryPath); final String? path = await pathProvider.getTemporaryPath(); verify(mockApi.getDirectoryPath(DirectoryType.temp)); expect(path, temporaryPath); }); test('getApplicationSupportPath', () async { final PathProviderFoundation pathProvider = PathProviderFoundation(); final String applicationSupportPath = p.join(testRoot.path, 'application', 'support', 'path'); when(mockApi.getDirectoryPath(DirectoryType.applicationSupport)) .thenReturn(applicationSupportPath); final String? path = await pathProvider.getApplicationSupportPath(); verify(mockApi.getDirectoryPath(DirectoryType.applicationSupport)); expect(path, applicationSupportPath); }); test('getApplicationSupportPath creates the directory if necessary', () async { final PathProviderFoundation pathProvider = PathProviderFoundation(); final String applicationSupportPath = p.join(testRoot.path, 'application', 'support', 'path'); when(mockApi.getDirectoryPath(DirectoryType.applicationSupport)) .thenReturn(applicationSupportPath); final String? path = await pathProvider.getApplicationSupportPath(); expect(Directory(path!).existsSync(), isTrue); }); test('getLibraryPath', () async { final PathProviderFoundation pathProvider = PathProviderFoundation(); final String libraryPath = p.join(testRoot.path, 'library', 'path'); when(mockApi.getDirectoryPath(DirectoryType.library)) .thenReturn(libraryPath); final String? path = await pathProvider.getLibraryPath(); verify(mockApi.getDirectoryPath(DirectoryType.library)); expect(path, libraryPath); }); test('getApplicationDocumentsPath', () async { final PathProviderFoundation pathProvider = PathProviderFoundation(); final String applicationDocumentsPath = p.join(testRoot.path, 'application', 'documents', 'path'); when(mockApi.getDirectoryPath(DirectoryType.applicationDocuments)) .thenReturn(applicationDocumentsPath); final String? path = await pathProvider.getApplicationDocumentsPath(); verify(mockApi.getDirectoryPath(DirectoryType.applicationDocuments)); expect(path, applicationDocumentsPath); }); test('getApplicationCachePath', () async { final PathProviderFoundation pathProvider = PathProviderFoundation(); final String applicationCachePath = p.join(testRoot.path, 'application', 'cache', 'path'); when(mockApi.getDirectoryPath(DirectoryType.applicationCache)) .thenReturn(applicationCachePath); final String? path = await pathProvider.getApplicationCachePath(); verify(mockApi.getDirectoryPath(DirectoryType.applicationCache)); expect(path, applicationCachePath); }); test('getApplicationCachePath creates the directory if necessary', () async { final PathProviderFoundation pathProvider = PathProviderFoundation(); final String applicationCachePath = p.join(testRoot.path, 'application', 'cache', 'path'); when(mockApi.getDirectoryPath(DirectoryType.applicationCache)) .thenReturn(applicationCachePath); final String? path = await pathProvider.getApplicationCachePath(); expect(Directory(path!).existsSync(), isTrue); }); test('getDownloadsPath', () async { final PathProviderFoundation pathProvider = PathProviderFoundation(); final String downloadsPath = p.join(testRoot.path, 'downloads', 'path'); when(mockApi.getDirectoryPath(DirectoryType.downloads)) .thenReturn(downloadsPath); final String? result = await pathProvider.getDownloadsPath(); verify(mockApi.getDirectoryPath(DirectoryType.downloads)); expect(result, downloadsPath); }); test('getExternalCachePaths throws', () async { final PathProviderFoundation pathProvider = PathProviderFoundation(); expect(pathProvider.getExternalCachePaths(), throwsA(isUnsupportedError)); }); test('getExternalStoragePath throws', () async { final PathProviderFoundation pathProvider = PathProviderFoundation(); expect( pathProvider.getExternalStoragePath(), throwsA(isUnsupportedError)); }); test('getExternalStoragePaths throws', () async { final PathProviderFoundation pathProvider = PathProviderFoundation(); expect( pathProvider.getExternalStoragePaths(), throwsA(isUnsupportedError)); }); test('getContainerPath', () async { final PathProviderFoundation pathProvider = PathProviderFoundation(platform: FakePlatformProvider(isIOS: true)); const String appGroupIdentifier = 'group.example.test'; final String containerPath = p.join(testRoot.path, 'container', 'path'); when(mockApi.getContainerPath(appGroupIdentifier)) .thenReturn(containerPath); final String? result = await pathProvider.getContainerPath( appGroupIdentifier: appGroupIdentifier); verify(mockApi.getContainerPath(appGroupIdentifier)); expect(result, containerPath); }); test('getContainerPath throws on macOS', () async { final PathProviderFoundation pathProvider = PathProviderFoundation(platform: FakePlatformProvider(isIOS: false)); expect( pathProvider.getContainerPath( appGroupIdentifier: 'group.example.test'), throwsA(isUnsupportedError)); }); }); } /// Fake implementation of PathProviderPlatformProvider that returns iOS is true class FakePlatformProvider implements PathProviderPlatformProvider { FakePlatformProvider({required this.isIOS}); @override bool isIOS; }
packages/packages/path_provider/path_provider_foundation/test/path_provider_foundation_test.dart/0
{ "file_path": "packages/packages/path_provider/path_provider_foundation/test/path_provider_foundation_test.dart", "repo_id": "packages", "token_count": 2376 }
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 'dart:io'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:path_provider_windows/path_provider_windows.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); testWidgets('getTemporaryDirectory', (WidgetTester tester) async { final PathProviderWindows provider = PathProviderWindows(); final String? result = await provider.getTemporaryPath(); _verifySampleFile(result, 'temporaryDirectory'); }); testWidgets('getApplicationDocumentsDirectory', (WidgetTester tester) async { final PathProviderWindows provider = PathProviderWindows(); final String? result = await provider.getApplicationDocumentsPath(); _verifySampleFile(result, 'applicationDocuments'); }); testWidgets('getApplicationSupportDirectory', (WidgetTester tester) async { final PathProviderWindows provider = PathProviderWindows(); final String? result = await provider.getApplicationSupportPath(); _verifySampleFile(result, 'applicationSupport'); }); testWidgets('getApplicationCacheDirectory', (WidgetTester tester) async { final PathProviderWindows provider = PathProviderWindows(); final String? result = await provider.getApplicationCachePath(); _verifySampleFile(result, 'applicationCache'); }); testWidgets('getDownloadsDirectory', (WidgetTester tester) async { final PathProviderWindows provider = PathProviderWindows(); final String? result = await provider.getDownloadsPath(); _verifySampleFile(result, 'downloads'); }); } /// Verify a file called [name] in [directoryPath] by recreating it with test /// contents when necessary. void _verifySampleFile(String? directoryPath, String name) { expect(directoryPath, isNotNull); if (directoryPath == null) { return; } final Directory directory = Directory(directoryPath); final File file = File('${directory.path}${Platform.pathSeparator}$name'); if (file.existsSync()) { file.deleteSync(); expect(file.existsSync(), isFalse); } file.writeAsStringSync('Hello world!'); expect(file.readAsStringSync(), 'Hello world!'); expect(directory.listSync(), isNotEmpty); file.deleteSync(); }
packages/packages/path_provider/path_provider_windows/example/integration_test/path_provider_test.dart/0
{ "file_path": "packages/packages/path_provider/path_provider_windows/example/integration_test/path_provider_test.dart", "repo_id": "packages", "token_count": 686 }
1,019
# Pigeon Contributor's Guide ## Description Pigeon is a code generation tool that adds type safety to Flutter’s Platform Channels. This document serves as an overview of how it functions to help people who would like to contribute to the project. ## State Diagram Pigeon generates a temporary file in its _LaunchIsolate_, the isolate that is spawned to run `main()`, then launches another isolate, _PigeonIsolate_, that uses `dart:mirrors` to parse the generated file, creating an [AST](https://en.wikipedia.org/wiki/Abstract_syntax_tree), then running code generators with that AST. ![State Diagram](./doc/pigeon_state.png) ## Source Index * [ast.dart](./lib/ast.dart) - The data structure for representing the Abstract Syntax Tree. * [dart_generator.dart](./lib/dart_generator.dart) - The Dart code generator. * [java_generator.dart](./lib/java_generator.dart) - The Java code generator. * [objc_generator.dart](./lib/objc_generator.dart) - The Objective-C code generator (header and source files). * [cpp_generator.dart](./lib/cpp_generator.dart) - The C++ code generator. * [generator_tools.dart](./lib/generator_tools.dart) - Shared code between generators. * [pigeon_cl.dart](./lib/pigeon_cl.dart) - The top-level function executed by the command line tool in [bin/][./bin]. * [pigeon_lib.dart](./lib/pigeon_lib.dart) - The top-level function for the PigeonIsolate and the AST generation code. * [pigeon.dart](./lib/pigeon.dart) - A file of exported modules, the intended import for users of Pigeon. ## Testing Overview Pigeon has 3 types of tests, you'll find them all in [test.dart](./tool/test.dart). * Unit tests - These are the fastest tests that are just typical unit tests, they may be generating code and checking it against a regular expression to see if it's correct. Example: [dart_generator_test.dart](./test/dart_generator_test.dart) * Compilation tests - These tests generate code, then attempt to compile that code. These are tests are much slower than unit tests, but not as slow as integration tests. These tests are typically run against the Pigeon files in [pigeons](./pigeons). * Integration tests - These tests generate code, then compile the generated code, then execute the generated code. It can be thought of as unit-tests run against the generated code. Examples: [platform_tests](./platform_tests) ## Generated Source Code Example This is what the temporary generated code that the _PigeonIsolate_ executes looks like (see [State Diagram](#state-diagram)): ```dart import 'path/to/supplied/pigeon/file.dart' import 'dart:io'; import 'dart:isolate'; import 'package:pigeon/pigeon_lib.dart'; void main(List<String> args, SendPort sendPort) async { sendPort.send(await Pigeon.run(args)); } ``` This is how `dart:mirrors` gets access to the supplied Pigeon file. ## Imminent Plans * Migrate to Dart Analyzer for AST generation ([issue 78818](https://github.com/flutter/flutter/issues/78818)) - We might have reached the limitations of using dart:mirrors for parsing the Dart files. That package has been deprecated and it doesn't support null-safe annotations. We should migrate to using the Dart Analyzer as the front-end parser.
packages/packages/pigeon/CONTRIBUTING.md/0
{ "file_path": "packages/packages/pigeon/CONTRIBUTING.md", "repo_id": "packages", "token_count": 994 }
1,020
// 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 'pigeon_lib.dart'; /// This is the main entrypoint for the command-line tool. [args] are the /// command line arguments and there is an optional [packageConfig] to /// accommodate users that want to integrate pigeon with other build systems. /// [sdkPath] for specifying an optional Dart SDK path. Future<int> runCommandLine(List<String> args, {Uri? packageConfig, String? sdkPath}) async { return Pigeon.run(args, sdkPath: sdkPath); }
packages/packages/pigeon/lib/pigeon_cl.dart/0
{ "file_path": "packages/packages/pigeon/lib/pigeon_cl.dart", "repo_id": "packages", "token_count": 184 }
1,021
# Native Pigeon Tests This directory contains native test harnesses for native and end-to-end tests of Pigeon-generated code. The [test script](../tool/test.dart) generates native code from [pigeons/](../pigeons/) into the native test scaffolding, and then drives the tests there. To run these tests, use [`test.dart`](../tool/test.dart). Alternately, if you are running them directly (e.g., from within a platform IDE), you can use [`generate.dart`](../tool/generate.dart) to generate the necessary Pigeon output. ## test\_plugin The new unified test harness for all platforms. Tests in this plugin use the same structure as tests for the Flutter team-maintained plugins, as described [in the repository documentation](https://github.com/flutter/flutter/wiki/Plugin-Tests). ## alternate\_language\_test\_plugin The test harness for alternate languages, on platforms that have multiple supported plugin languages. It covers: - Java for Android - Objective-C for iOS ## flutter\_null\_safe\_unit\_tests Dart unit tests for null-safe mode. This is a legacy structure from before NNBD was the only mode Pigeon supported; these should be folded back into the main tests.
packages/packages/pigeon/platform_tests/README.md/0
{ "file_path": "packages/packages/pigeon/platform_tests/README.md", "repo_id": "packages", "token_count": 330 }
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 com.example.alternate_language_test_plugin; import static org.junit.Assert.*; import com.example.alternate_language_test_plugin.NonNullFields.NonNullFieldSearchRequest; import java.lang.IllegalStateException; import org.junit.Test; public class NonNullFieldsTest { @Test public void builder() { NonNullFieldSearchRequest request = new NonNullFieldSearchRequest.Builder().setQuery("hello").build(); assertEquals(request.getQuery(), "hello"); } @Test(expected = IllegalStateException.class) public void builderThrowsIfNull() { NonNullFieldSearchRequest request = new NonNullFieldSearchRequest.Builder().build(); } }
packages/packages/pigeon/platform_tests/alternate_language_test_plugin/android/src/test/java/com/example/alternate_language_test_plugin/NonNullFieldsTest.java/0
{ "file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/android/src/test/java/com/example/alternate_language_test_plugin/NonNullFieldsTest.java", "repo_id": "packages", "token_count": 243 }
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 Flutter; @import XCTest; @import alternate_language_test_plugin; #import "EchoMessenger.h" /////////////////////////////////////////////////////////////////////////////////////////// @interface PrimitiveTest : XCTestCase @end /////////////////////////////////////////////////////////////////////////////////////////// @implementation PrimitiveTest - (void)testIntPrimitive { EchoBinaryMessenger *binaryMessenger = [[EchoBinaryMessenger alloc] initWithCodec:PrimitiveFlutterApiGetCodec()]; PrimitiveFlutterApi *api = [[PrimitiveFlutterApi alloc] initWithBinaryMessenger:binaryMessenger]; XCTestExpectation *expectation = [self expectationWithDescription:@"callback"]; [api anIntValue:1 completion:^(NSNumber *_Nonnull result, FlutterError *_Nullable err) { XCTAssertEqualObjects(@1, result); [expectation fulfill]; }]; [self waitForExpectations:@[ expectation ] timeout:1.0]; } - (void)testBoolPrimitive { EchoBinaryMessenger *binaryMessenger = [[EchoBinaryMessenger alloc] initWithCodec:PrimitiveFlutterApiGetCodec()]; PrimitiveFlutterApi *api = [[PrimitiveFlutterApi alloc] initWithBinaryMessenger:binaryMessenger]; XCTestExpectation *expectation = [self expectationWithDescription:@"callback"]; BOOL arg = YES; [api aBoolValue:arg completion:^(NSNumber *_Nonnull result, FlutterError *_Nullable err) { XCTAssertNotNil(result); XCTAssertEqual(arg, result.boolValue); [expectation fulfill]; }]; [self waitForExpectations:@[ expectation ] timeout:1.0]; } - (void)testDoublePrimitive { EchoBinaryMessenger *binaryMessenger = [[EchoBinaryMessenger alloc] initWithCodec:PrimitiveFlutterApiGetCodec()]; PrimitiveFlutterApi *api = [[PrimitiveFlutterApi alloc] initWithBinaryMessenger:binaryMessenger]; XCTestExpectation *expectation = [self expectationWithDescription:@"callback"]; NSInteger arg = 1.5; [api aDoubleValue:arg completion:^(NSNumber *_Nonnull result, FlutterError *_Nullable err) { XCTAssertNotNil(result); XCTAssertEqual(arg, result.integerValue); [expectation fulfill]; }]; [self waitForExpectations:@[ expectation ] timeout:1.0]; } - (void)testStringPrimitive { EchoBinaryMessenger *binaryMessenger = [[EchoBinaryMessenger alloc] initWithCodec:PrimitiveFlutterApiGetCodec()]; PrimitiveFlutterApi *api = [[PrimitiveFlutterApi alloc] initWithBinaryMessenger:binaryMessenger]; XCTestExpectation *expectation = [self expectationWithDescription:@"callback"]; NSString *arg = @"hello"; [api aStringValue:arg completion:^(NSString *_Nonnull result, FlutterError *_Nullable err) { XCTAssertEqualObjects(arg, result); [expectation fulfill]; }]; [self waitForExpectations:@[ expectation ] timeout:1.0]; } - (void)testListPrimitive { EchoBinaryMessenger *binaryMessenger = [[EchoBinaryMessenger alloc] initWithCodec:PrimitiveFlutterApiGetCodec()]; PrimitiveFlutterApi *api = [[PrimitiveFlutterApi alloc] initWithBinaryMessenger:binaryMessenger]; XCTestExpectation *expectation = [self expectationWithDescription:@"callback"]; NSArray *arg = @[ @"hello" ]; [api aListValue:arg completion:^(NSArray *_Nonnull result, FlutterError *_Nullable err) { XCTAssertEqualObjects(arg, result); [expectation fulfill]; }]; [self waitForExpectations:@[ expectation ] timeout:1.0]; } - (void)testMapPrimitive { EchoBinaryMessenger *binaryMessenger = [[EchoBinaryMessenger alloc] initWithCodec:PrimitiveFlutterApiGetCodec()]; PrimitiveFlutterApi *api = [[PrimitiveFlutterApi alloc] initWithBinaryMessenger:binaryMessenger]; XCTestExpectation *expectation = [self expectationWithDescription:@"callback"]; NSDictionary *arg = @{@"hello" : @1}; [api aMapValue:arg completion:^(NSDictionary *_Nonnull result, FlutterError *_Nullable err) { XCTAssertEqualObjects(arg, result); [expectation fulfill]; }]; [self waitForExpectations:@[ expectation ] timeout:1.0]; } @end
packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/PrimitiveTest.m/0
{ "file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/example/ios/RunnerTests/PrimitiveTest.m", "repo_id": "packages", "token_count": 1527 }
1,024
name: alternate_language_test_plugin description: Pigeon test harness for alternate plugin languages. version: 0.0.1 publish_to: none environment: sdk: ^3.1.0 flutter: ">=3.13.0" flutter: plugin: platforms: android: package: com.example.alternate_language_test_plugin pluginClass: AlternateLanguageTestPlugin ios: pluginClass: AlternateLanguageTestPlugin macos: pluginClass: AlternateLanguageTestPlugin dependencies: flutter: sdk: flutter dev_dependencies: flutter_test: sdk: flutter
packages/packages/pigeon/platform_tests/alternate_language_test_plugin/pubspec.yaml/0
{ "file_path": "packages/packages/pigeon/platform_tests/alternate_language_test_plugin/pubspec.yaml", "repo_id": "packages", "token_count": 217 }
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. // // 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 PrimitiveHostApi { /// Constructor for [PrimitiveHostApi]. 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. PrimitiveHostApi({BinaryMessenger? binaryMessenger}) : __pigeon_binaryMessenger = binaryMessenger; final BinaryMessenger? __pigeon_binaryMessenger; static const MessageCodec<Object?> pigeonChannelCodec = StandardMessageCodec(); Future<int> anInt(int value) async { const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.anInt'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[value]) 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?)!; } } Future<bool> aBool(bool value) async { const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aBool'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[value]) 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 bool?)!; } } Future<String> aString(String value) async { const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aString'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[value]) 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 String?)!; } } Future<double> aDouble(double value) async { const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aDouble'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[value]) 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 double?)!; } } Future<Map<Object?, Object?>> aMap(Map<Object?, Object?> value) async { const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aMap'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[value]) 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 Map<Object?, Object?>?)!; } } Future<List<Object?>> aList(List<Object?> value) async { const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aList'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[value]) 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 List<Object?>?)!; } } Future<Int32List> anInt32List(Int32List value) async { const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.anInt32List'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[value]) 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 Int32List?)!; } } Future<List<bool?>> aBoolList(List<bool?> value) async { const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aBoolList'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[value]) 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 List<Object?>?)!.cast<bool?>(); } } Future<Map<String?, int?>> aStringIntMap(Map<String?, int?> value) async { const String __pigeon_channelName = 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveHostApi.aStringIntMap'; final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel<Object?>( __pigeon_channelName, pigeonChannelCodec, binaryMessenger: __pigeon_binaryMessenger, ); final List<Object?>? __pigeon_replyList = await __pigeon_channel.send(<Object?>[value]) 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 Map<Object?, Object?>?)! .cast<String?, int?>(); } } } abstract class PrimitiveFlutterApi { static const MessageCodec<Object?> pigeonChannelCodec = StandardMessageCodec(); int anInt(int value); bool aBool(bool value); String aString(String value); double aDouble(double value); Map<Object?, Object?> aMap(Map<Object?, Object?> value); List<Object?> aList(List<Object?> value); Int32List anInt32List(Int32List value); List<bool?> aBoolList(List<bool?> value); Map<String?, int?> aStringIntMap(Map<String?, int?> value); static void setup(PrimitiveFlutterApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.anInt', 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.PrimitiveFlutterApi.anInt was null.'); final List<Object?> args = (message as List<Object?>?)!; final int? arg_value = (args[0] as int?); assert(arg_value != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.anInt was null, expected non-null int.'); try { final int output = api.anInt(arg_value!); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aBool', 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.PrimitiveFlutterApi.aBool was null.'); final List<Object?> args = (message as List<Object?>?)!; final bool? arg_value = (args[0] as bool?); assert(arg_value != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aBool was null, expected non-null bool.'); try { final bool output = api.aBool(arg_value!); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aString', 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.PrimitiveFlutterApi.aString was null.'); final List<Object?> args = (message as List<Object?>?)!; final String? arg_value = (args[0] as String?); assert(arg_value != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aString was null, expected non-null String.'); try { final String output = api.aString(arg_value!); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aDouble', 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.PrimitiveFlutterApi.aDouble was null.'); final List<Object?> args = (message as List<Object?>?)!; final double? arg_value = (args[0] as double?); assert(arg_value != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aDouble was null, expected non-null double.'); try { final double output = api.aDouble(arg_value!); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aMap', 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.PrimitiveFlutterApi.aMap was null.'); final List<Object?> args = (message as List<Object?>?)!; final Map<Object?, Object?>? arg_value = (args[0] as Map<Object?, Object?>?); assert(arg_value != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aMap was null, expected non-null Map<Object?, Object?>.'); try { final Map<Object?, Object?> output = api.aMap(arg_value!); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aList', 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.PrimitiveFlutterApi.aList was null.'); final List<Object?> args = (message as List<Object?>?)!; final List<Object?>? arg_value = (args[0] as List<Object?>?); assert(arg_value != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aList was null, expected non-null List<Object?>.'); try { final List<Object?> output = api.aList(arg_value!); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.anInt32List', 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.PrimitiveFlutterApi.anInt32List was null.'); final List<Object?> args = (message as List<Object?>?)!; final Int32List? arg_value = (args[0] as Int32List?); assert(arg_value != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.anInt32List was null, expected non-null Int32List.'); try { final Int32List output = api.anInt32List(arg_value!); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aBoolList', 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.PrimitiveFlutterApi.aBoolList was null.'); final List<Object?> args = (message as List<Object?>?)!; final List<bool?>? arg_value = (args[0] as List<Object?>?)?.cast<bool?>(); assert(arg_value != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aBoolList was null, expected non-null List<bool?>.'); try { final List<bool?> output = api.aBoolList(arg_value!); return wrapResponse(result: output); } on PlatformException catch (e) { return wrapResponse(error: e); } catch (e) { return wrapResponse( error: PlatformException(code: 'error', message: e.toString())); } }); } } { final BasicMessageChannel<Object?> __pigeon_channel = BasicMessageChannel< Object?>( 'dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aStringIntMap', 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.PrimitiveFlutterApi.aStringIntMap was null.'); final List<Object?> args = (message as List<Object?>?)!; final Map<String?, int?>? arg_value = (args[0] as Map<Object?, Object?>?)?.cast<String?, int?>(); assert(arg_value != null, 'Argument for dev.flutter.pigeon.pigeon_integration_tests.PrimitiveFlutterApi.aStringIntMap was null, expected non-null Map<String?, int?>.'); try { final Map<String?, int?> output = api.aStringIntMap(arg_value!); 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/primitive.gen.dart/0
{ "file_path": "packages/packages/pigeon/platform_tests/shared_test_plugin_code/lib/src/generated/primitive.gen.dart", "repo_id": "packages", "token_count": 10285 }
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. package com.example.test_plugin import junit.framework.TestCase import org.junit.Test class NonNullFieldsTests : TestCase() { @Test fun testMake() { val request = NonNullFieldSearchRequest("hello") assertEquals("hello", request.query) } }
packages/packages/pigeon/platform_tests/test_plugin/android/src/test/kotlin/com/example/test_plugin/NonNullFieldsTests.kt/0
{ "file_path": "packages/packages/pigeon/platform_tests/test_plugin/android/src/test/kotlin/com/example/test_plugin/NonNullFieldsTests.kt", "repo_id": "packages", "token_count": 128 }
1,027
// 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 @testable import test_plugin class MockHostSmallApi: HostSmallApi { var output: String? func echo(aString: String, completion: @escaping (Result<String, Error>) -> Void) { completion(.success(output!)) } func voidVoid(completion: @escaping (Result<Void, Error>) -> Void) { completion(.success(())) } } class AsyncHandlersTest: XCTestCase { func testAsyncHost2Flutter() throws { let value = "Test" let binaryMessenger = MockBinaryMessenger<String>(codec: FlutterIntegrationCoreApiCodec.shared) binaryMessenger.result = value let flutterApi = FlutterIntegrationCoreApi(binaryMessenger: binaryMessenger) let expectation = XCTestExpectation(description: "callback") flutterApi.echo(value) { result in switch result { case .success(let res): XCTAssertEqual(res, value) expectation.fulfill() case .failure(_): return } } wait(for: [expectation], timeout: 1.0) } func testAsyncFlutter2HostVoidVoid() throws { let binaryMessenger = MockBinaryMessenger<String>( codec: FlutterStandardMessageCodec.sharedInstance()) let mockHostSmallApi = MockHostSmallApi() HostSmallApiSetup.setUp(binaryMessenger: binaryMessenger, api: mockHostSmallApi) let channelName = "dev.flutter.pigeon.pigeon_integration_tests.HostSmallApi.voidVoid" XCTAssertNotNil(binaryMessenger.handlers[channelName]) let expectation = XCTestExpectation(description: "voidvoid callback") binaryMessenger.handlers[channelName]?(nil) { data in let outputList = binaryMessenger.codec.decode(data) as? [Any] XCTAssertEqual(outputList?.first as! NSNull, NSNull()) expectation.fulfill() } wait(for: [expectation], timeout: 1.0) } func testAsyncFlutter2Host() throws { let binaryMessenger = MockBinaryMessenger<String>( codec: FlutterStandardMessageCodec.sharedInstance()) let mockHostSmallApi = MockHostSmallApi() let value = "Test" mockHostSmallApi.output = value HostSmallApiSetup.setUp(binaryMessenger: binaryMessenger, api: mockHostSmallApi) let channelName = "dev.flutter.pigeon.pigeon_integration_tests.HostSmallApi.echo" XCTAssertNotNil(binaryMessenger.handlers[channelName]) let inputEncoded = binaryMessenger.codec.encode([value]) let expectation = XCTestExpectation(description: "echo callback") binaryMessenger.handlers[channelName]?(inputEncoded) { data in let outputList = binaryMessenger.codec.decode(data) as? [Any] let output = outputList?.first as? String XCTAssertEqual(output, value) expectation.fulfill() } wait(for: [expectation], timeout: 1.0) } }
packages/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/AsyncHandlersTest.swift/0
{ "file_path": "packages/packages/pigeon/platform_tests/test_plugin/example/ios/RunnerTests/AsyncHandlersTest.swift", "repo_id": "packages", "token_count": 1036 }
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. import Flutter import UIKit extension FlutterError: Error {} /// This plugin handles the native side of the integration tests in /// example/integration_test/. public class TestPlugin: NSObject, FlutterPlugin, HostIntegrationCoreApi { var flutterAPI: FlutterIntegrationCoreApi public static func register(with registrar: FlutterPluginRegistrar) { let plugin = TestPlugin(binaryMessenger: registrar.messenger()) HostIntegrationCoreApiSetup.setUp(binaryMessenger: registrar.messenger(), api: plugin) } init(binaryMessenger: FlutterBinaryMessenger) { flutterAPI = FlutterIntegrationCoreApi(binaryMessenger: binaryMessenger) } // MARK: HostIntegrationCoreApi implementation func noop() { } func echo(_ everything: AllTypes) -> AllTypes { return everything } func echo(_ everything: AllNullableTypes?) -> AllNullableTypes? { return everything } func throwError() throws -> Any? { throw FlutterError(code: "code", message: "message", details: "details") } func throwErrorFromVoid() throws { throw FlutterError(code: "code", message: "message", details: "details") } func throwFlutterError() throws -> Any? { throw FlutterError(code: "code", message: "message", details: "details") } func echo(_ anInt: Int64) -> Int64 { return anInt } func echo(_ aDouble: Double) -> Double { return aDouble } func echo(_ aBool: Bool) -> Bool { return aBool } func echo(_ aString: String) -> String { return aString } func echo(_ aUint8List: FlutterStandardTypedData) -> FlutterStandardTypedData { return aUint8List } func echo(_ anObject: Any) -> Any { return anObject } func echo(_ aList: [Any?]) throws -> [Any?] { return aList } func echo(_ aMap: [String?: Any?]) throws -> [String?: Any?] { return aMap } func echo(_ wrapper: AllClassesWrapper) throws -> AllClassesWrapper { return wrapper } func echo(_ anEnum: AnEnum) throws -> AnEnum { return anEnum } func extractNestedNullableString(from wrapper: AllClassesWrapper) -> String? { return wrapper.allNullableTypes.aNullableString } func createNestedObject(with nullableString: String?) -> AllClassesWrapper { return AllClassesWrapper(allNullableTypes: AllNullableTypes(aNullableString: nullableString)) } func sendMultipleNullableTypes( aBool aNullableBool: Bool?, anInt aNullableInt: Int64?, aString aNullableString: String? ) -> AllNullableTypes { let someThings = AllNullableTypes( aNullableBool: aNullableBool, aNullableInt: aNullableInt, aNullableString: aNullableString) return someThings } func echo(_ aNullableInt: Int64?) -> Int64? { return aNullableInt } func echo(_ aNullableDouble: Double?) -> Double? { return aNullableDouble } func echo(_ aNullableBool: Bool?) -> Bool? { return aNullableBool } func echo(_ aNullableString: String?) -> String? { return aNullableString } func echo(_ aNullableUint8List: FlutterStandardTypedData?) -> FlutterStandardTypedData? { return aNullableUint8List } func echo(_ aNullableObject: Any?) -> Any? { return aNullableObject } func echoNamedDefault(_ aString: String) throws -> String { return aString } func echoOptionalDefault(_ aDouble: Double) throws -> Double { return aDouble } func echoRequired(_ anInt: Int64) throws -> Int64 { return anInt } func echoNullable(_ aNullableList: [Any?]?) throws -> [Any?]? { return aNullableList } func echoNullable(_ aNullableMap: [String?: Any?]?) throws -> [String?: Any?]? { return aNullableMap } func echoNullable(_ anEnum: AnEnum?) throws -> AnEnum? { return anEnum } func echoOptional(_ aNullableInt: Int64?) throws -> Int64? { return aNullableInt } func echoNamed(_ aNullableString: String?) throws -> String? { return aNullableString } func noopAsync(completion: @escaping (Result<Void, Error>) -> Void) { completion(.success(Void())) } func throwAsyncError(completion: @escaping (Result<Any?, Error>) -> Void) { completion(.failure(FlutterError(code: "code", message: "message", details: "details"))) } func throwAsyncErrorFromVoid(completion: @escaping (Result<Void, Error>) -> Void) { completion(.failure(FlutterError(code: "code", message: "message", details: "details"))) } func throwAsyncFlutterError(completion: @escaping (Result<Any?, Error>) -> Void) { completion(.failure(FlutterError(code: "code", message: "message", details: "details"))) } func echoAsync(_ everything: AllTypes, completion: @escaping (Result<AllTypes, Error>) -> Void) { completion(.success(everything)) } func echoAsync( _ everything: AllNullableTypes?, completion: @escaping (Result<AllNullableTypes?, Error>) -> Void ) { completion(.success(everything)) } func echoAsync(_ anInt: Int64, completion: @escaping (Result<Int64, Error>) -> Void) { completion(.success(anInt)) } func echoAsync(_ aDouble: Double, completion: @escaping (Result<Double, Error>) -> Void) { completion(.success(aDouble)) } func echoAsync(_ aBool: Bool, completion: @escaping (Result<Bool, Error>) -> Void) { completion(.success(aBool)) } func echoAsync(_ aString: String, completion: @escaping (Result<String, Error>) -> Void) { completion(.success(aString)) } func echoAsync( _ aUint8List: FlutterStandardTypedData, completion: @escaping (Result<FlutterStandardTypedData, Error>) -> Void ) { completion(.success(aUint8List)) } func echoAsync(_ anObject: Any, completion: @escaping (Result<Any, Error>) -> Void) { completion(.success(anObject)) } func echoAsync(_ aList: [Any?], completion: @escaping (Result<[Any?], Error>) -> Void) { completion(.success(aList)) } func echoAsync( _ aMap: [String?: Any?], completion: @escaping (Result<[String?: Any?], Error>) -> Void ) { completion(.success(aMap)) } func echoAsync(_ anEnum: AnEnum, completion: @escaping (Result<AnEnum, Error>) -> Void) { completion(.success(anEnum)) } func echoAsyncNullable(_ anInt: Int64?, completion: @escaping (Result<Int64?, Error>) -> Void) { completion(.success(anInt)) } func echoAsyncNullable(_ aDouble: Double?, completion: @escaping (Result<Double?, Error>) -> Void) { completion(.success(aDouble)) } func echoAsyncNullable(_ aBool: Bool?, completion: @escaping (Result<Bool?, Error>) -> Void) { completion(.success(aBool)) } func echoAsyncNullable(_ aString: String?, completion: @escaping (Result<String?, Error>) -> Void) { completion(.success(aString)) } func echoAsyncNullable( _ aUint8List: FlutterStandardTypedData?, completion: @escaping (Result<FlutterStandardTypedData?, Error>) -> Void ) { completion(.success(aUint8List)) } func echoAsyncNullable(_ anObject: Any?, completion: @escaping (Result<Any?, Error>) -> Void) { completion(.success(anObject)) } func echoAsyncNullable(_ aList: [Any?]?, completion: @escaping (Result<[Any?]?, Error>) -> Void) { completion(.success(aList)) } func echoAsyncNullable( _ aMap: [String?: Any?]?, completion: @escaping (Result<[String?: Any?]?, Error>) -> Void ) { completion(.success(aMap)) } func echoAsyncNullable(_ anEnum: AnEnum?, completion: @escaping (Result<AnEnum?, Error>) -> Void) { completion(.success(anEnum)) } func callFlutterNoop(completion: @escaping (Result<Void, Error>) -> Void) { flutterAPI.noop { response in switch response { case .success(let res): completion(.success(res)) case .failure(let error): completion(.failure(error)) } } } func callFlutterThrowError(completion: @escaping (Result<Any?, Error>) -> Void) { flutterAPI.throwError { response in switch response { case .success(let res): completion(.success(res)) case .failure(let error): completion(.failure(error)) } } } func callFlutterThrowErrorFromVoid(completion: @escaping (Result<Void, Error>) -> Void) { flutterAPI.throwErrorFromVoid { response in switch response { case .success(let res): completion(.success(res)) case .failure(let error): completion(.failure(error)) } } } func callFlutterEcho( _ everything: AllTypes, completion: @escaping (Result<AllTypes, Error>) -> Void ) { flutterAPI.echo(everything) { response in switch response { case .success(let res): completion(.success(res)) case .failure(let error): completion(.failure(error)) } } } func callFlutterEcho( _ everything: AllNullableTypes?, completion: @escaping (Result<AllNullableTypes?, Error>) -> Void ) { flutterAPI.echoNullable(everything) { response in switch response { case .success(let res): completion(.success(res)) case .failure(let error): completion(.failure(error)) } } } func callFlutterSendMultipleNullableTypes( aBool aNullableBool: Bool?, anInt aNullableInt: Int64?, aString aNullableString: String?, completion: @escaping (Result<AllNullableTypes, Error>) -> Void ) { flutterAPI.sendMultipleNullableTypes( aBool: aNullableBool, anInt: aNullableInt, aString: aNullableString ) { response in switch response { case .success(let res): completion(.success(res)) case .failure(let error): completion(.failure(error)) } } } func callFlutterEcho(_ aBool: Bool, completion: @escaping (Result<Bool, Error>) -> Void) { flutterAPI.echo(aBool) { response in switch response { case .success(let res): completion(.success(res)) case .failure(let error): completion(.failure(error)) } } } func callFlutterEcho(_ anInt: Int64, completion: @escaping (Result<Int64, Error>) -> Void) { flutterAPI.echo(anInt) { response in switch response { case .success(let res): completion(.success(res)) case .failure(let error): completion(.failure(error)) } } } func callFlutterEcho(_ aDouble: Double, completion: @escaping (Result<Double, Error>) -> Void) { flutterAPI.echo(aDouble) { response in switch response { case .success(let res): completion(.success(res)) case .failure(let error): completion(.failure(error)) } } } func callFlutterEcho(_ aString: String, completion: @escaping (Result<String, Error>) -> Void) { flutterAPI.echo(aString) { response in switch response { case .success(let res): completion(.success(res)) case .failure(let error): completion(.failure(error)) } } } func callFlutterEcho( _ aList: FlutterStandardTypedData, completion: @escaping (Result<FlutterStandardTypedData, Error>) -> Void ) { flutterAPI.echo(aList) { response in switch response { case .success(let res): completion(.success(res)) case .failure(let error): completion(.failure(error)) } } } func callFlutterEcho(_ aList: [Any?], completion: @escaping (Result<[Any?], Error>) -> Void) { flutterAPI.echo(aList) { response in switch response { case .success(let res): completion(.success(res)) case .failure(let error): completion(.failure(error)) } } } func callFlutterEcho( _ aMap: [String?: Any?], completion: @escaping (Result<[String?: Any?], Error>) -> Void ) { flutterAPI.echo(aMap) { response in switch response { case .success(let res): completion(.success(res)) case .failure(let error): completion(.failure(error)) } } } func callFlutterEcho(_ anEnum: AnEnum, completion: @escaping (Result<AnEnum, Error>) -> Void) { flutterAPI.echo(anEnum) { response in switch response { case .success(let res): completion(.success(res)) case .failure(let error): completion(.failure(error)) } } } func callFlutterEchoNullable(_ aBool: Bool?, completion: @escaping (Result<Bool?, Error>) -> Void) { flutterAPI.echoNullable(aBool) { response in switch response { case .success(let res): completion(.success(res)) case .failure(let error): completion(.failure(error)) } } } func callFlutterEchoNullable( _ anInt: Int64?, completion: @escaping (Result<Int64?, Error>) -> Void ) { flutterAPI.echoNullable(anInt) { response in switch response { case .success(let res): completion(.success(res)) case .failure(let error): completion(.failure(error)) } } } func callFlutterEchoNullable( _ aDouble: Double?, completion: @escaping (Result<Double?, Error>) -> Void ) { flutterAPI.echoNullable(aDouble) { response in switch response { case .success(let res): completion(.success(res)) case .failure(let error): completion(.failure(error)) } } } func callFlutterEchoNullable( _ aString: String?, completion: @escaping (Result<String?, Error>) -> Void ) { flutterAPI.echoNullable(aString) { response in switch response { case .success(let res): completion(.success(res)) case .failure(let error): completion(.failure(error)) } } } func callFlutterEchoNullable( _ aList: FlutterStandardTypedData?, completion: @escaping (Result<FlutterStandardTypedData?, Error>) -> Void ) { flutterAPI.echoNullable(aList) { response in switch response { case .success(let res): completion(.success(res)) case .failure(let error): completion(.failure(error)) } } } func callFlutterEchoNullable( _ aList: [Any?]?, completion: @escaping (Result<[Any?]?, Error>) -> Void ) { flutterAPI.echoNullable(aList) { response in switch response { case .success(let res): completion(.success(res)) case .failure(let error): completion(.failure(error)) } } } func callFlutterEchoNullable( _ aMap: [String?: Any?]?, completion: @escaping (Result<[String?: Any?]?, Error>) -> Void ) { flutterAPI.echoNullable(aMap) { response in switch response { case .success(let res): completion(.success(res)) case .failure(let error): completion(.failure(error)) } } } func callFlutterNullableEcho( _ anEnum: AnEnum?, completion: @escaping (Result<AnEnum?, Error>) -> Void ) { flutterAPI.echoNullable(anEnum) { response in switch response { case .success(let res): completion(.success(res)) case .failure(let error): completion(.failure(error)) } } } }
packages/packages/pigeon/platform_tests/test_plugin/ios/Classes/TestPlugin.swift/0
{ "file_path": "packages/packages/pigeon/platform_tests/test_plugin/ios/Classes/TestPlugin.swift", "repo_id": "packages", "token_count": 5665 }
1,029
// 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. #include <flutter/encodable_value.h> #include <gtest/gtest.h> #include "pigeon/null_fields.gen.h" namespace null_fields_pigeontest { namespace { using flutter::EncodableList; using flutter::EncodableMap; using flutter::EncodableValue; /// EXPECTs that 'list' contains 'index', and then returns a pointer to its /// value. /// /// This gives useful test failure messages instead of silent crashes when the /// value isn't present, or has the wrong type. template <class T> const T* ExpectAndGetIndex(const EncodableList& list, const int i) { EXPECT_LT(i, list.size()) << "Index " << i << " is out of bounds; size is " << list.size(); if (i >= list.size()) { return nullptr; } const T* value_ptr = std::get_if<T>(&(list[i])); EXPECT_NE(value_ptr, nullptr) << "Value for index " << i << " has incorrect type"; return value_ptr; } } // namespace class NullFieldsTest : public ::testing::Test { protected: // Wrapper for access to private NullFieldsSearchRequest list constructor. NullFieldsSearchRequest RequestFromList(const EncodableList& list) { return NullFieldsSearchRequest::FromEncodableList(list); } // Wrapper for access to private NullFieldsSearchRequest list constructor. NullFieldsSearchReply ReplyFromList(const EncodableList& list) { return NullFieldsSearchReply::FromEncodableList(list); } // Wrapper for access to private NullFieldsSearchRequest::ToEncodableList. EncodableList ListFromRequest(const NullFieldsSearchRequest& request) { return request.ToEncodableList(); } // Wrapper for access to private NullFieldsSearchRequest list constructor. EncodableList ListFromReply(const NullFieldsSearchReply& reply) { return reply.ToEncodableList(); } }; TEST(NullFields, BuildWithValues) { NullFieldsSearchRequest request(0); request.set_query("hello"); NullFieldsSearchReply reply; reply.set_result("result"); reply.set_error("error"); reply.set_indices(EncodableList({1, 2, 3})); reply.set_request(request); reply.set_type(NullFieldsSearchReplyType::success); EXPECT_EQ(*reply.result(), "result"); EXPECT_EQ(*reply.error(), "error"); EXPECT_EQ(reply.indices()->size(), 3); EXPECT_EQ(*reply.request()->query(), "hello"); EXPECT_EQ(*reply.type(), NullFieldsSearchReplyType::success); } TEST(NullFields, BuildRequestWithNulls) { NullFieldsSearchRequest request(0); EXPECT_EQ(request.query(), nullptr); } TEST(NullFields, BuildReplyWithNulls) { NullFieldsSearchReply reply; EXPECT_EQ(reply.result(), nullptr); EXPECT_EQ(reply.error(), nullptr); EXPECT_EQ(reply.indices(), nullptr); EXPECT_EQ(reply.request(), nullptr); EXPECT_EQ(reply.type(), nullptr); } TEST_F(NullFieldsTest, RequestFromListWithValues) { EncodableList list{ EncodableValue("hello"), EncodableValue(1), }; NullFieldsSearchRequest request = RequestFromList(list); EXPECT_EQ(*request.query(), "hello"); EXPECT_EQ(request.identifier(), 1); } TEST_F(NullFieldsTest, RequestFromListWithNulls) { EncodableList list{ EncodableValue(), EncodableValue(1), }; NullFieldsSearchRequest request = RequestFromList(list); EXPECT_EQ(request.query(), nullptr); EXPECT_EQ(request.identifier(), 1); } TEST_F(NullFieldsTest, ReplyFromListWithValues) { EncodableList list{ EncodableValue("result"), EncodableValue("error"), EncodableValue(EncodableList{ EncodableValue(1), EncodableValue(2), EncodableValue(3), }), EncodableValue(EncodableList{ EncodableValue("hello"), EncodableValue(1), }), EncodableValue(0), }; NullFieldsSearchReply reply = ReplyFromList(list); EXPECT_EQ(*reply.result(), "result"); EXPECT_EQ(*reply.error(), "error"); EXPECT_EQ(reply.indices()->size(), 3); EXPECT_EQ(*reply.request()->query(), "hello"); EXPECT_EQ(reply.request()->identifier(), 1); EXPECT_EQ(*reply.type(), NullFieldsSearchReplyType::success); } TEST_F(NullFieldsTest, ReplyFromListWithNulls) { EncodableList list{ EncodableValue(), EncodableValue(), EncodableValue(), EncodableValue(), EncodableValue(), }; NullFieldsSearchReply reply = ReplyFromList(list); EXPECT_EQ(reply.result(), nullptr); EXPECT_EQ(reply.error(), nullptr); EXPECT_EQ(reply.indices(), nullptr); EXPECT_EQ(reply.request(), nullptr); EXPECT_EQ(reply.type(), nullptr); } TEST_F(NullFieldsTest, RequestToListWithValues) { NullFieldsSearchRequest request(1); request.set_query("hello"); EncodableList list = ListFromRequest(request); EXPECT_EQ(list.size(), 2); EXPECT_EQ(*ExpectAndGetIndex<std::string>(list, 0), "hello"); EXPECT_EQ(*ExpectAndGetIndex<int64_t>(list, 1), 1); } TEST_F(NullFieldsTest, RequestToMapWithNulls) { NullFieldsSearchRequest request(1); EncodableList list = ListFromRequest(request); EXPECT_EQ(list.size(), 2); EXPECT_TRUE(list[0].IsNull()); EXPECT_EQ(*ExpectAndGetIndex<int64_t>(list, 1), 1); } TEST_F(NullFieldsTest, ReplyToMapWithValues) { NullFieldsSearchRequest request(1); request.set_query("hello"); NullFieldsSearchReply reply; reply.set_result("result"); reply.set_error("error"); reply.set_indices(EncodableList({1, 2, 3})); reply.set_request(request); reply.set_type(NullFieldsSearchReplyType::success); const EncodableList list = ListFromReply(reply); EXPECT_EQ(list.size(), 5); EXPECT_EQ(*ExpectAndGetIndex<std::string>(list, 0), "result"); EXPECT_EQ(*ExpectAndGetIndex<std::string>(list, 1), "error"); const EncodableList& indices = *ExpectAndGetIndex<EncodableList>(list, 2); EXPECT_EQ(indices.size(), 3); EXPECT_EQ(indices[0].LongValue(), 1L); EXPECT_EQ(indices[1].LongValue(), 2L); EXPECT_EQ(indices[2].LongValue(), 3L); const EncodableList& request_list = *ExpectAndGetIndex<EncodableList>(list, 3); EXPECT_EQ(*ExpectAndGetIndex<std::string>(request_list, 0), "hello"); EXPECT_EQ(*ExpectAndGetIndex<int64_t>(request_list, 1), 1); } TEST_F(NullFieldsTest, ReplyToListWithNulls) { NullFieldsSearchReply reply; const EncodableList list = ListFromReply(reply); const int field_count = 5; EXPECT_EQ(list.size(), field_count); for (int i = 0; i < field_count; ++i) { EXPECT_TRUE(list[i].IsNull()); } } } // namespace null_fields_pigeontest
packages/packages/pigeon/platform_tests/test_plugin/windows/test/null_fields_test.cpp/0
{ "file_path": "packages/packages/pigeon/platform_tests/test_plugin/windows/test/null_fields_test.cpp", "repo_id": "packages", "token_count": 2367 }
1,030
// 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/functional.dart'; import 'package:test/test.dart'; void main() { test('indexMap', () { final List<String> items = <String>['a', 'b', 'c']; final List<String> result = indexMap(items, (int index, String value) => value + index.toString()) .toList(); expect(result[0], 'a0'); expect(result[1], 'b1'); expect(result[2], 'c2'); }); test('enumerate', () { final List<String> items = <String>['a', 'b', 'c']; int saw = 0; enumerate(items, (int index, String value) { if (index == 0) { expect(value, 'a'); saw |= 0x1; } else if (index == 1) { expect(value, 'b'); saw |= 0x2; } else if (index == 2) { expect(value, 'c'); saw |= 0x4; } }); expect(saw, 0x7); }); test('map2', () { final List<int> result = map2(<int>[3, 5, 7], <int>[1, 2, 3], (int x, int y) => x * y).toList(); expect(result[0], 3); expect(result[1], 10); expect(result[2], 21); }); test('map2 unequal', () { expect( () => map2(<int>[], <int>[1, 2, 3], (int x, int y) => x * y).toList(), throwsArgumentError); }); test('map3', () { final List<int> result = map3(<int>[3, 5, 7], <int>[1, 2, 3], <int>[2, 2, 2], (int x, int y, int z) => x * y * z).toList(); expect(result[0], 6); expect(result[1], 20); expect(result[2], 42); }); test('map3 unequal', () { expect( () => map3(<int>[], <int>[1, 2, 3], <int>[], (int x, int y, int z) => x * y * z).toList(), throwsArgumentError); }); test('wholeNumbers', () { final List<int> result = wholeNumbers.take(3).toList(); expect(result.length, 3); expect(result[0], 0); expect(result[1], 1); expect(result[2], 2); }); test('repeat', () { final List<int> result = repeat(123, 3).toList(); expect(result.length, 3); expect(result[0], 123); expect(result[1], 123); expect(result[2], 123); }); }
packages/packages/pigeon/test/functional_test.dart/0
{ "file_path": "packages/packages/pigeon/test/functional_test.dart", "repo_id": "packages", "token_count": 977 }
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. // ignore_for_file: avoid_print import 'dart:io' show Directory, File; import 'package:meta/meta.dart'; import 'package:path/path.dart' as p; import 'flutter_utils.dart'; import 'generation.dart'; import 'native_project_runners.dart'; import 'process_utils.dart'; const int _noDeviceAvailableExitCode = 100; const String _testPluginRelativePath = 'platform_tests/test_plugin'; const String _alternateLanguageTestPluginRelativePath = 'platform_tests/alternate_language_test_plugin'; const String _integrationTestFileRelativePath = 'integration_test/test.dart'; /// Information about a test suite. @immutable class TestInfo { const TestInfo({required this.function, this.description}); /// The function to run the test suite. final Future<int> Function() function; /// A user-facing description of the test suite. final String? description; } // Test suite names. const String androidJavaUnitTests = 'android_java_unittests'; const String androidJavaLint = 'android_java_lint'; const String androidJavaIntegrationTests = 'android_java_integration_tests'; const String androidKotlinUnitTests = 'android_kotlin_unittests'; const String androidKotlinIntegrationTests = 'android_kotlin_integration_tests'; const String iOSObjCUnitTests = 'ios_objc_unittests'; const String iOSObjCIntegrationTests = 'ios_objc_integration_tests'; const String iOSSwiftUnitTests = 'ios_swift_unittests'; const String iOSSwiftIntegrationTests = 'ios_swift_integration_tests'; const String macOSObjCIntegrationTests = 'macos_objc_integration_tests'; const String macOSSwiftUnitTests = 'macos_swift_unittests'; const String macOSSwiftIntegrationTests = 'macos_swift_integration_tests'; const String windowsUnitTests = 'windows_unittests'; const String windowsIntegrationTests = 'windows_integration_tests'; const String dartUnitTests = 'dart_unittests'; const String flutterUnitTests = 'flutter_unittests'; const String commandLineTests = 'command_line_tests'; const Map<String, TestInfo> testSuites = <String, TestInfo>{ windowsUnitTests: TestInfo( function: _runWindowsUnitTests, description: 'Unit tests on generated Windows C++ code.'), windowsIntegrationTests: TestInfo( function: _runWindowsIntegrationTests, description: 'Integration tests on generated Windows C++ code.'), androidJavaUnitTests: TestInfo( function: _runAndroidJavaUnitTests, description: 'Unit tests on generated Java code.'), androidJavaIntegrationTests: TestInfo( function: _runAndroidJavaIntegrationTests, description: 'Integration tests on generated Java code.'), androidJavaLint: TestInfo( function: _runAndroidJavaLint, description: 'Lint generated Java code.'), androidKotlinUnitTests: TestInfo( function: _runAndroidKotlinUnitTests, description: 'Unit tests on generated Kotlin code.'), androidKotlinIntegrationTests: TestInfo( function: _runAndroidKotlinIntegrationTests, description: 'Integration tests on generated Kotlin code.'), dartUnitTests: TestInfo( function: _runDartUnitTests, description: "Unit tests on and analysis on Pigeon's implementation."), flutterUnitTests: TestInfo( function: _runFlutterUnitTests, description: 'Unit tests on generated Dart code.'), iOSObjCUnitTests: TestInfo( function: _runIOSObjCUnitTests, description: 'Unit tests on generated Objective-C code.'), iOSObjCIntegrationTests: TestInfo( function: _runIOSObjCIntegrationTests, description: 'Integration tests on generated Objective-C code.'), iOSSwiftUnitTests: TestInfo( function: _runIOSSwiftUnitTests, description: 'Unit tests on generated Swift code.'), iOSSwiftIntegrationTests: TestInfo( function: _runIOSSwiftIntegrationTests, description: 'Integration tests on generated Swift code.'), macOSObjCIntegrationTests: TestInfo( function: _runMacOSObjCIntegrationTests, description: 'Integration tests on generated Objective-C code on macOS.'), macOSSwiftUnitTests: TestInfo( function: _runMacOSSwiftUnitTests, description: 'Unit tests on generated Swift code on macOS.'), macOSSwiftIntegrationTests: TestInfo( function: _runMacOSSwiftIntegrationTests, description: 'Integration tests on generated Swift code on macOS.'), commandLineTests: TestInfo( function: _runCommandLineTests, description: 'Tests running pigeon with various command-line options.'), }; Future<int> _runAndroidJavaUnitTests() async { return _runAndroidUnitTests(_alternateLanguageTestPluginRelativePath); } Future<int> _runAndroidJavaIntegrationTests() async { return _runMobileIntegrationTests( 'Android', _alternateLanguageTestPluginRelativePath); } Future<int> _runAndroidJavaLint() async { const String examplePath = './$_alternateLanguageTestPluginRelativePath/example'; const String androidProjectPath = '$examplePath/android'; final File gradleFile = File(p.join(androidProjectPath, 'gradlew')); if (!gradleFile.existsSync()) { final int compileCode = await runFlutterBuild(examplePath, 'apk', flags: <String>['--config-only']); if (compileCode != 0) { return compileCode; } } return runGradleBuild( androidProjectPath, 'alternate_language_test_plugin:lintDebug'); } Future<int> _runAndroidKotlinUnitTests() async { return _runAndroidUnitTests(_testPluginRelativePath); } Future<int> _runAndroidUnitTests(String testPluginPath) async { final String examplePath = './$testPluginPath/example'; final String androidProjectPath = '$examplePath/android'; final File gradleFile = File(p.join(androidProjectPath, 'gradlew')); if (!gradleFile.existsSync()) { final int compileCode = await runFlutterBuild(examplePath, 'apk'); if (compileCode != 0) { return compileCode; } } return runGradleBuild(androidProjectPath, 'testDebugUnitTest'); } Future<int> _runAndroidKotlinIntegrationTests() async { return _runMobileIntegrationTests('Android', _testPluginRelativePath); } Future<int> _runMobileIntegrationTests( String platform, String testPluginPath) async { final String? device = await getDeviceForPlatform(platform.toLowerCase()); if (device == null) { print('No $platform device available. Attach an $platform device or start ' 'an emulator/simulator to run integration tests'); return _noDeviceAvailableExitCode; } final String examplePath = './$testPluginPath/example'; return runFlutterCommand( examplePath, 'test', <String>[_integrationTestFileRelativePath, '-d', device], ); } Future<int> _runDartUnitTests() async { int exitCode = await runProcess('dart', <String>['analyze', 'bin']); if (exitCode != 0) { return exitCode; } exitCode = await runProcess('dart', <String>['analyze', 'lib']); if (exitCode != 0) { return exitCode; } exitCode = await runProcess('dart', <String>['test']); return exitCode; } Future<int> _analyzeFlutterUnitTests(String flutterUnitTestsPath) async { final String messagePath = '$flutterUnitTestsPath/lib/message.gen.dart'; final String messageTestPath = '$flutterUnitTestsPath/test/message_test.dart'; final int generateTestCode = await runPigeon( input: 'pigeons/message.dart', dartOut: messagePath, dartTestOut: messageTestPath, ); if (generateTestCode != 0) { return generateTestCode; } final int analyzeCode = await runFlutterCommand(flutterUnitTestsPath, 'analyze'); if (analyzeCode != 0) { return analyzeCode; } // Delete these files that were just generated to help with the analyzer step. File(messagePath).deleteSync(); File(messageTestPath).deleteSync(); return 0; } Future<int> _runFlutterUnitTests() async { const String flutterUnitTestsPath = 'platform_tests/shared_test_plugin_code'; final int analyzeCode = await _analyzeFlutterUnitTests(flutterUnitTestsPath); if (analyzeCode != 0) { return analyzeCode; } final int testCode = await runFlutterCommand(flutterUnitTestsPath, 'test'); if (testCode != 0) { return testCode; } return 0; } Future<int> _runIOSObjCUnitTests() async { return _runIOSPluginUnitTests(_alternateLanguageTestPluginRelativePath); } Future<int> _runIOSObjCIntegrationTests() async { final String? device = await getDeviceForPlatform('ios'); if (device == null) { print('No iOS device available. Attach an iOS device or start ' 'a simulator to run integration tests'); return _noDeviceAvailableExitCode; } const String examplePath = './$_alternateLanguageTestPluginRelativePath/example'; return runFlutterCommand( examplePath, 'test', <String>[_integrationTestFileRelativePath, '-d', device], ); } Future<int> _runMacOSObjCIntegrationTests() async { const String examplePath = './$_alternateLanguageTestPluginRelativePath/example'; return runFlutterCommand( examplePath, 'test', <String>[_integrationTestFileRelativePath, '-d', 'macos'], ); } Future<int> _runMacOSSwiftUnitTests() async { const String examplePath = './$_testPluginRelativePath/example'; final int compileCode = await runFlutterBuild(examplePath, 'macos'); if (compileCode != 0) { return compileCode; } return runXcodeBuild( '$examplePath/macos', extraArguments: <String>[ '-configuration', 'Debug', 'test', ], ); } Future<int> _runMacOSSwiftIntegrationTests() async { const String examplePath = './$_testPluginRelativePath/example'; return runFlutterCommand( examplePath, 'test', <String>[_integrationTestFileRelativePath, '-d', 'macos'], ); } Future<int> _runIOSSwiftUnitTests() async { return _runIOSPluginUnitTests(_testPluginRelativePath); } Future<int> _runIOSPluginUnitTests(String testPluginPath) async { final String examplePath = './$testPluginPath/example'; final int compileCode = await runFlutterBuild( examplePath, 'ios', flags: <String>['--simulator', '--no-codesign'], ); if (compileCode != 0) { return compileCode; } const String deviceName = 'Pigeon-Test-iPhone'; const String deviceType = 'com.apple.CoreSimulator.SimDeviceType.iPhone-14'; const String deviceRuntime = 'com.apple.CoreSimulator.SimRuntime.iOS-17-0'; const String deviceOS = '17.0'; await _createSimulator(deviceName, deviceType, deviceRuntime); return runXcodeBuild( '$examplePath/ios', sdk: 'iphonesimulator', destination: 'platform=iOS Simulator,name=$deviceName,OS=$deviceOS', extraArguments: <String>['test'], ).whenComplete(() => _deleteSimulator(deviceName)); } Future<int> _createSimulator( String deviceName, String deviceType, String deviceRuntime, ) async { // Delete any existing simulators with the same name until it fails. It will // fail once there are no simulators with the name. Having more than one may // cause issues when builds target the device. int deleteResult = 0; while (deleteResult == 0) { deleteResult = await _deleteSimulator(deviceName); } return runProcess( 'xcrun', <String>[ 'simctl', 'create', deviceName, deviceType, deviceRuntime, ], streamOutput: false, logFailure: true, ); } Future<int> _deleteSimulator(String deviceName) async { return runProcess( 'xcrun', <String>[ 'simctl', 'delete', deviceName, ], streamOutput: false, ); } Future<int> _runIOSSwiftIntegrationTests() async { return _runMobileIntegrationTests('iOS', _testPluginRelativePath); } Future<int> _runWindowsUnitTests() async { const String examplePath = './$_testPluginRelativePath/example'; final int compileCode = await runFlutterBuild(examplePath, 'windows'); if (compileCode != 0) { return compileCode; } // Depending on the Flutter version, the build output path is different. To // handle both master and stable, and to future-proof against the changes // that will happen in https://github.com/flutter/flutter/issues/129807 // - Try arm64, to future-proof against arm64 support. // - Try x64, to cover pre-arm64 support on arm64 hosts, as well as x64 hosts // running newer versions of Flutter. // - Fall back to the pre-arch path, to support running against stable. // TODO(stuartmorgan): Remove all this when these tests no longer need to // support a version of Flutter without // https://github.com/flutter/flutter/issues/129807, and just construct the // version of the path with the current architecture. const String buildDirBase = '$examplePath/build/windows'; const String buildRelativeBinaryPath = 'plugins/test_plugin/Debug/test_plugin_test.exe'; const String arm64Path = '$buildDirBase/arm64/$buildRelativeBinaryPath'; const String x64Path = '$buildDirBase/x64/$buildRelativeBinaryPath'; const String oldPath = '$buildDirBase/$buildRelativeBinaryPath'; if (File(arm64Path).existsSync()) { return runProcess(arm64Path, <String>[]); } else if (File(x64Path).existsSync()) { return runProcess(x64Path, <String>[]); } else { return runProcess(oldPath, <String>[]); } } Future<int> _runWindowsIntegrationTests() async { const String examplePath = './$_testPluginRelativePath/example'; return runFlutterCommand( examplePath, 'test', <String>[_integrationTestFileRelativePath, '-d', 'windows'], ); } Future<int> _runCommandLineTests() async { final Directory tempDir = Directory.systemTemp.createTempSync('pigeon'); final String tempOutput = p.join(tempDir.path, 'pigeon_output'); const String pigeonScript = 'bin/pigeon.dart'; final String snapshot = p.join(tempDir.path, 'pigeon.dart.dill'); // Precompile to make the repeated calls faster. if (await runProcess('dart', <String>[ '--snapshot-kind=kernel', '--snapshot=$snapshot', pigeonScript ]) != 0) { print('Unable to generate $snapshot from $pigeonScript'); return 1; } final List<List<String>> testArguments = <List<String>>[ // Test with no arguments. <String>[], // Test one_language flag. With this flag specified, java_out can be // generated without dart_out. <String>[ '--input', 'pigeons/message.dart', '--one_language', '--java_out', tempOutput ], // Test dartOut in ConfigurePigeon overrides output. <String>['--input', 'pigeons/configure_pigeon_dart_out.dart'], // Make sure AST generation exits correctly. <String>[ '--input', 'pigeons/message.dart', '--one_language', '--ast_out', tempOutput ], // Test writing a file in a directory that doesn't exist. <String>[ '--input', 'pigeons/message.dart', '--dart_out', '$tempDir/subdirectory/does/not/exist/message.g.dart', ], ]; int exitCode = 0; for (final List<String> arguments in testArguments) { print('Testing dart $pigeonScript ${arguments.join(', ')}'); exitCode = await runProcess('dart', <String>[snapshot, ...arguments], streamOutput: false, logFailure: true); if (exitCode != 0) { break; } } tempDir.deleteSync(recursive: true); return exitCode; }
packages/packages/pigeon/tool/shared/test_suites.dart/0
{ "file_path": "packages/packages/pigeon/tool/shared/test_suites.dart", "repo_id": "packages", "token_count": 5211 }
1,032
<?xml version="1.0" encoding="utf-8"?> <layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@android:color/white" /> </layer-list>
packages/packages/platform/example/android/app/src/main/res/drawable/launch_background.xml/0
{ "file_path": "packages/packages/platform/example/android/app/src/main/res/drawable/launch_background.xml", "repo_id": "packages", "token_count": 68 }
1,033
#include "Generated.xcconfig"
packages/packages/platform/example/ios/Flutter/Debug.xcconfig/0
{ "file_path": "packages/packages/platform/example/ios/Flutter/Debug.xcconfig", "repo_id": "packages", "token_count": 12 }
1,034
name: pointer_interceptor_platform_interface description: "A common platform interface for the pointer_interceptor plugin." repository: https://github.com/flutter/packages/tree/main/packages/pointer_interceptor/pointer_interceptor_platform_interface issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+pointer_interceptor%22 version: 0.10.0+1 environment: sdk: '>=3.1.0 <4.0.0' flutter: '>=3.13.0' dependencies: flutter: sdk: flutter plugin_platform_interface: ^2.1.7 dev_dependencies: flutter_test: sdk: flutter topics: - widgets - platform-views - pointer-interceptor
packages/packages/pointer_interceptor/pointer_interceptor_platform_interface/pubspec.yaml/0
{ "file_path": "packages/packages/pointer_interceptor/pointer_interceptor_platform_interface/pubspec.yaml", "repo_id": "packages", "token_count": 240 }
1,035
// 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; /// A wrapper around an [io.Process] class that adds some convenience methods. class ProcessWrapper implements io.Process { /// Constructs a [ProcessWrapper] object that delegates to the specified /// underlying object. ProcessWrapper(this._delegate) : _stdout = StreamController<List<int>>(), _stderr = StreamController<List<int>>(), _stdoutDone = Completer<void>(), _stderrDone = Completer<void>() { _monitorStdioStream(_delegate.stdout, _stdout, _stdoutDone); _monitorStdioStream(_delegate.stderr, _stderr, _stderrDone); } final io.Process _delegate; final StreamController<List<int>> _stdout; final StreamController<List<int>> _stderr; final Completer<void> _stdoutDone; final Completer<void> _stderrDone; /// Listens to the specified [stream], repeating events on it via /// [controller], and completing [completer] once the stream is done. void _monitorStdioStream( Stream<List<int>> stream, StreamController<List<int>> controller, Completer<void> completer, ) { stream.listen( controller.add, onError: controller.addError, onDone: () { controller.close(); completer.complete(); }, ); } @override Future<int> get exitCode => _delegate.exitCode; /// A [Future] that completes when the process has exited and its standard /// output and error streams have closed. /// /// This exists as an alternative to [exitCode], which does not guarantee /// that the stdio streams have closed (it is possible for the exit code to /// be available before stdout and stderr have closed). /// /// The future returned here will complete with the exit code of the process. Future<int> get done async { late int result; await Future.wait<void>(<Future<void>>[ _stdoutDone.future, _stderrDone.future, _delegate.exitCode.then((int value) { result = value; }), ]); return result; } @override bool kill([io.ProcessSignal signal = io.ProcessSignal.sigterm]) { return _delegate.kill(signal); } @override int get pid => _delegate.pid; @override io.IOSink get stdin => _delegate.stdin; @override Stream<List<int>> get stdout => _stdout.stream; @override Stream<List<int>> get stderr => _stderr.stream; }
packages/packages/process/lib/src/interface/process_wrapper.dart/0
{ "file_path": "packages/packages/process/lib/src/interface/process_wrapper.dart", "repo_id": "packages", "token_count": 879 }
1,036
// 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.quickactions; import static io.flutter.plugins.quickactions.QuickActions.EXTRA_ACTION; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.ShortcutManager; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import io.flutter.embedding.engine.plugins.FlutterPlugin.FlutterPluginBinding; import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; import io.flutter.plugin.common.BinaryMessenger; import java.nio.ByteBuffer; import org.junit.Test; public class QuickActionsTest { private static class TestBinaryMessenger implements BinaryMessenger { public boolean launchActionCalled; @Override public void send(@NonNull String channel, @Nullable ByteBuffer message) { send(channel, message, null); } @Override public void send( @NonNull String channel, @Nullable ByteBuffer message, @Nullable final BinaryReply callback) { if (channel.contains("launchAction")) { launchActionCalled = true; } } @Override public void setMessageHandler(@NonNull String channel, @Nullable BinaryMessageHandler handler) { // Do nothing. } } static final int SUPPORTED_BUILD = 25; static final int UNSUPPORTED_BUILD = 24; static final String SHORTCUT_TYPE = "action_one"; @Test public void canAttachToEngine() { final TestBinaryMessenger testBinaryMessenger = new TestBinaryMessenger(); final FlutterPluginBinding mockPluginBinding = mock(FlutterPluginBinding.class); when(mockPluginBinding.getBinaryMessenger()).thenReturn(testBinaryMessenger); final QuickActionsPlugin plugin = new QuickActionsPlugin(); plugin.onAttachedToEngine(mockPluginBinding); } @Test public void onAttachedToActivity_buildVersionSupported_invokesLaunchMethod() throws NoSuchFieldException, IllegalAccessException { // Arrange final TestBinaryMessenger testBinaryMessenger = new TestBinaryMessenger(); final QuickActionsPlugin plugin = new QuickActionsPlugin((version) -> SUPPORTED_BUILD >= version); setUpMessengerAndFlutterPluginBinding(testBinaryMessenger, plugin); final Intent mockIntent = createMockIntentWithQuickActionExtra(); final Activity mockMainActivity = mock(Activity.class); when(mockMainActivity.getIntent()).thenReturn(mockIntent); final ActivityPluginBinding mockActivityPluginBinding = mock(ActivityPluginBinding.class); when(mockActivityPluginBinding.getActivity()).thenReturn(mockMainActivity); final Context mockContext = mock(Context.class); when(mockMainActivity.getApplicationContext()).thenReturn(mockContext); final ShortcutManager mockShortcutManager = mock(ShortcutManager.class); when(mockContext.getSystemService(Context.SHORTCUT_SERVICE)).thenReturn(mockShortcutManager); plugin.onAttachedToActivity(mockActivityPluginBinding); // Act plugin.onAttachedToActivity(mockActivityPluginBinding); // Assert assertTrue(testBinaryMessenger.launchActionCalled); } @Test public void onNewIntent_buildVersionUnsupported_doesNotInvokeMethod() { // Arrange final TestBinaryMessenger testBinaryMessenger = new TestBinaryMessenger(); final QuickActionsPlugin plugin = new QuickActionsPlugin((version) -> UNSUPPORTED_BUILD >= version); setUpMessengerAndFlutterPluginBinding(testBinaryMessenger, plugin); final Intent mockIntent = createMockIntentWithQuickActionExtra(); // Act final boolean onNewIntentReturn = plugin.onNewIntent(mockIntent); // Assert assertFalse(testBinaryMessenger.launchActionCalled); assertFalse(onNewIntentReturn); } @Test public void onNewIntent_buildVersionSupported_invokesLaunchMethod() { // Arrange final TestBinaryMessenger testBinaryMessenger = new TestBinaryMessenger(); final QuickActionsPlugin plugin = new QuickActionsPlugin((version) -> SUPPORTED_BUILD >= version); setUpMessengerAndFlutterPluginBinding(testBinaryMessenger, plugin); final Intent mockIntent = createMockIntentWithQuickActionExtra(); final Activity mockMainActivity = mock(Activity.class); when(mockMainActivity.getIntent()).thenReturn(mockIntent); final ActivityPluginBinding mockActivityPluginBinding = mock(ActivityPluginBinding.class); when(mockActivityPluginBinding.getActivity()).thenReturn(mockMainActivity); final Context mockContext = mock(Context.class); when(mockMainActivity.getApplicationContext()).thenReturn(mockContext); final ShortcutManager mockShortcutManager = mock(ShortcutManager.class); when(mockContext.getSystemService(Context.SHORTCUT_SERVICE)).thenReturn(mockShortcutManager); plugin.onAttachedToActivity(mockActivityPluginBinding); // Act final boolean onNewIntentReturn = plugin.onNewIntent(mockIntent); // Assert assertTrue(testBinaryMessenger.launchActionCalled); assertFalse(onNewIntentReturn); } private void setUpMessengerAndFlutterPluginBinding( TestBinaryMessenger testBinaryMessenger, QuickActionsPlugin plugin) { final FlutterPluginBinding mockPluginBinding = mock(FlutterPluginBinding.class); when(mockPluginBinding.getBinaryMessenger()).thenReturn(testBinaryMessenger); plugin.onAttachedToEngine(mockPluginBinding); } private Intent createMockIntentWithQuickActionExtra() { final Intent mockIntent = mock(Intent.class); when(mockIntent.hasExtra(EXTRA_ACTION)).thenReturn(true); when(mockIntent.getStringExtra(EXTRA_ACTION)).thenReturn(QuickActionsTest.SHORTCUT_TYPE); return mockIntent; } }
packages/packages/quick_actions/quick_actions_android/android/src/test/java/io/flutter/plugins/quickactions/QuickActionsTest.java/0
{ "file_path": "packages/packages/quick_actions/quick_actions_android/android/src/test/java/io/flutter/plugins/quickactions/QuickActionsTest.java", "repo_id": "packages", "token_count": 1913 }
1,037
# Hello World for RFW This example shows the simplest use of the `RemoteWidget` widget. In this example, the "remote" widget is hard-coded into the application.
packages/packages/rfw/example/hello/README.md/0
{ "file_path": "packages/packages/rfw/example/hello/README.md", "repo_id": "packages", "token_count": 41 }
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. import 'package:flutter/widgets.dart'; /// For clarity, this example uses the text representation of the sample remote /// widget library, and parses it locally. To do this, [parseLibraryFile] is /// used. In production, this is strongly discouraged since it is 10x slower /// than using [decodeLibraryBlob] to parse the binary version of the format. import 'package:rfw/formats.dart' show parseLibraryFile; import 'package:rfw/rfw.dart'; void main() { runApp(const Example()); } // The "#docregion" comment helps us keep this code in sync with the // excerpt in the rfw package's README.md file. // // #docregion Example class Example extends StatefulWidget { const Example({super.key}); @override State<Example> createState() => _ExampleState(); } class _ExampleState extends State<Example> { final Runtime _runtime = Runtime(); final DynamicContent _data = DynamicContent(); @override void initState() { super.initState(); _update(); } @override void reassemble() { // This function causes the Runtime to be updated any time the app is // hot reloaded, so that changes to _createLocalWidgets can be seen // during development. This function has no effect in production. super.reassemble(); _update(); } static WidgetLibrary _createLocalWidgets() { return LocalWidgetLibrary(<String, LocalWidgetBuilder>{ 'GreenBox': (BuildContext context, DataSource source) { return ColoredBox( color: const Color(0xFF002211), child: source.child(<Object>['child']), ); }, 'Hello': (BuildContext context, DataSource source) { return Center( child: Text( 'Hello, ${source.v<String>(<Object>["name"])}!', textDirection: TextDirection.ltr, ), ); }, }); } static const LibraryName localName = LibraryName(<String>['local']); static const LibraryName remoteName = LibraryName(<String>['remote']); void _update() { _runtime.update(localName, _createLocalWidgets()); // Normally we would obtain the remote widget library in binary form from a // server, and decode it with [decodeLibraryBlob] rather than parsing the // text version using [parseLibraryFile]. However, to make it easier to // play with this sample, this uses the slower text format. _runtime.update(remoteName, parseLibraryFile(''' import local; widget root = GreenBox( child: Hello(name: "World"), ); ''')); } @override Widget build(BuildContext context) { return RemoteWidget( runtime: _runtime, data: _data, widget: const FullyQualifiedWidgetName(remoteName, 'root'), onEvent: (String name, DynamicMap arguments) { debugPrint('user triggered event "$name" with data: $arguments'); }, ); } } // #enddocregion Example
packages/packages/rfw/example/local/lib/main.dart/0
{ "file_path": "packages/packages/rfw/example/local/lib/main.dart", "repo_id": "packages", "token_count": 1016 }
1,039
#include "../../Flutter/Flutter-Release.xcconfig" #include "Warnings.xcconfig"
packages/packages/rfw/example/wasm/macos/Runner/Configs/Release.xcconfig/0
{ "file_path": "packages/packages/rfw/example/wasm/macos/Runner/Configs/Release.xcconfig", "repo_id": "packages", "token_count": 32 }
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. // There's a lot of <Object>[] lists in this file so to avoid making this // file even less readable we relax our usual stance on verbose typing. // ignore_for_file: always_specify_types // This file is hand-formatted. // ignore: unnecessary_import, see https://github.com/flutter/flutter/pull/138881 import 'dart:ui' show FontFeature; import 'package:flutter/gestures.dart' show DragStartBehavior; import 'package:flutter/material.dart' show Icons; import 'package:flutter/widgets.dart'; import 'argument_decoders.dart'; import 'runtime.dart'; /// A widget library for Remote Flutter Widgets that defines widgets that are /// implemented on the client in terms of Flutter widgets from the `widgets` /// Dart library. /// /// The following widgets are implemented: /// /// * [Align] /// * [AspectRatio] /// * [Center] /// * [ClipRRect] /// * [ColoredBox] /// * [Column] /// * [Container] (actually uses [AnimatedContainer]) /// * [DefaultTextStyle] /// * [Directionality] /// * [Expanded] /// * [FittedBox] /// * [FractionallySizedBox] /// * [GestureDetector] /// * [GridView] (actually uses [GridView.builder]) /// * [Icon] /// * [IconTheme] /// * [IntrinsicHeight] /// * [IntrinsicWidth] /// * [Image] (see below) /// * [ListBody] /// * [ListView] (actually uses [ListView.builder]) /// * [Opacity] (actually uses [AnimatedOpacity]) /// * [Padding] (actually uses [AnimatedPadding]) /// * [Placeholder] /// * [Positioned] (actually uses [AnimatedPositionedDirectional]) /// * [Rotation] (actually uses [AnimatedRotation]) /// * [Row] /// * [SafeArea] /// * [Scale] (actually uses [AnimatedScale]) /// * [SingleChildScrollView] /// * [SizedBox] /// * `SizedBoxExpand` (actually [SizedBox.expand]) /// * `SizedBoxShrink` (actually [SizedBox.shrink]) /// * [Spacer] /// * [Stack] /// * [Text] /// * [Wrap] /// /// For each, every parameter is implemented using the same name. Parameters /// that take structured types are represented using maps, with each named /// parameter of that type's default constructor represented by a key, with the /// following notable caveats and exceptions: /// /// * Enums are represented as strings with the unqualified name of the value. /// For example, [MainAxisAlignment.start] is represented as the string /// `"start"`. /// /// * Types that have multiple subclasses (or multiple very unrelated /// constructors, like [ColorFilter]) are represented as maps where the `type` /// key specifies the type. Typically these have an extension mechanism. /// /// * Matrices are represented as **column-major** flattened arrays. [Matrix4] /// values must have exactly 16 doubles in the array. /// /// * [AlignmentGeometry] values can be represented either as `{x: ..., y: /// ...}` for a non-directional variant or `{start: ..., y: ...}` for a /// directional variant. /// /// * [BoxBorder] instances are defined as arrays of [BorderSide] maps. If the /// array has length 1, then that value is used for all four sides. Two /// values become the horizontal and vertical sides respectively. Three /// values become the start, top-and-bottom, and end respectively. Four /// values become the start, top, end, and bottom respectively. /// /// * [BorderRadiusGeometry] values work similarly to [BoxBorder], as an array /// of [Radius] values. If the array has one value, it's used for all corners. /// With two values, the first becomes the `topStart` and `bottomStart` /// corners and the second the `topEnd` and `bottomEnd`. With three, the /// values are used for `topStart`, `topEnd`-and-`bottomEnd`, and /// `bottomStart` respectively. Four values map to the `topStart`, `topEnd`, /// `bottomStart`, and `bottomEnd` respectively. /// /// * [Color] values are represented as integers. The hex literal values are /// most convenient for this, the alpha, red, green, and blue channels map to /// the 32 bit hex integer as 0xAARRGGBB. /// /// * [ColorFilter] is represented as a map with a `type` key that matches the /// constructor name (e.g. `linearToSrgbGamma`). The `matrix` version uses /// the `matrix` key for the matrix, expecting a 20-value array. The `mode` /// version expects a `color` key for the color (defaults to black) and a /// `blendMode` key for the blend mode (defaults to [BlendMode.srcOver]). /// Other types are looked up in [ArgumentDecoders.colorFilterDecoders]. /// /// * [Curve] values are represented as a string giving the kind of curve from /// the predefined [Curves], e.g. `easeInOutCubicEmphasized`. More types may /// be added using [ArgumentDecoders.curveDecoders]. /// /// * The types supported for [Decoration] are `box` for [BoxDecoration], /// `flutterLogo` for [FlutterLogoDecoration], and `shape` for /// [ShapeDecoration]. More types can be added with [decorationDecoders]. /// /// * [DecorationImage] expects a `source` key that gives either an absolute /// URL (to use a [NetworkImage]) or the name of an asset in the client /// binary (to use [AssetImage]). In the case of a URL, the `scale` key gives /// the scale to pass to the [NetworkImage] constructor. /// [DecorationImage.onError] is supported as an event handler with arguments /// giving the stringified exception and stack trace. Values can be added to /// [ArgumentDecoders.imageProviderDecoders] to override the behavior described here. /// /// * [Duration] is represented by an integer giving milliseconds. /// /// * [EdgeInsetsGeometry] values work like [BoxBorder], with each value in the /// array being a double rather than a map. /// /// * [FontFeature] values are a map with a `feature` key and a `value` key. /// The `value` defaults to 1. (Technically the `feature` defaults to `NONE`, /// too, but that's hardly useful.) /// /// * The [dart:ui.Gradient] and [painting.Gradient] types are both represented /// as a map with a type that is either `linear` (for [LinearGradient]), /// `radial` (for [RadialGradient]), or `sweep` (for [SweepGradient]), using /// the conventions from the [painting.Gradient] version. The `transform` /// property on these objects is not currently supported. New gradient types /// can be implemented using [ArgumentDecoders.gradientDecoders]. /// /// * The [GridDelegate] type is represented as a map with a `type` key that is /// either `fixedCrossAxisCount` for /// [SliverGridDelegateWithFixedCrossAxisCount] or `maxCrossAxisExtent` for /// [SliverGridDelegateWithMaxCrossAxisExtent]. New delegate types can be /// supported using [ArgumentDecoders.gridDelegateDecoders]. /// /// * [IconData] is represented as a map with an `icon` key giving the /// [IconData.codePoint] (and corresponding keys for the other parameters of /// the [IconData] constructor). To determine the values to use for icons in /// the MaterialIcons font, see how the icons are defined in [Icons]. For /// example, [Icons.flutter_dash] is `IconData(0xe2a0, fontFamily: /// 'MaterialIcons')` so it would be represented here as `{ icon: 0xE2A0, /// fontFamily: "MaterialIcons" }`. (The client must have the font as a /// defined asset.) /// /// * [Locale] values are defined as a string in the form `languageCode`, /// `languageCode-countryCode`, or /// `languageCode-scriptCode-countryCode-ignoredSubtags`. The string is split /// on hyphens. /// /// * [MaskFilter] is represented as a map with a `type` key that must be /// `blur`; only [MaskFilter.blur] is supported. (The other keys must be /// `style`, the [BlurStyle], and `sigma`.) /// /// * [Offset]s are a map with an `x` key and a `y` key. /// /// * [Paint] objects are represented as maps; each property of [Paint] is a /// key as if there was a constructor that could set all of [Paint]'s /// properties with named parameters. In principle all properties are /// supported, though since [Paint] is only used as part of /// [painting.TextStyle.background] and [painting.TextStyle.foreground], in /// practice some of the properties are ignored since they would be no-ops /// (e.g. `invertColors`). /// /// * [Radius] is represented as a map with an `x` value and optionally a `y` /// value; if the `y` value is absent, the `x` value is used for both. /// /// * [Rect] values are represented as an array with four doubles, giving the /// x, y, width, and height respectively. /// /// * [ShapeBorder] values are represented as either maps with a `type` _or_ as /// an array of [ShapeBorder] values. In the array case, the values are /// reduced together using [ShapeBorder.+]. When represented as maps, the /// type must be one of `box` ([BoxBorder]), `beveled` /// ([BeveledRectangleBorder]), `circle` ([CircleBorder]), `continuous` /// ([ContinuousRectangleBorder]), `rounded` ([RoundedRectangleBorder]), or /// `stadium` ([StadiumBorder]). In the case of `box`, there must be a /// `sides` key whose value is an array that is interpreted as per /// [BoxBorder] above. Support for new types can be added using the /// [ArgumentDecoders.shapeBorderDecoders] map. /// /// * [Shader] values are a map with a `type` that is either `linear`, /// `radial`, or `sweep`; in each case, the data is interpreted as per the /// [Gradient] case above, except that the gradient is specifically applied /// to a [Rect] given by the `rect` key and a [TextDirection] given by the /// `textDirection` key. New shader types can be added using /// [ArgumentDecoders.shaderDecoders]. /// /// * [TextDecoration] is represented either as an array of [TextDecoration] /// values (combined via [TextDecoration.combine]) or a string which matches /// the name of one of the [TextDecoration] constants (e.g. `underline`). /// /// * [VisualDensity] is either represented as a string which matches one of the /// predefined values (`adaptivePlatformDensity`, `comfortable`, etc), or as /// a map with keys `horizontal` and `vertical` to define a custom density. /// /// Some of the widgets have special considerations: /// /// * [Image] does not support the builder callbacks or the [Image.opacity] /// parameter (because builders are code and code can't be represented in RFW /// arguments). The map should have a `source` key that is interpreted as /// described above for [DecorationImage]. If the `source` is omitted, an /// [AssetImage] with the name `error.png` is used instead (which will likely /// fail unless such an asset is declared in the client). /// /// * Parameters of type [ScrollController] and [ScrollPhysics] are not /// supported, because they can't really be exposed to declarative code (they /// expect to be configured using code that implements delegates or that /// interacts with controllers). /// /// * The [Text] widget's first argument, the string, is represented using the /// key `text`, which must be either a string or an array of strings to be /// concatenated. /// /// One additional widget is defined, [AnimationDefaults]. It has a `duration` /// argument and `curve` argument. It sets the default animation duration and /// curve for widgets in the library that use the animated variants. If absent, /// a default of 200ms and [Curves.fastOutSlowIn] is used. LocalWidgetLibrary createCoreWidgets() => LocalWidgetLibrary(_coreWidgetsDefinitions); // In these widgets we make an effort to expose every single argument available. Map<String, LocalWidgetBuilder> get _coreWidgetsDefinitions => <String, LocalWidgetBuilder>{ // Keep these in alphabetical order and add any new widgets to the list // in the documentation above. 'AnimationDefaults': (BuildContext context, DataSource source) { return AnimationDefaults( duration: ArgumentDecoders.duration(source, ['duration'], context), curve: ArgumentDecoders.curve(source, ['curve'], context), child: source.child(['child']), ); }, 'Align': (BuildContext context, DataSource source) { return AnimatedAlign( duration: ArgumentDecoders.duration(source, ['duration'], context), curve: ArgumentDecoders.curve(source, ['curve'], context), alignment: ArgumentDecoders.alignment(source, ['alignment']) ?? Alignment.center, widthFactor: source.v<double>(['widthFactor']), heightFactor: source.v<double>(['heightFactor']), onEnd: source.voidHandler(['onEnd']), child: source.optionalChild(['child']), ); }, 'AspectRatio': (BuildContext context, DataSource source) { return AspectRatio( aspectRatio: source.v<double>(['aspectRatio']) ?? 1.0, child: source.optionalChild(['child']), ); }, 'Center': (BuildContext context, DataSource source) { return Center( widthFactor: source.v<double>(['widthFactor']), heightFactor: source.v<double>(['heightFactor']), child: source.optionalChild(['child']), ); }, 'ClipRRect': (BuildContext context, DataSource source) { return ClipRRect( borderRadius: ArgumentDecoders.borderRadius(source, ['borderRadius']) ?? BorderRadius.zero, // CustomClipper<RRect> clipper, clipBehavior: ArgumentDecoders.enumValue<Clip>(Clip.values, source, ['clipBehavior']) ?? Clip.antiAlias, child: source.optionalChild(['child']), ); }, 'ColoredBox': (BuildContext context, DataSource source) { return ColoredBox( color: ArgumentDecoders.color(source, ['color']) ?? const Color(0xFF000000), child: source.optionalChild(['child']), ); }, 'Column': (BuildContext context, DataSource source) { return Column( mainAxisAlignment: ArgumentDecoders.enumValue<MainAxisAlignment>(MainAxisAlignment.values, source, ['mainAxisAlignment']) ?? MainAxisAlignment.start, mainAxisSize: ArgumentDecoders.enumValue<MainAxisSize>(MainAxisSize.values, source, ['mainAxisSize']) ?? MainAxisSize.max, crossAxisAlignment: ArgumentDecoders.enumValue<CrossAxisAlignment>(CrossAxisAlignment.values, source, ['crossAxisAlignment']) ?? CrossAxisAlignment.center, textDirection: ArgumentDecoders.enumValue<TextDirection>(TextDirection.values, source, ['textDirection']), verticalDirection: ArgumentDecoders.enumValue<VerticalDirection>(VerticalDirection.values, source, ['verticalDirection']) ?? VerticalDirection.down, textBaseline: ArgumentDecoders.enumValue<TextBaseline>(TextBaseline.values, source, ['textBaseline']), children: source.childList(['children']), ); }, 'Container': (BuildContext context, DataSource source) { return AnimatedContainer( duration: ArgumentDecoders.duration(source, ['duration'], context), curve: ArgumentDecoders.curve(source, ['curve'], context), alignment: ArgumentDecoders.alignment(source, ['alignment']), padding: ArgumentDecoders.edgeInsets(source, ['padding']), color: ArgumentDecoders.color(source, ['color']), decoration: ArgumentDecoders.decoration(source, ['decoration']), foregroundDecoration: ArgumentDecoders.decoration(source, ['foregroundDecoration']), width: source.v<double>(['width']), height: source.v<double>(['height']), constraints: ArgumentDecoders.boxConstraints(source, ['constraints']), margin: ArgumentDecoders.edgeInsets(source, ['margin']), transform: ArgumentDecoders.matrix(source, ['transform']), transformAlignment: ArgumentDecoders.alignment(source, ['transformAlignment']), clipBehavior: ArgumentDecoders.enumValue<Clip>(Clip.values, source, ['clipBehavior']) ?? Clip.none, onEnd: source.voidHandler(['onEnd']), child: source.optionalChild(['child']), ); }, 'DefaultTextStyle': (BuildContext context, DataSource source) { return AnimatedDefaultTextStyle( duration: ArgumentDecoders.duration(source, ['duration'], context), curve: ArgumentDecoders.curve(source, ['curve'], context), style: ArgumentDecoders.textStyle(source, ['style']) ?? const TextStyle(), textAlign: ArgumentDecoders.enumValue<TextAlign>(TextAlign.values, source, ['textAlign']), softWrap: source.v<bool>(['softWrap']) ?? true, overflow: ArgumentDecoders.enumValue<TextOverflow>(TextOverflow.values, source, ['overflow']) ?? TextOverflow.clip, maxLines: source.v<int>(['maxLines']), textWidthBasis: ArgumentDecoders.enumValue<TextWidthBasis>(TextWidthBasis.values, source, ['textWidthBasis']) ?? TextWidthBasis.parent, textHeightBehavior: ArgumentDecoders.textHeightBehavior(source, ['textHeightBehavior']), onEnd: source.voidHandler(['onEnd']), child: source.child(['child']), ); }, 'Directionality': (BuildContext context, DataSource source) { return Directionality( textDirection: ArgumentDecoders.enumValue<TextDirection>(TextDirection.values, source, ['textDirection']) ?? TextDirection.ltr, child: source.child(['child']), ); }, 'Expanded': (BuildContext context, DataSource source) { return Expanded( flex: source.v<int>(['flex']) ?? 1, child: source.child(['child']), ); }, 'FittedBox': (BuildContext context, DataSource source) { return FittedBox( fit: ArgumentDecoders.enumValue<BoxFit>(BoxFit.values, source, ['fit']) ?? BoxFit.contain, alignment: ArgumentDecoders.alignment(source, ['alignment']) ?? Alignment.center, clipBehavior: ArgumentDecoders.enumValue<Clip>(Clip.values, source, ['clipBehavior']) ?? Clip.none, child: source.optionalChild(['child']), ); }, 'FractionallySizedBox': (BuildContext context, DataSource source) { return FractionallySizedBox( alignment: ArgumentDecoders.alignment(source, ['alignment']) ?? Alignment.center, widthFactor: source.v<double>(['widthFactor']), heightFactor: source.v<double>(['heightFactor']), child: source.child(['child']), ); }, 'GestureDetector': (BuildContext context, DataSource source) { return GestureDetector( onTap: source.voidHandler(['onTap']), onTapDown: source.handler(['onTapDown'], (VoidCallback trigger) => (TapDownDetails details) => trigger()), onTapUp: source.handler(['onTapUp'], (VoidCallback trigger) => (TapUpDetails details) => trigger()), onTapCancel: source.voidHandler(['onTapCancel']), onDoubleTap: source.voidHandler(['onDoubleTap']), onLongPress: source.voidHandler(['onLongPress']), behavior: ArgumentDecoders.enumValue<HitTestBehavior>(HitTestBehavior.values, source, ['behavior']), child: source.optionalChild(['child']), ); }, 'GridView': (BuildContext context, DataSource source) { return GridView.builder( scrollDirection: ArgumentDecoders.enumValue<Axis>(Axis.values, source, ['scrollDirection']) ?? Axis.vertical, reverse: source.v<bool>(['reverse']) ?? false, // controller, primary: source.v<bool>(['primary']), // physics, shrinkWrap: source.v<bool>(['shrinkWrap']) ?? false, padding: ArgumentDecoders.edgeInsets(source, ['padding']), gridDelegate: ArgumentDecoders.gridDelegate(source, ['gridDelegate']) ?? const SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2), itemBuilder: (BuildContext context, int index) => source.child(['children', index]), itemCount: source.length(['children']), addAutomaticKeepAlives: source.v<bool>(['addAutomaticKeepAlives']) ?? true, addRepaintBoundaries: source.v<bool>(['addRepaintBoundaries']) ?? true, addSemanticIndexes: source.v<bool>(['addSemanticIndexes']) ?? true, cacheExtent: source.v<double>(['cacheExtent']), semanticChildCount: source.v<int>(['semanticChildCount']), dragStartBehavior: ArgumentDecoders.enumValue<DragStartBehavior>(DragStartBehavior.values, source, ['dragStartBehavior']) ?? DragStartBehavior.start, keyboardDismissBehavior: ArgumentDecoders.enumValue<ScrollViewKeyboardDismissBehavior>(ScrollViewKeyboardDismissBehavior.values, source, ['keyboardDismissBehavior']) ?? ScrollViewKeyboardDismissBehavior.manual, restorationId: source.v<String>(['restorationId']), clipBehavior: ArgumentDecoders.enumValue<Clip>(Clip.values, source, ['clipBehavior']) ?? Clip.hardEdge, ); }, 'Icon': (BuildContext context, DataSource source) { return Icon( ArgumentDecoders.iconData(source, []) ?? Icons.flutter_dash, size: source.v<double>(['size']), color: ArgumentDecoders.color(source, ['color']), semanticLabel: source.v<String>(['semanticLabel']), textDirection: ArgumentDecoders.enumValue<TextDirection>(TextDirection.values, source, ['textDirection']), ); }, 'IconTheme': (BuildContext context, DataSource source) { return IconTheme( data: ArgumentDecoders.iconThemeData(source, []) ?? const IconThemeData(), child: source.child(['child']), ); }, 'IntrinsicHeight': (BuildContext context, DataSource source) { return IntrinsicHeight( child: source.optionalChild(['child']), ); }, 'IntrinsicWidth': (BuildContext context, DataSource source) { return IntrinsicWidth( stepWidth: source.v<double>(['width']), stepHeight: source.v<double>(['height']), child: source.optionalChild(['child']), ); }, 'Image': (BuildContext context, DataSource source) { return Image( image: ArgumentDecoders.imageProvider(source, []) ?? const AssetImage('error.png'), // ImageFrameBuilder? frameBuilder, // ImageLoadingBuilder? loadingBuilder, // ImageErrorWidgetBuilder? errorBuilder, semanticLabel: source.v<String>(['semanticLabel']), excludeFromSemantics: source.v<bool>(['excludeFromSemantics']) ?? false, width: source.v<double>(['width']), height: source.v<double>(['height']), color: ArgumentDecoders.color(source, ['color']), // Animation<double>? opacity, colorBlendMode: ArgumentDecoders.enumValue<BlendMode>(BlendMode.values, source, ['blendMode']), fit: ArgumentDecoders.enumValue<BoxFit>(BoxFit.values, source, ['fit']), alignment: ArgumentDecoders.alignment(source, ['alignment']) ?? Alignment.center, repeat: ArgumentDecoders.enumValue<ImageRepeat>(ImageRepeat.values, source, ['repeat']) ?? ImageRepeat.noRepeat, centerSlice: ArgumentDecoders.rect(source, ['centerSlice']), matchTextDirection: source.v<bool>(['matchTextDirection']) ?? false, gaplessPlayback: source.v<bool>(['gaplessPlayback']) ?? false, isAntiAlias: source.v<bool>(['isAntiAlias']) ?? false, filterQuality: ArgumentDecoders.enumValue<FilterQuality>(FilterQuality.values, source, ['filterQuality']) ?? FilterQuality.low, ); }, 'ListBody': (BuildContext context, DataSource source) { return ListBody( mainAxis: ArgumentDecoders.enumValue<Axis>(Axis.values, source, ['mainAxis']) ?? Axis.vertical, reverse: source.v<bool>(['reverse']) ?? false, children: source.childList(['children']), ); }, 'ListView': (BuildContext context, DataSource source) { return ListView.builder( scrollDirection: ArgumentDecoders.enumValue<Axis>(Axis.values, source, ['scrollDirection']) ?? Axis.vertical, reverse: source.v<bool>(['reverse']) ?? false, // ScrollController? controller, primary: source.v<bool>(['primary']), // ScrollPhysics? physics, shrinkWrap: source.v<bool>(['shrinkWrap']) ?? false, padding: ArgumentDecoders.edgeInsets(source, ['padding']), itemExtent: source.v<double>(['itemExtent']), prototypeItem: source.optionalChild(['prototypeItem']), itemCount: source.length(['children']), itemBuilder: (BuildContext context, int index) => source.child(['children', index]), clipBehavior: ArgumentDecoders.enumValue<Clip>(Clip.values, source, ['clipBehavior']) ?? Clip.hardEdge, addAutomaticKeepAlives: source.v<bool>(['addAutomaticKeepAlives']) ?? true, addRepaintBoundaries: source.v<bool>(['addRepaintBoundaries']) ?? true, addSemanticIndexes: source.v<bool>(['addSemanticIndexes']) ?? true, cacheExtent: source.v<double>(['cacheExtent']), semanticChildCount: source.v<int>(['semanticChildCount']), dragStartBehavior: ArgumentDecoders.enumValue<DragStartBehavior>(DragStartBehavior.values, source, ['dragStartBehavior']) ?? DragStartBehavior.start, keyboardDismissBehavior: ArgumentDecoders.enumValue<ScrollViewKeyboardDismissBehavior>(ScrollViewKeyboardDismissBehavior.values, source, ['keyboardDismissBehavior']) ?? ScrollViewKeyboardDismissBehavior.manual, restorationId: source.v<String>(['restorationId']), ); }, 'Opacity': (BuildContext context, DataSource source) { return AnimatedOpacity( duration: ArgumentDecoders.duration(source, ['duration'], context), curve: ArgumentDecoders.curve(source, ['curve'], context), opacity: source.v<double>(['opacity']) ?? 0.0, onEnd: source.voidHandler(['onEnd']), alwaysIncludeSemantics: source.v<bool>(['alwaysIncludeSemantics']) ?? true, child: source.optionalChild(['child']), ); }, 'Padding': (BuildContext context, DataSource source) { return AnimatedPadding( duration: ArgumentDecoders.duration(source, ['duration'], context), curve: ArgumentDecoders.curve(source, ['curve'], context), padding: ArgumentDecoders.edgeInsets(source, ['padding']) ?? EdgeInsets.zero, onEnd: source.voidHandler(['onEnd']), child: source.optionalChild(['child']), ); }, 'Placeholder': (BuildContext context, DataSource source) { return Placeholder( color: ArgumentDecoders.color(source, ['color']) ?? const Color(0xFF455A64), strokeWidth: source.v<double>(['strokeWidth']) ?? 2.0, fallbackWidth: source.v<double>(['placeholderWidth']) ?? 400.0, fallbackHeight: source.v<double>(['placeholderHeight']) ?? 400.0, ); }, 'Positioned': (BuildContext context, DataSource source) { return AnimatedPositionedDirectional( duration: ArgumentDecoders.duration(source, ['duration'], context), curve: ArgumentDecoders.curve(source, ['curve'], context), start: source.v<double>(['start']), top: source.v<double>(['top']), end: source.v<double>(['end']), bottom: source.v<double>(['bottom']), width: source.v<double>(['width']), height: source.v<double>(['height']), onEnd: source.voidHandler(['onEnd']), child: source.child(['child']), ); }, 'Rotation': (BuildContext context, DataSource source) { return AnimatedRotation( duration: ArgumentDecoders.duration(source, ['duration'], context), curve: ArgumentDecoders.curve(source, ['curve'], context), turns: source.v<double>(['turns']) ?? 0.0, alignment: (ArgumentDecoders.alignment(source, ['alignment']) ?? Alignment.center).resolve(Directionality.of(context)), filterQuality: ArgumentDecoders.enumValue<FilterQuality>(FilterQuality.values, source, ['filterQuality']), onEnd: source.voidHandler(['onEnd']), child: source.optionalChild(['child']), ); }, // The "#docregion" pragma below makes this accessible from the README.md file. // #docregion Row 'Row': (BuildContext context, DataSource source) { return Row( mainAxisAlignment: ArgumentDecoders.enumValue<MainAxisAlignment>(MainAxisAlignment.values, source, ['mainAxisAlignment']) ?? MainAxisAlignment.start, mainAxisSize: ArgumentDecoders.enumValue<MainAxisSize>(MainAxisSize.values, source, ['mainAxisSize']) ?? MainAxisSize.max, crossAxisAlignment: ArgumentDecoders.enumValue<CrossAxisAlignment>(CrossAxisAlignment.values, source, ['crossAxisAlignment']) ?? CrossAxisAlignment.center, textDirection: ArgumentDecoders.enumValue<TextDirection>(TextDirection.values, source, ['textDirection']), verticalDirection: ArgumentDecoders.enumValue<VerticalDirection>(VerticalDirection.values, source, ['verticalDirection']) ?? VerticalDirection.down, textBaseline: ArgumentDecoders.enumValue<TextBaseline>(TextBaseline.values, source, ['textBaseline']), children: source.childList(['children']), ); }, // #enddocregion Row 'SafeArea': (BuildContext context, DataSource source) { return SafeArea( left: source.v<bool>(['left']) ?? true, top: source.v<bool>(['top']) ?? true, right: source.v<bool>(['right']) ?? true, bottom: source.v<bool>(['bottom']) ?? true, minimum: (ArgumentDecoders.edgeInsets(source, ['minimum']) ?? EdgeInsets.zero).resolve(Directionality.of(context)), maintainBottomViewPadding: source.v<bool>(['maintainBottomViewPadding']) ?? false, child: source.child(['child']), ); }, 'Scale': (BuildContext context, DataSource source) { return AnimatedScale( duration: ArgumentDecoders.duration(source, ['duration'], context), curve: ArgumentDecoders.curve(source, ['curve'], context), scale: source.v<double>(['scale']) ?? 1.0, alignment: (ArgumentDecoders.alignment(source, ['alignment']) ?? Alignment.center).resolve(Directionality.of(context)), filterQuality: ArgumentDecoders.enumValue<FilterQuality>(FilterQuality.values, source, ['filterQuality']), onEnd: source.voidHandler(['onEnd']), child: source.optionalChild(['child']), ); }, 'SingleChildScrollView': (BuildContext context, DataSource source) { return SingleChildScrollView( scrollDirection: ArgumentDecoders.enumValue<Axis>(Axis.values, source, ['scrollDirection']) ?? Axis.vertical, reverse: source.v<bool>(['reverse']) ?? false, padding: ArgumentDecoders.edgeInsets(source, ['padding']), primary: source.v<bool>(['primary']) ?? true, dragStartBehavior: ArgumentDecoders.enumValue<DragStartBehavior>(DragStartBehavior.values, source, ['dragStartBehavior']) ?? DragStartBehavior.start, clipBehavior: ArgumentDecoders.enumValue<Clip>(Clip.values, source, ['clipBehavior']) ?? Clip.hardEdge, restorationId: source.v<String>(['restorationId']), keyboardDismissBehavior: ArgumentDecoders.enumValue<ScrollViewKeyboardDismissBehavior>(ScrollViewKeyboardDismissBehavior.values, source, ['keyboardDismissBehavior']) ?? ScrollViewKeyboardDismissBehavior.manual, // ScrollPhysics? physics, // ScrollController? controller, child: source.optionalChild(['child']), ); }, 'SizedBox': (BuildContext context, DataSource source) { return SizedBox( width: source.v<double>(['width']), height: source.v<double>(['height']), child: source.optionalChild(['child']), ); }, 'SizedBoxExpand': (BuildContext context, DataSource source) { return SizedBox.expand( child: source.optionalChild(['child']), ); }, 'SizedBoxShrink': (BuildContext context, DataSource source) { return SizedBox.shrink( child: source.optionalChild(['child']), ); }, 'Spacer': (BuildContext context, DataSource source) { return Spacer( flex: source.v<int>(['flex']) ?? 1, ); }, 'Stack': (BuildContext context, DataSource source) { return Stack( alignment: ArgumentDecoders.alignment(source, ['alignment']) ?? AlignmentDirectional.topStart, textDirection: ArgumentDecoders.enumValue<TextDirection>(TextDirection.values, source, ['textDirection']), fit: ArgumentDecoders.enumValue<StackFit>(StackFit.values, source, ['fit']) ?? StackFit.loose, clipBehavior: ArgumentDecoders.enumValue<Clip>(Clip.values, source, ['clipBehavior']) ?? Clip.hardEdge, children: source.childList(['children']), ); }, 'Text': (BuildContext context, DataSource source) { String? text = source.v<String>(['text']); if (text == null) { final StringBuffer builder = StringBuffer(); final int count = source.length(['text']); for (int index = 0; index < count; index += 1) { builder.write(source.v<String>(['text', index]) ?? ''); } text = builder.toString(); } final double? textScaleFactor = source.v<double>(['textScaleFactor']); return Text( text, style: ArgumentDecoders.textStyle(source, ['style']), strutStyle: ArgumentDecoders.strutStyle(source, ['strutStyle']), textAlign: ArgumentDecoders.enumValue<TextAlign>(TextAlign.values, source, ['textAlign']), textDirection: ArgumentDecoders.enumValue<TextDirection>(TextDirection.values, source, ['textDirection']), locale: ArgumentDecoders.locale(source, ['locale']), softWrap: source.v<bool>(['softWrap']), overflow: ArgumentDecoders.enumValue<TextOverflow>(TextOverflow.values, source, ['overflow']), textScaler: textScaleFactor == null ? null : TextScaler.linear(textScaleFactor), maxLines: source.v<int>(['maxLines']), semanticsLabel: source.v<String>(['semanticsLabel']), textWidthBasis: ArgumentDecoders.enumValue<TextWidthBasis>(TextWidthBasis.values, source, ['textWidthBasis']), textHeightBehavior: ArgumentDecoders.textHeightBehavior(source, ['textHeightBehavior']), ); }, 'Wrap': (BuildContext context, DataSource source) { return Wrap( direction: ArgumentDecoders.enumValue<Axis>(Axis.values, source, ['direction']) ?? Axis.horizontal, alignment: ArgumentDecoders.enumValue<WrapAlignment>(WrapAlignment.values, source, ['alignment']) ?? WrapAlignment.start, spacing: source.v<double>(['spacing']) ?? 0.0, runAlignment: ArgumentDecoders.enumValue<WrapAlignment>(WrapAlignment.values, source, ['runAlignment']) ?? WrapAlignment.start, runSpacing: source.v<double>(['runSpacing']) ?? 0.0, crossAxisAlignment: ArgumentDecoders.enumValue<WrapCrossAlignment>(WrapCrossAlignment.values, source, ['crossAxisAlignment']) ?? WrapCrossAlignment.start, textDirection: ArgumentDecoders.enumValue<TextDirection>(TextDirection.values, source, ['textDirection']), verticalDirection: ArgumentDecoders.enumValue<VerticalDirection>(VerticalDirection.values, source, ['verticalDirection']) ?? VerticalDirection.down, clipBehavior: ArgumentDecoders.enumValue<Clip>(Clip.values, source, ['clipBehavior']) ?? Clip.none, children: source.childList(['children']), ); }, };
packages/packages/rfw/lib/src/flutter/core_widgets.dart/0
{ "file_path": "packages/packages/rfw/lib/src/flutter/core_widgets.dart", "repo_id": "packages", "token_count": 11598 }
1,041
// 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:flutter/foundation.dart'; // Detects if we're running the tests on the main channel. // // This is useful for _tests_ that depend on _Flutter_ features that have not // yet rolled to stable. Avoid using this to skip tests of _RFW_ features that // aren't compatible with stable. Those should wait until the stable release // channel is updated so that RFW can be compatible with it. bool get isMainChannel { assert(!kIsWeb, 'isMainChannel is not available on web'); return !Platform.environment.containsKey('CHANNEL') || Platform.environment['CHANNEL'] == 'main' || Platform.environment['CHANNEL'] == 'master'; } // See Contributing section of README.md file. final bool runGoldens = !kIsWeb && Platform.isLinux && isMainChannel;
packages/packages/rfw/test/utils.dart/0
{ "file_path": "packages/packages/rfw/test/utils.dart", "repo_id": "packages", "token_count": 272 }
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 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:shared_preferences_platform_interface/shared_preferences_platform_interface.dart'; import 'package:shared_preferences_platform_interface/types.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); group('SharedPreferencesAndroid', () { const Map<String, Object> flutterTestValues = <String, Object>{ 'flutter.String': 'hello world', 'flutter.Bool': true, 'flutter.Int': 42, 'flutter.Double': 3.14159, 'flutter.StringList': <String>['foo', 'bar'], }; const Map<String, Object> prefixTestValues = <String, Object>{ 'prefix.String': 'hello world', 'prefix.Bool': true, 'prefix.Int': 42, 'prefix.Double': 3.14159, 'prefix.StringList': <String>['foo', 'bar'], }; const Map<String, Object> nonPrefixTestValues = <String, Object>{ 'String': 'hello world', 'Bool': true, 'Int': 42, 'Double': 3.14159, 'StringList': <String>['foo', 'bar'], }; final Map<String, Object> allTestValues = <String, Object>{}; allTestValues.addAll(flutterTestValues); allTestValues.addAll(prefixTestValues); allTestValues.addAll(nonPrefixTestValues); late SharedPreferencesStorePlatform preferences; setUp(() async { preferences = SharedPreferencesStorePlatform.instance; }); tearDown(() async { await preferences.clearWithParameters( ClearParameters( filter: PreferencesFilter(prefix: ''), ), ); }); testWidgets('reading', (WidgetTester _) async { final Map<String, Object> values = await preferences.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: ''), ), ); expect(values['String'], isNull); expect(values['Bool'], isNull); expect(values['Int'], isNull); expect(values['Double'], isNull); expect(values['StringList'], isNull); }); Future<void> addData() async { await preferences.setValue('String', 'String', allTestValues['String']!); await preferences.setValue('Bool', 'Bool', allTestValues['Bool']!); await preferences.setValue('Int', 'Int', allTestValues['Int']!); await preferences.setValue('Double', 'Double', allTestValues['Double']!); await preferences.setValue( 'StringList', 'StringList', allTestValues['StringList']!); await preferences.setValue( 'String', 'prefix.String', allTestValues['prefix.String']!); await preferences.setValue( 'Bool', 'prefix.Bool', allTestValues['prefix.Bool']!); await preferences.setValue( 'Int', 'prefix.Int', allTestValues['prefix.Int']!); await preferences.setValue( 'Double', 'prefix.Double', allTestValues['prefix.Double']!); await preferences.setValue('StringList', 'prefix.StringList', allTestValues['prefix.StringList']!); await preferences.setValue( 'String', 'flutter.String', allTestValues['flutter.String']!); await preferences.setValue( 'Bool', 'flutter.Bool', allTestValues['flutter.Bool']!); await preferences.setValue( 'Int', 'flutter.Int', allTestValues['flutter.Int']!); await preferences.setValue( 'Double', 'flutter.Double', allTestValues['flutter.Double']!); await preferences.setValue('StringList', 'flutter.StringList', allTestValues['flutter.StringList']!); } testWidgets('getAllWithPrefix', (WidgetTester _) async { await Future.wait(<Future<bool>>[ preferences.setValue( 'String', 'prefix.String', allTestValues['prefix.String']!), preferences.setValue( 'Bool', 'prefix.Bool', allTestValues['prefix.Bool']!), preferences.setValue('Int', 'prefix.Int', allTestValues['prefix.Int']!), preferences.setValue( 'Double', 'prefix.Double', allTestValues['prefix.Double']!), preferences.setValue('StringList', 'prefix.StringList', allTestValues['prefix.StringList']!), preferences.setValue( 'String', 'flutter.String', allTestValues['flutter.String']!), preferences.setValue( 'Bool', 'flutter.Bool', allTestValues['flutter.Bool']!), preferences.setValue( 'Int', 'flutter.Int', allTestValues['flutter.Int']!), preferences.setValue( 'Double', 'flutter.Double', allTestValues['flutter.Double']!), preferences.setValue('StringList', 'flutter.StringList', allTestValues['flutter.StringList']!) ]); final Map<String, Object> values = // ignore: deprecated_member_use await preferences.getAllWithPrefix('prefix.'); expect(values['prefix.String'], allTestValues['prefix.String']); expect(values['prefix.Bool'], allTestValues['prefix.Bool']); expect(values['prefix.Int'], allTestValues['prefix.Int']); expect(values['prefix.Double'], allTestValues['prefix.Double']); expect(values['prefix.StringList'], allTestValues['prefix.StringList']); }); group('withPrefix', () { testWidgets('clearWithPrefix', (WidgetTester _) async { await Future.wait(<Future<bool>>[ preferences.setValue( 'String', 'prefix.String', allTestValues['prefix.String']!), preferences.setValue( 'Bool', 'prefix.Bool', allTestValues['prefix.Bool']!), preferences.setValue( 'Int', 'prefix.Int', allTestValues['prefix.Int']!), preferences.setValue( 'Double', 'prefix.Double', allTestValues['prefix.Double']!), preferences.setValue('StringList', 'prefix.StringList', allTestValues['prefix.StringList']!), preferences.setValue( 'String', 'flutter.String', allTestValues['flutter.String']!), preferences.setValue( 'Bool', 'flutter.Bool', allTestValues['flutter.Bool']!), preferences.setValue( 'Int', 'flutter.Int', allTestValues['flutter.Int']!), preferences.setValue( 'Double', 'flutter.Double', allTestValues['flutter.Double']!), preferences.setValue('StringList', 'flutter.StringList', allTestValues['flutter.StringList']!) ]); // ignore: deprecated_member_use await preferences.clearWithPrefix('prefix.'); Map<String, Object> values = // ignore: deprecated_member_use await preferences.getAllWithPrefix('prefix.'); expect(values['prefix.String'], null); expect(values['prefix.Bool'], null); expect(values['prefix.Int'], null); expect(values['prefix.Double'], null); expect(values['prefix.StringList'], null); // ignore: deprecated_member_use values = await preferences.getAllWithPrefix('flutter.'); expect(values['flutter.String'], allTestValues['flutter.String']); expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); expect( values['flutter.StringList'], allTestValues['flutter.StringList']); }); testWidgets('getAllWithNoPrefix', (WidgetTester _) async { await Future.wait(<Future<bool>>[ preferences.setValue('String', 'String', allTestValues['String']!), preferences.setValue('Bool', 'Bool', allTestValues['Bool']!), preferences.setValue('Int', 'Int', allTestValues['Int']!), preferences.setValue('Double', 'Double', allTestValues['Double']!), preferences.setValue( 'StringList', 'StringList', allTestValues['StringList']!), preferences.setValue( 'String', 'flutter.String', allTestValues['flutter.String']!), preferences.setValue( 'Bool', 'flutter.Bool', allTestValues['flutter.Bool']!), preferences.setValue( 'Int', 'flutter.Int', allTestValues['flutter.Int']!), preferences.setValue( 'Double', 'flutter.Double', allTestValues['flutter.Double']!), preferences.setValue('StringList', 'flutter.StringList', allTestValues['flutter.StringList']!) ]); final Map<String, Object> values = // ignore: deprecated_member_use await preferences.getAllWithPrefix(''); expect(values['String'], allTestValues['String']); expect(values['Bool'], allTestValues['Bool']); expect(values['Int'], allTestValues['Int']); expect(values['Double'], allTestValues['Double']); expect(values['StringList'], allTestValues['StringList']); expect(values['flutter.String'], allTestValues['flutter.String']); expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); expect( values['flutter.StringList'], allTestValues['flutter.StringList']); }); testWidgets('clearWithNoPrefix', (WidgetTester _) async { await Future.wait(<Future<bool>>[ preferences.setValue('String', 'String', allTestValues['String']!), preferences.setValue('Bool', 'Bool', allTestValues['Bool']!), preferences.setValue('Int', 'Int', allTestValues['Int']!), preferences.setValue('Double', 'Double', allTestValues['Double']!), preferences.setValue( 'StringList', 'StringList', allTestValues['StringList']!), preferences.setValue( 'String', 'flutter.String', allTestValues['flutter.String']!), preferences.setValue( 'Bool', 'flutter.Bool', allTestValues['flutter.Bool']!), preferences.setValue( 'Int', 'flutter.Int', allTestValues['flutter.Int']!), preferences.setValue( 'Double', 'flutter.Double', allTestValues['flutter.Double']!), preferences.setValue('StringList', 'flutter.StringList', allTestValues['flutter.StringList']!) ]); // ignore: deprecated_member_use await preferences.clearWithPrefix(''); final Map<String, Object> values = // ignore: deprecated_member_use await preferences.getAllWithPrefix(''); expect(values['String'], null); expect(values['Bool'], null); expect(values['Int'], null); expect(values['Double'], null); expect(values['StringList'], null); expect(values['flutter.String'], null); expect(values['flutter.Bool'], null); expect(values['flutter.Int'], null); expect(values['flutter.Double'], null); expect(values['flutter.StringList'], null); }); }); testWidgets('get all with prefix', (WidgetTester _) async { await addData(); final Map<String, Object> values = await preferences.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: 'prefix.'), ), ); expect(values['prefix.String'], allTestValues['prefix.String']); expect(values['prefix.Bool'], allTestValues['prefix.Bool']); expect(values['prefix.Int'], allTestValues['prefix.Int']); expect(values['prefix.Double'], allTestValues['prefix.Double']); expect(values['prefix.StringList'], allTestValues['prefix.StringList']); }); testWidgets('get all with allow list', (WidgetTester _) async { await addData(); final Map<String, Object> values = await preferences.getAllWithParameters( GetAllParameters( filter: PreferencesFilter( prefix: 'prefix.', allowList: <String>{'prefix.String'}, ), ), ); expect(values['prefix.String'], allTestValues['prefix.String']); expect(values['prefix.Bool'], null); expect(values['prefix.Int'], null); expect(values['prefix.Double'], null); expect(values['prefix.StringList'], null); }); testWidgets('getAllWithNoPrefix', (WidgetTester _) async { await addData(); final Map<String, Object> values = await preferences.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: ''), ), ); expect(values['String'], allTestValues['String']); expect(values['Bool'], allTestValues['Bool']); expect(values['Int'], allTestValues['Int']); expect(values['Double'], allTestValues['Double']); expect(values['StringList'], allTestValues['StringList']); expect(values['flutter.String'], allTestValues['flutter.String']); expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); expect(values['flutter.StringList'], allTestValues['flutter.StringList']); }); testWidgets('clearWithParameters', (WidgetTester _) async { await addData(); await preferences.clearWithParameters( ClearParameters( filter: PreferencesFilter(prefix: 'prefix.'), ), ); Map<String, Object> values = await preferences.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: 'prefix.'), ), ); expect(values['prefix.String'], null); expect(values['prefix.Bool'], null); expect(values['prefix.Int'], null); expect(values['prefix.Double'], null); expect(values['prefix.StringList'], null); values = await preferences.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: 'flutter.'), ), ); expect(values['flutter.String'], allTestValues['flutter.String']); expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); expect(values['flutter.StringList'], allTestValues['flutter.StringList']); }); testWidgets('clearWithParameters with allow list', (WidgetTester _) async { await addData(); await preferences.clearWithParameters( ClearParameters( filter: PreferencesFilter( prefix: 'prefix.', allowList: <String>{ 'prefix.Double', 'prefix.Int', 'prefix.Bool', 'prefix.String', }, ), ), ); Map<String, Object> values = await preferences.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: 'prefix.'), ), ); expect(values['prefix.String'], null); expect(values['prefix.Bool'], null); expect(values['prefix.Int'], null); expect(values['prefix.Double'], null); expect(values['prefix.StringList'], allTestValues['prefix.StringList']); values = await preferences.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: 'flutter.'), ), ); expect(values['flutter.String'], allTestValues['flutter.String']); expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); expect(values['flutter.StringList'], allTestValues['flutter.StringList']); }); testWidgets('clearWithNoPrefix', (WidgetTester _) async { await addData(); await preferences.clearWithParameters( ClearParameters( filter: PreferencesFilter(prefix: ''), ), ); final Map<String, Object> values = await preferences.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: ''), ), ); expect(values['String'], null); expect(values['Bool'], null); expect(values['Int'], null); expect(values['Double'], null); expect(values['StringList'], null); expect(values['flutter.String'], null); expect(values['flutter.Bool'], null); expect(values['flutter.Int'], null); expect(values['flutter.Double'], null); expect(values['flutter.StringList'], null); }); testWidgets('getAll', (WidgetTester _) async { await preferences.setValue( 'String', 'flutter.String', allTestValues['flutter.String']!); await preferences.setValue( 'Bool', 'flutter.Bool', allTestValues['flutter.Bool']!); await preferences.setValue( 'Int', 'flutter.Int', allTestValues['flutter.Int']!); await preferences.setValue( 'Double', 'flutter.Double', allTestValues['flutter.Double']!); await preferences.setValue('StringList', 'flutter.StringList', allTestValues['flutter.StringList']!); final Map<String, Object> values = await preferences.getAll(); expect(values['flutter.String'], allTestValues['flutter.String']); expect(values['flutter.Bool'], allTestValues['flutter.Bool']); expect(values['flutter.Int'], allTestValues['flutter.Int']); expect(values['flutter.Double'], allTestValues['flutter.Double']); expect(values['flutter.StringList'], allTestValues['flutter.StringList']); }); testWidgets('remove', (WidgetTester _) async { const String key = 'testKey'; await preferences.setValue( 'String', key, allTestValues['flutter.String']!); await preferences.setValue('Bool', key, allTestValues['flutter.Bool']!); await preferences.setValue('Int', key, allTestValues['flutter.Int']!); await preferences.setValue( 'Double', key, allTestValues['flutter.Double']!); await preferences.setValue( 'StringList', key, allTestValues['flutter.StringList']!); await preferences.remove(key); final Map<String, Object> values = await preferences.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: ''), ), ); expect(values[key], isNull); }); testWidgets('clear', (WidgetTester _) async { await preferences.setValue( 'String', 'flutter.String', allTestValues['flutter.String']!); await preferences.setValue( 'Bool', 'flutter.Bool', allTestValues['flutter.Bool']!); await preferences.setValue( 'Int', 'flutter.Int', allTestValues['flutter.Int']!); await preferences.setValue( 'Double', 'flutter.Double', allTestValues['flutter.Double']!); await preferences.setValue('StringList', 'flutter.StringList', allTestValues['flutter.StringList']!); await preferences.clear(); final Map<String, Object> values = await preferences.getAll(); expect(values['flutter.String'], null); expect(values['flutter.Bool'], null); expect(values['flutter.Int'], null); expect(values['flutter.Double'], null); expect(values['flutter.StringList'], null); }); testWidgets('simultaneous writes', (WidgetTester _) async { final List<Future<bool>> writes = <Future<bool>>[]; const int writeCount = 100; for (int i = 1; i <= writeCount; i++) { writes.add(preferences.setValue('Int', 'Int', i)); } final List<bool> result = await Future.wait(writes, eagerError: true); // All writes should succeed. expect(result.where((bool element) => !element), isEmpty); // The last write should win. final Map<String, Object> values = await preferences.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: ''), ), ); expect(values['Int'], writeCount); }); testWidgets('string clash with lists, big integers and doubles', (WidgetTester _) async { const String key = 'akey'; const String value = 'a string value'; await preferences.clearWithParameters( ClearParameters( filter: PreferencesFilter(prefix: ''), ), ); // Special prefixes used to store datatypes that can't be stored directly // in SharedPreferences as strings instead. const List<String> specialPrefixes = <String>[ // Prefix for lists: 'VGhpcyBpcyB0aGUgcHJlZml4IGZvciBhIGxpc3Qu', // Prefix for big integers: 'VGhpcyBpcyB0aGUgcHJlZml4IGZvciBCaWdJbnRlZ2Vy', // Prefix for doubles: 'VGhpcyBpcyB0aGUgcHJlZml4IGZvciBEb3VibGUu', ]; for (final String prefix in specialPrefixes) { expect(preferences.setValue('String', key, prefix + value), throwsA(isA<PlatformException>())); final Map<String, Object> values = await preferences.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: ''), ), ); expect(values[key], null); } }); }); }
packages/packages/shared_preferences/shared_preferences_android/example/integration_test/shared_preferences_test.dart/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_android/example/integration_test/shared_preferences_test.dart", "repo_id": "packages", "token_count": 8670 }
1,043
<?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>NSPrivacyTrackingDomains</key> <array/> <key>NSPrivacyAccessedAPITypes</key> <array> <dict> <key>NSPrivacyAccessedAPIType</key> <string>NSPrivacyAccessedAPICategoryUserDefaults</string> <key>NSPrivacyAccessedAPITypeReasons</key> <array> <string>1C8F.1</string> </array> </dict> </array> <key>NSPrivacyCollectedDataTypes</key> <array/> <key>NSPrivacyTracking</key> <false/> </dict> </plist>
packages/packages/shared_preferences/shared_preferences_foundation/darwin/Resources/PrivacyInfo.xcprivacy/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_foundation/darwin/Resources/PrivacyInfo.xcprivacy", "repo_id": "packages", "token_count": 279 }
1,044
#include "../../Flutter/Flutter-Debug.xcconfig" #include "Warnings.xcconfig"
packages/packages/shared_preferences/shared_preferences_foundation/example/macos/Runner/Configs/Debug.xcconfig/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_foundation/example/macos/Runner/Configs/Debug.xcconfig", "repo_id": "packages", "token_count": 32 }
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. // Autogenerated from Pigeon (v10.1.6), 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, unnecessary_import // ignore_for_file: avoid_relative_lib_imports 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'; import 'package:flutter_test/flutter_test.dart'; import 'package:shared_preferences_foundation/messages.g.dart'; abstract class TestUserDefaultsApi { static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => TestDefaultBinaryMessengerBinding.instance; static const MessageCodec<Object?> codec = StandardMessageCodec(); void remove(String key); void setBool(String key, bool value); void setDouble(String key, double value); void setValue(String key, Object value); Map<String?, Object?> getAll(String prefix, List<String?>? allowList); bool clear(String prefix, List<String?>? allowList); static void setup(TestUserDefaultsApi? api, {BinaryMessenger? binaryMessenger}) { { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.remove', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.remove was null.'); final List<Object?> args = (message as List<Object?>?)!; final String? arg_key = (args[0] as String?); assert(arg_key != null, 'Argument for dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.remove was null, expected non-null String.'); api.remove(arg_key!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.setBool', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.setBool was null.'); final List<Object?> args = (message as List<Object?>?)!; final String? arg_key = (args[0] as String?); assert(arg_key != null, 'Argument for dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.setBool was null, expected non-null String.'); final bool? arg_value = (args[1] as bool?); assert(arg_value != null, 'Argument for dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.setBool was null, expected non-null bool.'); api.setBool(arg_key!, arg_value!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.setDouble', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.setDouble was null.'); final List<Object?> args = (message as List<Object?>?)!; final String? arg_key = (args[0] as String?); assert(arg_key != null, 'Argument for dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.setDouble was null, expected non-null String.'); final double? arg_value = (args[1] as double?); assert(arg_value != null, 'Argument for dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.setDouble was null, expected non-null double.'); api.setDouble(arg_key!, arg_value!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.setValue', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.setValue was null.'); final List<Object?> args = (message as List<Object?>?)!; final String? arg_key = (args[0] as String?); assert(arg_key != null, 'Argument for dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.setValue was null, expected non-null String.'); final Object? arg_value = (args[1] as Object?); assert(arg_value != null, 'Argument for dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.setValue was null, expected non-null Object.'); api.setValue(arg_key!, arg_value!); return <Object?>[]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.getAll', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.getAll was null.'); final List<Object?> args = (message as List<Object?>?)!; final String? arg_prefix = (args[0] as String?); assert(arg_prefix != null, 'Argument for dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.getAll was null, expected non-null String.'); final List<String?>? arg_allowList = (args[1] as List<Object?>?)?.cast<String?>(); final Map<String?, Object?> output = api.getAll(arg_prefix!, arg_allowList); return <Object?>[output]; }); } } { final BasicMessageChannel<Object?> channel = BasicMessageChannel<Object?>( 'dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.clear', codec, binaryMessenger: binaryMessenger); if (api == null) { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, null); } else { _testBinaryMessengerBinding!.defaultBinaryMessenger .setMockDecodedMessageHandler<Object?>(channel, (Object? message) async { assert(message != null, 'Argument for dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.clear was null.'); final List<Object?> args = (message as List<Object?>?)!; final String? arg_prefix = (args[0] as String?); assert(arg_prefix != null, 'Argument for dev.flutter.pigeon.shared_preferences_foundation.UserDefaultsApi.clear was null, expected non-null String.'); final List<String?>? arg_allowList = (args[1] as List<Object?>?)?.cast<String?>(); final bool output = api.clear(arg_prefix!, arg_allowList); return <Object?>[output]; }); } } } }
packages/packages/shared_preferences/shared_preferences_foundation/test/test_api.g.dart/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_foundation/test/test_api.g.dart", "repo_id": "packages", "token_count": 3795 }
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. import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:shared_preferences_platform_interface/method_channel_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(); group(MethodChannelSharedPreferencesStore, () { const MethodChannel channel = MethodChannel( 'plugins.flutter.io/shared_preferences', ); const Map<String, Object> flutterTestValues = <String, Object>{ 'flutter.String': 'hello world', 'flutter.Bool': true, 'flutter.Int': 42, 'flutter.Double': 3.14159, 'flutter.StringList': <String>['foo', 'bar'], }; const Map<String, Object> prefixTestValues = <String, Object>{ 'prefix.String': 'hello world', 'prefix.Bool': true, 'prefix.Int': 42, 'prefix.Double': 3.14159, 'prefix.StringList': <String>['foo', 'bar'], }; const Map<String, Object> nonPrefixTestValues = <String, Object>{ 'String': 'hello world', 'Bool': true, 'Int': 42, 'Double': 3.14159, 'StringList': <String>['foo', 'bar'], }; final Map<String, Object> allTestValues = <String, Object>{}; allTestValues.addAll(flutterTestValues); allTestValues.addAll(prefixTestValues); allTestValues.addAll(nonPrefixTestValues); late InMemorySharedPreferencesStore testData; final List<MethodCall> log = <MethodCall>[]; late MethodChannelSharedPreferencesStore store; setUp(() async { testData = InMemorySharedPreferencesStore.empty(); Map<String, Object?> getArgumentDictionary(MethodCall call) { return (call.arguments as Map<Object?, Object?>) .cast<String, Object?>(); } TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler(channel, (MethodCall methodCall) async { log.add(methodCall); if (methodCall.method == 'getAll') { return testData.getAll(); } if (methodCall.method == 'getAllWithParameters') { final Map<String, Object?> arguments = getArgumentDictionary(methodCall); final String prefix = arguments['prefix']! as String; Set<String>? allowSet; final List<dynamic>? allowList = arguments['allowList'] as List<dynamic>?; if (allowList != null) { allowSet = <String>{}; for (final dynamic key in allowList) { allowSet.add(key as String); } } return testData.getAllWithParameters( GetAllParameters( filter: PreferencesFilter( prefix: prefix, allowList: allowSet, ), ), ); } if (methodCall.method == 'remove') { final Map<String, Object?> arguments = getArgumentDictionary(methodCall); final String key = arguments['key']! as String; return testData.remove(key); } if (methodCall.method == 'clear') { return testData.clear(); } if (methodCall.method == 'clearWithParameters') { final Map<String, Object?> arguments = getArgumentDictionary(methodCall); final String prefix = arguments['prefix']! as String; Set<String>? allowSet; final List<dynamic>? allowList = arguments['allowList'] as List<dynamic>?; if (allowList != null) { allowSet = <String>{}; for (final dynamic key in allowList) { allowSet.add(key as String); } } return testData.clearWithParameters( ClearParameters( filter: PreferencesFilter(prefix: prefix, allowList: allowSet), ), ); } final RegExp setterRegExp = RegExp(r'set(.*)'); final Match? match = setterRegExp.matchAsPrefix(methodCall.method); if (match?.groupCount == 1) { final String valueType = match!.group(1)!; final Map<String, Object?> arguments = getArgumentDictionary(methodCall); final String key = arguments['key']! as String; final Object value = arguments['value']!; return testData.setValue(valueType, key, value); } fail('Unexpected method call: ${methodCall.method}'); }); store = MethodChannelSharedPreferencesStore(); log.clear(); }); tearDown(() async { await testData.clear(); }); test('getAll', () async { testData = InMemorySharedPreferencesStore.withData(allTestValues); expect(await store.getAll(), flutterTestValues); expect(log.single.method, 'getAll'); }); test('getAllWithParameters with Prefix', () async { testData = InMemorySharedPreferencesStore.withData(allTestValues); expect( await store.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: 'prefix.'), ), ), prefixTestValues); expect(log.single.method, 'getAllWithParameters'); }); test('getAllWithParameters with allow list', () async { testData = InMemorySharedPreferencesStore.withData(allTestValues); final Map<String, Object> data = await store.getAllWithParameters( GetAllParameters( filter: PreferencesFilter( prefix: 'prefix.', allowList: <String>{'prefix.Bool'}, ), ), ); expect(data.length, 1); expect(data['prefix.Bool'], true); expect(log.single.method, 'getAllWithParameters'); }); test('remove', () async { testData = InMemorySharedPreferencesStore.withData(allTestValues); expect(await store.remove('flutter.String'), true); expect(await store.remove('flutter.Bool'), true); expect(await store.remove('flutter.Int'), true); expect(await store.remove('flutter.Double'), true); expect(await testData.getAll(), <String, dynamic>{ 'flutter.StringList': <String>['foo', 'bar'], }); expect(log, hasLength(4)); for (final MethodCall call in log) { expect(call.method, 'remove'); } }); test('setValue', () async { expect(await testData.getAll(), isEmpty); for (final String key in allTestValues.keys) { final Object value = allTestValues[key]!; expect(await store.setValue(key.split('.').last, key, value), true); } expect(await testData.getAll(), flutterTestValues); expect(log, hasLength(15)); expect(log[0].method, 'setString'); expect(log[1].method, 'setBool'); expect(log[2].method, 'setInt'); expect(log[3].method, 'setDouble'); expect(log[4].method, 'setStringList'); }); test('clear', () async { testData = InMemorySharedPreferencesStore.withData(allTestValues); expect(await testData.getAll(), isNotEmpty); expect(await store.clear(), true); expect(await testData.getAll(), isEmpty); expect(log.single.method, 'clear'); }); test('clearWithParameters with Prefix', () async { testData = InMemorySharedPreferencesStore.withData(allTestValues); expect( await testData.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: 'prefix.'), ), ), isNotEmpty); expect( await store.clearWithParameters( ClearParameters( filter: PreferencesFilter(prefix: 'prefix.'), ), ), true); expect( await testData.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: 'prefix.'), ), ), isEmpty); }); test('getAllWithParameters with no Prefix', () async { testData = InMemorySharedPreferencesStore.withData(allTestValues); expect( await testData.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: ''), ), ), hasLength(15)); }); test('clearWithNoPrefix', () async { testData = InMemorySharedPreferencesStore.withData(allTestValues); expect( await testData.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: ''), ), ), isNotEmpty); expect( await store.clearWithParameters( ClearParameters( filter: PreferencesFilter(prefix: ''), ), ), true); expect( await testData.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: ''), ), ), isEmpty); }); test('clearWithParameters with allow list', () async { testData = InMemorySharedPreferencesStore.withData(allTestValues); expect( await testData.getAllWithParameters( GetAllParameters( filter: PreferencesFilter(prefix: 'prefix.'), ), ), isNotEmpty); expect( await store.clearWithParameters( ClearParameters( filter: PreferencesFilter( prefix: 'prefix.', allowList: <String>{'prefix.String'}, ), ), ), true); expect( (await testData.getAllWithParameters(GetAllParameters( filter: PreferencesFilter(prefix: 'prefix.')))) .length, 4); }); }); }
packages/packages/shared_preferences/shared_preferences_platform_interface/test/method_channel_shared_preferences_test.dart/0
{ "file_path": "packages/packages/shared_preferences/shared_preferences_platform_interface/test/method_channel_shared_preferences_test.dart", "repo_id": "packages", "token_count": 4400 }
1,047
// 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/widgets.dart'; import 'table.dart'; /// The relative position of a child in a [TableViewport] in relation /// to other children of the viewport, in terms of rows and columns. /// /// This subclass translates the abstract [ChildVicinity.xIndex] and /// [ChildVicinity.yIndex] into terms of rows and columns for ease of use within /// the context of a [TableView]. @immutable class TableVicinity extends ChildVicinity { /// Creates a reference to a child in a [TableView], with the [xIndex] and /// [yIndex] converted to terms of [row] and [column]. const TableVicinity({ required int row, required int column, }) : super(xIndex: column, yIndex: row); /// The row index of the child in the [TableView]. /// /// Equivalent to the [yIndex]. int get row => yIndex; /// The column index of the child in the [TableView]. /// /// Equivalent to the [xIndex]. int get column => xIndex; /// The origin vicinity of the [TableView], (0,0). static const TableVicinity zero = TableVicinity(row: 0, column: 0); /// Returns a new [TableVicinity], copying over the row and column fields with /// those provided, or maintaining the original values. TableVicinity copyWith({ int? row, int? column, }) { return TableVicinity( row: row ?? this.row, column: column ?? this.column, ); } @override String toString() => '(row: $row, column: $column)'; } /// Parent data structure used by [RenderTableViewport]. class TableViewParentData extends TwoDimensionalViewportParentData { /// Converts the [ChildVicinity] to a [TableVicinity] for ease of use. TableVicinity get tableVicinity => vicinity as TableVicinity; /// Represents the row index where a merged cell in the table begins. /// /// Defaults to null, meaning a non-merged cell. A value must be provided if /// a value is provided for [rowMergeSpan]. int? rowMergeStart; /// Represents the number of rows spanned by a merged cell. /// /// Defaults to null, meaning the cell is not merged. A value must be provided /// if a value is provided for [rowMergeStart]. int? rowMergeSpan; /// Represents the column index where a merged cell in the table begins. /// /// Defaults to null, meaning a non-merged cell. A value must be provided if /// a value is provided for [columnMergeSpan]. int? columnMergeStart; /// Represents the number of columns spanned by a merged cell. /// /// Defaults to null, meaning the cell is not merged. A value must be provided /// if a value is provided for [columnMergeStart]. int? columnMergeSpan; @override String toString() { String mergeDetails = ''; if (rowMergeStart != null || columnMergeStart != null) { mergeDetails += ', merged'; } if (rowMergeStart != null) { mergeDetails += ', rowMergeStart=$rowMergeStart, ' 'rowMergeSpan=$rowMergeSpan'; } if (columnMergeStart != null) { mergeDetails += ', columnMergeStart=$columnMergeStart, ' 'columnMergeSpan=$columnMergeSpan'; } return super.toString() + mergeDetails; } } /// Creates a cell of the [TableView], along with information regarding merged /// cells and [RepaintBoundary]s. /// /// When merging cells in a [TableView], the same child should be returned from /// every vicinity the merged cell contains. The `build` method will only be /// called once for a merged cell, but since the table's children are lazily /// laid out, returning the same child ensures the merged cell can be built no /// matter which part of it is visible. class TableViewCell extends StatelessWidget { /// Creates a widget that controls how a child of a [TableView] spans across /// multiple rows or columns. const TableViewCell({ super.key, this.rowMergeStart, this.rowMergeSpan, this.columnMergeStart, this.columnMergeSpan, this.addRepaintBoundaries = true, required this.child, }) : assert( (rowMergeStart == null && rowMergeSpan == null) || (rowMergeStart != null && rowMergeSpan != null), 'Row merge start and span must both be set, or both unset.', ), assert(rowMergeStart == null || rowMergeStart >= 0), assert(rowMergeSpan == null || rowMergeSpan > 0), assert( (columnMergeStart == null && columnMergeSpan == null) || (columnMergeStart != null && columnMergeSpan != null), 'Column merge start and span must both be set, or both unset.', ), assert(columnMergeStart == null || columnMergeStart >= 0), assert(columnMergeSpan == null || columnMergeSpan > 0); /// The child contained in this cell of the [TableView]. final Widget child; /// Represents the row index where a merged cell in the table begins. /// /// Defaults to null, meaning a non-merged cell. A value must be provided if /// a value is provided for [rowMergeSpan]. final int? rowMergeStart; /// Represents the number of rows spanned by a merged cell. /// /// Defaults to null, meaning the cell is not merged. A value must be provided /// if a value is provided for [rowMergeStart]. final int? rowMergeSpan; /// Represents the column index where a merged cell in the table begins. /// /// Defaults to null, meaning a non-merged cell. A value must be provided if /// a value is provided for [columnMergeSpan]. final int? columnMergeStart; /// Represents the number of columns spanned by a merged cell. /// /// Defaults to null, meaning the cell is not merged. A value must be provided /// if a value is provided for [columnMergeStart]. final int? columnMergeSpan; /// Whether to wrap each child in a [RepaintBoundary]. /// /// Typically, children in a scrolling container are wrapped in repaint /// boundaries so that they do not need to be repainted as the list scrolls. /// If the children are easy to repaint (e.g., solid color blocks or a short /// snippet of text), it might be more efficient to not add a repaint boundary /// and instead always repaint the children during scrolling. /// /// Defaults to true. final bool addRepaintBoundaries; @override Widget build(BuildContext context) { Widget child = this.child; if (addRepaintBoundaries) { child = RepaintBoundary(child: child); } return _TableViewCell( rowMergeStart: rowMergeStart, rowMergeSpan: rowMergeSpan, columnMergeStart: columnMergeStart, columnMergeSpan: columnMergeSpan, child: child, ); } } class _TableViewCell extends ParentDataWidget<TableViewParentData> { const _TableViewCell({ this.rowMergeStart, this.rowMergeSpan, this.columnMergeStart, this.columnMergeSpan, required super.child, }); final int? rowMergeStart; final int? rowMergeSpan; final int? columnMergeStart; final int? columnMergeSpan; @override void applyParentData(RenderObject renderObject) { final TableViewParentData parentData = renderObject.parentData! as TableViewParentData; bool needsLayout = false; if (parentData.rowMergeStart != rowMergeStart) { assert(rowMergeStart == null || rowMergeStart! >= 0); parentData.rowMergeStart = rowMergeStart; needsLayout = true; } if (parentData.rowMergeSpan != rowMergeSpan) { assert(rowMergeSpan == null || rowMergeSpan! > 0); parentData.rowMergeSpan = rowMergeSpan; needsLayout = true; } if (parentData.columnMergeStart != columnMergeStart) { assert(columnMergeStart == null || columnMergeStart! >= 0); parentData.columnMergeStart = columnMergeStart; needsLayout = true; } if (parentData.columnMergeSpan != columnMergeSpan) { assert(columnMergeSpan == null || columnMergeSpan! > 0); parentData.columnMergeSpan = columnMergeSpan; needsLayout = true; } if (needsLayout) { renderObject.parent?.markNeedsLayout(); } } @override Type get debugTypicalAncestorWidgetClass => TableViewport; @override void debugFillProperties(DiagnosticPropertiesBuilder properties) { super.debugFillProperties(properties); if (rowMergeStart != null) { properties.add(IntProperty('rowMergeStart', rowMergeStart)); properties.add(IntProperty('rowMergeSpan', rowMergeSpan)); } if (columnMergeStart != null) { properties.add(IntProperty('columnMergeStart', columnMergeStart)); properties.add(IntProperty('columnMergeSpan', columnMergeSpan)); } } }
packages/packages/two_dimensional_scrollables/lib/src/table_view/table_cell.dart/0
{ "file_path": "packages/packages/two_dimensional_scrollables/lib/src/table_view/table_cell.dart", "repo_id": "packages", "token_count": 2901 }
1,048
name: url_launcher_example description: Demonstrates how to use the url_launcher plugin. publish_to: none environment: sdk: ">=3.1.0 <4.0.0" flutter: ">=3.13.0" dependencies: flutter: sdk: flutter path: ^1.8.0 url_launcher: # When depending on this package from a real application you should use: # url_launcher: ^x.y.z # See https://dart.dev/tools/pub/dependencies#version-constraints # The example app is bundled with the plugin so we use a path dependency on # the parent directory to use the current plugin's version. path: ../ dev_dependencies: build_runner: ^2.1.10 flutter_test: sdk: flutter integration_test: sdk: flutter mockito: 5.4.4 plugin_platform_interface: ^2.1.7 flutter: uses-material-design: true
packages/packages/url_launcher/url_launcher/example/pubspec.yaml/0
{ "file_path": "packages/packages/url_launcher/url_launcher/example/pubspec.yaml", "repo_id": "packages", "token_count": 299 }
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. package io.flutter.plugins.urllauncher; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.provider.Browser; import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import androidx.browser.customtabs.CustomTabsClient; import androidx.browser.customtabs.CustomTabsIntent; import io.flutter.plugins.urllauncher.Messages.BrowserOptions; import io.flutter.plugins.urllauncher.Messages.UrlLauncherApi; import io.flutter.plugins.urllauncher.Messages.WebViewOptions; import java.util.Collections; import java.util.Locale; import java.util.Map; /** Implements the Pigeon-defined interface for calls from Dart. */ final class UrlLauncher implements UrlLauncherApi { @VisibleForTesting interface IntentResolver { String getHandlerComponentName(@NonNull Intent intent); } private static final String TAG = "UrlLauncher"; private final @NonNull Context applicationContext; private final @NonNull IntentResolver intentResolver; private @Nullable Activity activity; /** * Creates an instance that uses {@code intentResolver} to look up the handler for intents. This * is to allow injecting an alternate resolver for unit testing. */ @VisibleForTesting UrlLauncher(@NonNull Context context, @NonNull IntentResolver intentResolver) { this.applicationContext = context; this.intentResolver = intentResolver; } UrlLauncher(@NonNull Context context) { this( context, intent -> { ComponentName componentName = intent.resolveActivity(context.getPackageManager()); return componentName == null ? null : componentName.toShortString(); }); } void setActivity(@Nullable Activity activity) { this.activity = activity; } @Override public @NonNull Boolean canLaunchUrl(@NonNull String url) { Intent launchIntent = new Intent(Intent.ACTION_VIEW); launchIntent.setData(Uri.parse(url)); String componentName = intentResolver.getHandlerComponentName(launchIntent); if (BuildConfig.DEBUG) { Log.i(TAG, "component name for " + url + " is " + componentName); } if (componentName == null) { return false; } else { // Ignore the emulator fallback activity. return !"{com.android.fallback/com.android.fallback.Fallback}".equals(componentName); } } @Override public @NonNull Boolean launchUrl(@NonNull String url, @NonNull Map<String, String> headers) { ensureActivity(); assert activity != null; Intent launchIntent = new Intent(Intent.ACTION_VIEW) .setData(Uri.parse(url)) .putExtra(Browser.EXTRA_HEADERS, extractBundle(headers)); try { activity.startActivity(launchIntent); } catch (ActivityNotFoundException e) { return false; } return true; } @Override public @NonNull Boolean openUrlInApp( @NonNull String url, @NonNull Boolean allowCustomTab, @NonNull WebViewOptions webViewOptions, @NonNull BrowserOptions browserOptions) { ensureActivity(); assert activity != null; Bundle headersBundle = extractBundle(webViewOptions.getHeaders()); // Try to launch using Custom Tabs if they have the necessary functionality, unless the caller // specifically requested a web view. if (allowCustomTab && !containsRestrictedHeader(webViewOptions.getHeaders())) { Uri uri = Uri.parse(url); if (openCustomTab(activity, uri, headersBundle, browserOptions)) { return true; } } // Fall back to a web view if necessary. Intent launchIntent = WebViewActivity.createIntent( activity, url, webViewOptions.getEnableJavaScript(), webViewOptions.getEnableDomStorage(), headersBundle); try { activity.startActivity(launchIntent); } catch (ActivityNotFoundException e) { return false; } return true; } @Override public void closeWebView() { applicationContext.sendBroadcast(new Intent(WebViewActivity.ACTION_CLOSE)); } @Override public @NonNull Boolean supportsCustomTabs() { return CustomTabsClient.getPackageName(applicationContext, Collections.emptyList()) != null; } private static boolean openCustomTab( @NonNull Context context, @NonNull Uri uri, @NonNull Bundle headersBundle, @NonNull BrowserOptions options) { CustomTabsIntent customTabsIntent = new CustomTabsIntent.Builder().setShowTitle(options.getShowTitle()).build(); customTabsIntent.intent.putExtra(Browser.EXTRA_HEADERS, headersBundle); try { customTabsIntent.launchUrl(context, uri); } catch (ActivityNotFoundException ex) { return false; } return true; } // Checks if headers contains a CORS restricted header. // https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_request_header private static boolean containsRestrictedHeader(Map<String, String> headersMap) { for (String key : headersMap.keySet()) { switch (key.toLowerCase(Locale.US)) { case "accept": case "accept-language": case "content-language": case "content-type": continue; default: return true; } } return false; } private static @NonNull Bundle extractBundle(Map<String, String> headersMap) { final Bundle headersBundle = new Bundle(); for (String key : headersMap.keySet()) { final String value = headersMap.get(key); headersBundle.putString(key, value); } return headersBundle; } private void ensureActivity() { if (activity == null) { throw new Messages.FlutterError( "NO_ACTIVITY", "Launching a URL requires a foreground activity.", null); } } }
packages/packages/url_launcher/url_launcher_android/android/src/main/java/io/flutter/plugins/urllauncher/UrlLauncher.java/0
{ "file_path": "packages/packages/url_launcher/url_launcher_android/android/src/main/java/io/flutter/plugins/urllauncher/UrlLauncher.java", "repo_id": "packages", "token_count": 2131 }
1,050
## 6.2.5 * Adds explicit imports for UIKit. * Updates minimum iOS version to 12.0 and minimum Flutter version to 3.16.6. ## 6.2.4 * Adds privacy manifest. ## 6.2.3 * Updates minimum required plugin_platform_interface version to 2.1.7. ## 6.2.2 * Updates minimum supported SDK version to Flutter 3.10/Dart 3.0. * Fixes lint warnings. ## 6.2.1 * Migrates plugin from Objective-C to Swift. ## 6.2.0 * Implements `supportsMode` and `supportsCloseForMode`. ## 6.1.5 * Adds pub topics to package metadata. * Updates minimum supported SDK version to Flutter 3.7/Dart 2.19. ## 6.1.4 * Updates pigeon to fix warnings with clang 15. ## 6.1.3 * Switches to Pigeon for internal implementation. ## 6.1.2 * Clarifies explanation of endorsement in README. ## 6.1.1 * Updates links for the merge of flutter/plugins into flutter/packages. ## 6.1.0 * Updates minimum Flutter version to 3.3 and iOS 11. ## 6.0.18 * Updates code for stricter lint checks. * Updates minimum Flutter version to 2.10. ## 6.0.17 * Suppresses warnings for pre-iOS-13 codepaths. ## 6.0.16 * Fixes library_private_types_in_public_api, sort_child_properties_last and use_key_in_widget_constructors lint warnings. ## 6.0.15 * Switches to an in-package method channel implementation. ## 6.0.14 * Updates code for new analysis options. * Removes dependency on `meta`. ## 6.0.13 * Splits from `url_launcher` as a federated implementation.
packages/packages/url_launcher/url_launcher_ios/CHANGELOG.md/0
{ "file_path": "packages/packages/url_launcher/url_launcher_ios/CHANGELOG.md", "repo_id": "packages", "token_count": 495 }
1,051
# # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'url_launcher_ios' s.version = '0.0.1' s.summary = 'Flutter plugin for launching a URL.' s.description = <<-DESC A Flutter plugin for making the underlying platform (Android or iOS) launch a URL. DESC s.homepage = 'https://github.com/flutter/packages/tree/main/packages/url_launcher' s.license = { :type => 'BSD', :file => '../LICENSE' } s.author = { 'Flutter Dev Team' => '[email protected]' } s.source = { :http => 'https://github.com/flutter/packages/tree/main/packages/url_launcher/url_launcher_ios' } s.documentation_url = 'https://pub.dev/packages/url_launcher' s.swift_version = '5.0' s.source_files = 'Classes/**/*.swift' s.xcconfig = { 'LIBRARY_SEARCH_PATHS' => '$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)/ $(SDKROOT)/usr/lib/swift', 'LD_RUNPATH_SEARCH_PATHS' => '/usr/lib/swift', } s.dependency 'Flutter' s.platform = :ios, '12.0' s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' } s.resource_bundles = {'url_launcher_ios_privacy' => ['Resources/PrivacyInfo.xcprivacy']} end
packages/packages/url_launcher/url_launcher_ios/ios/url_launcher_ios.podspec/0
{ "file_path": "packages/packages/url_launcher/url_launcher_ios/ios/url_launcher_ios.podspec", "repo_id": "packages", "token_count": 572 }
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 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:url_launcher_macos/src/messages.g.dart'; import 'package:url_launcher_macos/url_launcher_macos.dart'; import 'package:url_launcher_platform_interface/url_launcher_platform_interface.dart'; void main() { group('UrlLauncherMacOS', () { late _FakeUrlLauncherApi api; setUp(() { api = _FakeUrlLauncherApi(); }); test('registers instance', () { UrlLauncherMacOS.registerWith(); expect(UrlLauncherPlatform.instance, isA<UrlLauncherMacOS>()); }); group('canLaunch', () { test('success', () async { final UrlLauncherMacOS launcher = UrlLauncherMacOS(api: api); expect(await launcher.canLaunch('http://example.com/'), true); }); test('failure', () async { final UrlLauncherMacOS launcher = UrlLauncherMacOS(api: api); expect(await launcher.canLaunch('unknown://scheme'), false); }); test('invalid URL returns a PlatformException', () async { final UrlLauncherMacOS launcher = UrlLauncherMacOS(api: api); await expectLater(launcher.canLaunch('invalid://u r l'), throwsA(isA<PlatformException>())); }); test('passes unexpected PlatformExceptions through', () async { final UrlLauncherMacOS launcher = UrlLauncherMacOS(api: api); await expectLater(launcher.canLaunch('unexpectedthrow://someexception'), throwsA(isA<PlatformException>())); }); }); group('launch', () { test('success', () async { final UrlLauncherMacOS launcher = UrlLauncherMacOS(api: api); expect( await launcher.launch( 'http://example.com/', useSafariVC: false, useWebView: false, enableJavaScript: false, enableDomStorage: false, universalLinksOnly: false, headers: const <String, String>{}, ), true); }); test('failure', () async { final UrlLauncherMacOS launcher = UrlLauncherMacOS(api: api); expect( await launcher.launch( 'unknown://scheme', useSafariVC: false, useWebView: false, enableJavaScript: false, enableDomStorage: false, universalLinksOnly: false, headers: const <String, String>{}, ), false); }); test('invalid URL returns a PlatformException', () async { final UrlLauncherMacOS launcher = UrlLauncherMacOS(api: api); await expectLater( launcher.launch( 'invalid://u r l', useSafariVC: false, useWebView: false, enableJavaScript: false, enableDomStorage: false, universalLinksOnly: false, headers: const <String, String>{}, ), throwsA(isA<PlatformException>())); }); test('passes unexpected PlatformExceptions through', () async { final UrlLauncherMacOS launcher = UrlLauncherMacOS(api: api); await expectLater( launcher.launch( 'unexpectedthrow://someexception', useSafariVC: false, useWebView: false, enableJavaScript: false, enableDomStorage: false, universalLinksOnly: false, headers: const <String, String>{}, ), throwsA(isA<PlatformException>())); }); }); group('supportsMode', () { test('returns true for platformDefault', () async { final UrlLauncherMacOS launcher = UrlLauncherMacOS(api: api); expect(await launcher.supportsMode(PreferredLaunchMode.platformDefault), true); }); test('returns true for external application', () async { final UrlLauncherMacOS launcher = UrlLauncherMacOS(api: api); expect( await launcher .supportsMode(PreferredLaunchMode.externalApplication), true); }); test('returns false for other modes', () async { final UrlLauncherMacOS launcher = UrlLauncherMacOS(api: api); expect( await launcher.supportsMode( PreferredLaunchMode.externalNonBrowserApplication), false); expect( await launcher.supportsMode(PreferredLaunchMode.inAppBrowserView), false); expect(await launcher.supportsMode(PreferredLaunchMode.inAppWebView), false); }); }); test('supportsCloseForMode returns false', () async { final UrlLauncherMacOS launcher = UrlLauncherMacOS(api: api); expect( await launcher .supportsCloseForMode(PreferredLaunchMode.platformDefault), false); expect( await launcher .supportsCloseForMode(PreferredLaunchMode.externalApplication), false); }); }); } /// A fake implementation of the host API that reacts to specific schemes. /// /// See _isLaunchable for the behaviors. class _FakeUrlLauncherApi implements UrlLauncherApi { @override Future<UrlLauncherBoolResult> canLaunchUrl(String url) async { return _isLaunchable(url); } @override Future<UrlLauncherBoolResult> launchUrl(String url) async { return _isLaunchable(url); } UrlLauncherBoolResult _isLaunchable(String url) { final String scheme = url.split(':')[0]; switch (scheme) { case 'http': case 'https': return UrlLauncherBoolResult(value: true); case 'invalid': return UrlLauncherBoolResult( value: false, error: UrlLauncherError.invalidUrl); case 'unexpectedthrow': throw PlatformException(code: 'argument_error'); default: return UrlLauncherBoolResult(value: false); } } }
packages/packages/url_launcher/url_launcher_macos/test/url_launcher_macos_test.dart/0
{ "file_path": "packages/packages/url_launcher/url_launcher_macos/test/url_launcher_macos_test.dart", "repo_id": "packages", "token_count": 2639 }
1,053